source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
67,561 | The wikipedia article about Law of Demeter says: The law can be stated simply as "use only one dot". However a simple example of a fluent interface may look like this: static void Main(string[] args){ new ZRLabs.Yael.Pipeline("cat.jpg") .Rotate(90) .Watermark("Monkey") .RoundCorners(100, Color.Bisque) .Save("test.png");} So does this goes together? | Well, the short definition of the law shortens it too much. The real "law" (in reality advice on good API design) basically says: Only access objects you created yourself, or were passed to you as an argument. Do not access objects indirectly through other objects. Methods of fluent interfaces often return the object itself, so they don't violate the law, if you use the object again. Other methods create objects for you, so there's no violation either. Also note that the "law" is only a best practices advice for "classical" APIs. Fluent interfaces are a completely different approach to API design and can't be evaluated with the Law of Demeter. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/67561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
]
} |
67,631 | How do I load a Python module given its full path? Note that the file can be anywhere in the filesystem where the user has access rights. See also: How to import a module given its name as string? | For Python 3.5+ use ( docs ): import importlib.utilimport sysspec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")foo = importlib.util.module_from_spec(spec)sys.modules["module.name"] = foospec.loader.exec_module(foo)foo.MyClass() For Python 3.3 and 3.4 use: from importlib.machinery import SourceFileLoaderfoo = SourceFileLoader("module.name", "/path/to/file.py").load_module()foo.MyClass() (Although this has been deprecated in Python 3.4.) For Python 2 use: import impfoo = imp.load_source('module.name', '/path/to/file.py')foo.MyClass() There are equivalent convenience functions for compiled Python files and DLLs. See also http://bugs.python.org/issue21436 . | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/67631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10286/"
]
} |
67,640 | I know and have Xcode, but I was wondering if there were any other complete development environments that support Objective-C? I'm not looking for solutions with vim or emacs, nor editors like BBEdit that support syntax highlighting, but a full fledged IDE with: code completion compilation debugging refactoring Extra points for being cross platform, supporting vi key bindings and supporting other languages. Note: I've updated and accepted my answer below as Jetbrains has released Early Access for AppCode , their new Objective-C IDE. Since this has been a fairly popular question, I thought it worthwhile to update the information. | I recently learned that Jetbrains the make of my favorite IDE (Idea) may support Objective-C (though it is unclear how much it will work for iPhone/iPad development). See the thread here for early discussion on this. In the last year or two, they have started adding additional language support both in their flagship IDE as well as specialized IDEs (for Ruby, Python, PHP). I guess this is just another step in the process. I for one would love to have another option other than XCode and I couldn't think of one that I'd love more. This is obviously vaporware at the moment, but I think it is something to keep an eye on. This is now a real product, albeit still in Early Access. See here for a the blog on this new product, which will give you pointers to check out the EAP. UPDATE: AppCode has now been released and offers a true alternative to using Xcode for Objective-C and iPhone/iPad/Mac development. It does still rely on Interface Builder for layout and wiring of GUI components and uses the iOS simulator, but all coding, including a slew of refactorings, smart templating and static analysis, is available through App Code. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/67640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284/"
]
} |
67,699 | My master and development branches are tracked remotely on GitHub . How do I clone both these branches? | First, clone a remote Git repository and cd into it: $ git clone git://example.com/myproject$ cd myproject Next, look at the local branches in your repository: $ git branch* master But there are other branches hiding in your repository! See these using the -a flag: $ git branch -a* master remotes/origin/HEAD remotes/origin/master remotes/origin/v1.0-stable remotes/origin/experimental To take a quick peek at an upstream branch, check it out directly: $ git checkout origin/experimental To work on that branch, create a local tracking branch, which is done automatically by: $ git checkout experimentalBranch experimental set up to track remote branch experimental from origin.Switched to a new branch 'experimental' Here, "new branch" simply means that the branch is taken from the index and created locally for you. As the previous line tells you, the branch is being set up to track the remote branch, which usually means the origin/branch_name branch. Your local branches should now show: $ git branch* experimental master You can track more than one remote repository using git remote : $ git remote add win32 git://example.com/users/joe/myproject-win32-port$ git branch -a* master remotes/origin/HEAD remotes/origin/master remotes/origin/v1.0-stable remotes/origin/experimental remotes/win32/master remotes/win32/new-widgets At this point, things are getting pretty crazy, so run gitk to see what's going on: $ gitk --all & | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/67699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117/"
]
} |
67,831 | There are so many different options coming out of microsoft for data access. Which one is the best for scalable apps? Linq Should we be using Linq? It certainly seems easy but if you know your SQL does it really help. Also I hear that you can't run Async queries in ASP.NET using Linq. Therefore I wonder if it is really scalable? Are there any really big sites using Linq (With the possible exception of stackoverflow). Entity Framework Don't hear so much razzmatazz about the Entity Framework. Seems closer to the Object model I'm familure with. Astoria/Dynamic Data Should we be exposing our data as a service? I'm pretty confused and thats before I get into the other ORM products like NHibernate. Any ideas or wisdom on which is better? | I would recommend either NHibernate or Entity Framework. For large sites, I'd use ADO.NET Data Services. I wouldn't do anything large with LINQ to SQL. I think Stack Overflow might end up with some interesting scale problems being 2-tier rather than 3-tier, and they'll also have some trouble refactoring as the physical aspects of the database change and those changes ripple throughout the code. Just a thought. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/67831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6336/"
]
} |
67,835 | Using VBA, how can I: test whether a file exists, and if so, delete it? | 1.) Check here . Basically do this: Function FileExists(ByVal FileToTest As String) As Boolean FileExists = (Dir(FileToTest) <> "")End Function I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering: Check for an empty string being passed. Check for a string containing characters illegal in a file name/path 2.) How To Delete a File. Look at this. Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you: Sub DeleteFile(ByVal FileToDelete As String) If FileExists(FileToDelete) Then 'See above ' First remove readonly attribute, if set SetAttr FileToDelete, vbNormal ' Then delete the file Kill FileToDelete End IfEnd Sub Again, I'll leave the error handling to you and again these are the things I'd consider: Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory? Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set? EDIT: Marking this answer as community wiki so anyone can modify it if need be. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/67835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10439/"
]
} |
67,875 | I'd love to learn Cocoa, it seems like the best systems language for Mac OS X. Can you recommend any useful ways to learn the language? Books, websites, example projects or even classes to take? | Andy Matuschak has a great blog post that leads you through several good Cocoa tutorials, explaining why you are reading each one. Cocoa Dev Central has loads of tutorials. For books, I echo Dave and Phillip Bowden with Cocoa Programming for Mac OS X by Aaron Hillegass . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/67875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9593/"
]
} |
67,890 | I'm writing a web app that points to external links. I'm looking to create a non-sequential, non-guessable id for each document that I can use in the URL. I did the obvious thing: treating the url as a string and str#crypt on it, but that seems to choke on any non-alphanumberic characters, like the slashes, dots and underscores. Any suggestions on the best way to solve this problem? Thanks! | Depending on how long a string you would like you can use a few alternatives: require 'digest'Digest.hexencode('http://foo-bar.com/yay/?foo=bar&a=22')# "687474703a2f2f666f6f2d6261722e636f6d2f7961792f3f666f6f3d62617226613d3232"require 'digest/md5'Digest::MD5.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22')# "43facc5eb5ce09fd41a6b55dba3fe2fe"require 'digest/sha1'Digest::SHA1.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22')# "2aba83b05dc9c2d9db7e5d34e69787d0a5e28fc5"require 'digest/sha2'Digest::SHA2.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22')# "e78f3d17c1c0f8d8c4f6bd91f175287516ecf78a4027d627ebcacfca822574b2" Note that this won't be unguessable, you may have to combine it with some other (secret but static) data to salt the string: salt = 'foobar'Digest::SHA1.hexdigest(salt + 'http://foo-bar.com/yay/?foo=bar&a=22')# "dbf43aff5e808ae471aa1893c6ec992088219bbb" Now it becomes much harder to generate this hash for someone who doesn't know the original content and has no access to your source. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/67890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10461/"
]
} |
67,894 | Why do we need to use: extern "C" {#include <foo.h>} Specifically: When should we use it? What is happening at the compiler/linker level that requires us to use it? How in terms of compilation/linking does this solve the problems which require us to use it? | C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI', or 'Application Binary Interface', so the linker chokes up. This is preferable to passing C++ data to a function expecting C data. (To get into the really nitty-gritty, C++'s ABI generally 'mangles' the names of their functions/methods, so calling printf() without flagging the prototype as a C function, the C++ will actually generate code calling _Zprintf , plus extra crap at the end.) So: use extern "C" {...} when including a c header—it's that simple. Otherwise, you'll have a mismatch in compiled code, and the linker will choke. For most headers, however, you won't even need the extern because most system C headers will already account for the fact that they might be included by C++ code and already extern "C" their code. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/67894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
]
} |
67,959 | I've run into a few gotchas when doing C# XML serializationthat I thought I'd share: You can't serialize items that are read-only (like KeyValuePairs) You can't serialize a generic dictionary. Instead, try this wrapper class (from http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx ): using System;using System.Collections.Generic;using System.Text;using System.Xml.Serialization;[XmlRoot("dictionary")]public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable{ public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } }} Any other XML Serialization gotchas out there? | I can't make comments yet, so I will comment on Dr8k's post and make another observation. Private variables that are exposed as public getter/setter properties, and do get serialized/deserialized as such through those properties. We did it at my old job al the time. One thing to note though is that if you have any logic in those properties, the logic is run, so sometimes, the order of serialization actually matters. The members are implicitly ordered by how they are ordered in the code, but there are no guarantees, especially when you are inheriting another object. Explicitly ordering them is a pain in the rear. I've been burnt by this in the past. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/67959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109/"
]
} |
68,018 | If I have a Resource bundle property file: A.properties: thekey={0} This is a test And then I have java code that loads the resource bundle: ResourceBundle labels = ResourceBundle.getBundle("A", currentLocale);labels.getString("thekey"); How can I replace the {0} text with some value labels.getString("thekey", "Yes!!!"); Such that the output comes out as: Yes!!! This is a test. There are no methods that are part of Resource Bundle to do this. Also, I am in Struts, is there some way to use MessageProperties to do the replacement. | The class you're looking for is java.text.MessageFormat; specifically, calling MessageFormat.format("{0} This {1} a test", new Object[] {"Yes!!!", "is"}); or MessageFormat.format("{0} This {1} a test", "Yes!!!", "is"); will return "Yes!!! This is a test" [Unfortunately, I can't help with the Struts connection, although this looks relevant.] | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/68018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10522/"
]
} |
68,084 | I'm trying to find a least-resistance path from C# to C++, and while I feel I handle C# pretty well after two solid years, I'm still not sure I've gotten the "groove" of C++, despite numerous attempts. Are there any particular books or websites that might be suitable for this transition? | I recommend The C++ Programming language by Bjarne Stroustrup. It's not a suitable book for new programmers, but I found it quite effective as programmer who was experienced in other languages and didn't want to waste too much time with learning how while loops work. It's a dense but quite comprehensive book. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/68084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10541/"
]
} |
68,113 | I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible. | I've had some luck with the Java Service Wrapper | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10273/"
]
} |
68,120 | I'm not overly familiar with Tomcat, but my team has inherited a complex project that revolves around a Java Servlet being hosted in Tomcat across many servers. Custom configuration management software is used to write out the server.xml, and various resources (connection pools, beans, server variables, etc) written into server.xml configure the servlet. This is all well and good. However, the names of some of the resources aren't known in advance. For example, the Servlet may need access to any number of "Anonymizers" as configured by the operator. Each anonymizer has a unique name associated with it. We create and configure each anonymizer using java beans similar to the following: <Resource name="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="50"/><Resource name="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="54"/> However, this appears to require us to have explicit entries in the Servlet's context.xml file for each an every possible resource name in advance. I'd like to replace the explicit context.xml entries with wildcards, or know if there is a better solution to this type of problem. Currently: <ResourceLink name="bean/Anonymizer_default" global="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean"/> <ResourceLink name="bean/Anonymizer_toon" global="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean"/> Replaced with something like: <ResourceLink name="bean/Anonymizer_*" global="bean/Anonymizer_*" type="com.company.tomcatutil.AnonymizerBean"/> However, I haven't been able to figure out if this is possible or what the correct syntax might be. Can anyone make any suggestions about better ways to handle this? | I've had some luck with the Java Service Wrapper | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10452/"
]
} |
68,150 | I took a data structures class in C++ last year, and consequently implemented all the major data structures in templated code. I saved it all on a flash drive because I have a feeling that at some point in my life, I'll use it again. I imagine something I end up programming will need a B-Tree, or is that just delusional? How long do you typically save the code you write for possible reuse? | Forever (or as close as I can get). That's the whole point of a source control system. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/68150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7545/"
]
} |
68,160 | Is it possible to get gdb or use some other tools to create a core dump of a running process and it's symbol table? It would be great if there's a way to do this without terminating the process. If this is possible, what commands would you use? (I'm trying to do this on a Linux box) | $ gdb --pid=26426(gdb) gcoreSaved corefile core.26426(gdb) detach | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
68,165 | I have a link on a long HTML page. When I click it, I wish a div on another part of the page to be visible in the window by scrolling into view. A bit like EnsureVisible in other languages. I've checked out scrollTop and scrollTo but they seem like red herrings. Can anyone help? | old question, but if anyone finds this through google (as I did) and who does not want to use anchors or jquery; there's a builtin javascriptfunction to 'jump' to an element; document.getElementById('youridhere').scrollIntoView(); and what's even better; according to the great compatibility-tables on quirksmode, this is supported by all major browsers ! | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/68165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
68,282 | When defining a method on a class in Python, it looks something like this: class MyClass(object): def __init__(self, x, y): self.x = x self.y = y But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument? | I like to quote Peters' Zen of Python. "Explicit is better than implicit." In Java and C++, ' this. ' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't. Python elects to make things like this explicit rather than based on a rule. Additionally, since nothing is implied or assumed, parts of the implementation are exposed. self.__class__ , self.__dict__ and other "internal" structures are available in an obvious way. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/68282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
68,283 | What's a quick and easy way to view and edit ID3 tags (artist, album, etc.) using C#? | Thirding TagLib Sharp . TagLib.File f = TagLib.File.Create(path);f.Tag.Album = "New Album Title";f.Save(); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/68283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10606/"
]
} |
68,291 | If you were running a news site that created a list of 10 top news stories, and you wanted to make tweaks to your algorithm and see if people liked the new top story mix better, how would you approach this? Simple Click logging in the DB associated with the post entry? A/B testing where you would show one version of the algorithm togroup A and another to group B and measure the clicks? What sort of characteristics would you base your decision on as to whether the changes were better? | Thirding TagLib Sharp . TagLib.File f = TagLib.File.Create(path);f.Tag.Album = "New Album Title";f.Save(); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/68291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281/"
]
} |
68,323 | Working on a project at the moment and we have to implement soft deletion for the majority of users (user roles). We decided to add an is_deleted='0' field on each table in the database and set it to '1' if particular user roles hit a delete button on a specific record. For future maintenance now, each SELECT query will need to ensure they do not include records where is_deleted='1' . Is there a better solution for implementing soft deletion? Update: I should also note that we have an Audit database that tracks changes (field, old value, new value, time, user, ip) to all tables/fields within the Application database. | You could perform all of your queries against a view that contains the WHERE IS_DELETED='0' clause. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
]
} |
68,327 | I create a new Button object but did not specify the command option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created? | Though Eli Courtwright's program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by way of the configure() method. from Tkinter import Tk, Buttondef goodbye_world(): print "Goodbye World!\nWait, I changed my mind!" button.configure(text = "Hello World!", command=hello_world)def hello_world(): print "Hello World!\nWait, I changed my mind!" button.configure(text = "Goodbye World!", command=goodbye_world)root = Tk()button = Button(root, text="Hello World!", command=hello_world)button.pack()root.mainloop() ¹ "fine" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the command option through .configure is much easier. ² the only attribute that can't change after instantiation is name . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/68327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
]
} |
68,335 | I have a text file on my local machine that is generated by a daily Python script run in cron. I would like to add a bit of code to have that file sent securely to my server over SSH. | You can call the scp bash command (it copies files over SSH ) with subprocess.run : import subprocesssubprocess.run(["scp", FILE, "USER@SERVER:PATH"])#e.g. subprocess.run(["scp", "foo.bar", "[email protected]:/path/to/foo.bar"]) If you're creating the file that you want to send in the same Python program, you'll want to call subprocess.run command outside the with block you're using to open the file (or call .close() on the file first if you're not using a with block), so you know it's flushed to disk from Python. You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10668/"
]
} |
68,372 | We all know how to use <ctrl>-R to reverse search through history, but did you know you can use <ctrl>-S to forward search if you set stty stop "" ? Also, have you ever tried running bind -p to see all of your keyboard shortcuts listed? There are over 455 on Mac OS X by default. What is your single most favorite obscure trick, keyboard shortcut or shopt configuration using bash? | cd - It's the command-line equivalent of the back button (takes you to the previous directory you were in). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
]
} |
68,456 | Is it ready for that? I've been playing with it for a short amount of time and it seems quite reasonable. Is anyone using it for live sites? any issues to be aware of? | Well, stackoverflow.com is. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/68456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10431/"
]
} |
68,477 | Is there a way to send a file using POST from a Python script? | From: https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file Requests makes it very simple to upload Multipart-encoded files: with open('report.xls', 'rb') as f: r = requests.post('http://httpbin.org/post', files={'report.xls': f}) That's it. I'm not joking - this is one line of code. The file was sent. Let's check: >>> r.text{ "origin": "179.13.100.4", "files": { "report.xls": "<censored...binary...data>" }, "form": {}, "url": "http://httpbin.org/post", "args": {}, "headers": { "Content-Length": "3196", "Accept-Encoding": "identity, deflate, compress, gzip", "Accept": "*/*", "User-Agent": "python-requests/0.8.0", "Host": "httpbin.org:80", "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1" }, "data": ""} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/68477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
68,485 | In Prototype I can show a "loading..." image with this code: var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} );function showLoad () { ...} In jQuery , I can load a server page into an element with this: $('#message').load('index.php?pg=ajaxFlashcard'); but how do I attach a loading spinner to this command as I did in Prototype? | There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself. $('#loadingDiv') .hide() // Hide it initially .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); The ajaxStart/Stop functions will fire whenever you do any Ajax calls. Update : As of jQuery 1.8, the documentation states that .ajaxStart/Stop should only be attached to document . This would transform the above snippet to: var $loading = $('#loadingDiv').hide();$(document) .ajaxStart(function () { $loading.show(); }) .ajaxStop(function () { $loading.hide(); }); | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/68485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
} |
68,527 | My team is developing a new service oriented product with a web front-end. In discussions about what technologies we will use we have settled on running a JBoss application server, and Flex frontend (with possible desktop deployment using Adobe AIR), and web services to interface the client and server. We've reached an impasse when it comes to which server technology to use for our business logic. The big argument is between EJB3 and Spring, with our biggest concerns being scalability and performance, and also maintainability of the code base. Here are my questions: What are the arguments for or against EJB3 vs Spring? What pitfalls can I expect with each? Where can I find good benchmark information? | There won't be much difference between EJB3 and Spring based on Performance. We chose Spring for the following reasons (not mentioned in the question): Spring drives the architecture in a direction that more readily supports unit testing. For example, inject a mock DAO object to unit test your business layer, or utilize Spring's MockHttpRequest object to unit test a servlet. We maintain a separate Spring config for unit tests that allows us to isolate tests to the specific layers. An overriding driver was compatibility. If you need to support more than one App Server (or eventually want the option to move from JBoss to Glassfish, etc.), you will essentially be carrying your container (Spring) with you, rather than relying on compatibility between different implementations of the EJB3 specification. Spring allows for technology choices for Persistence, object remoting, etc. For example, we are also using a Flex front end, and are using the Hessian protocol for communications between Flex and Spring. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92/"
]
} |
68,561 | 1, Create and build a default Windows Forms project and look at the project properties. It says that the project is targetting .NET Framework 2.0. 2, Create a Setup project that installs just the single executable from the Windows Forms project. 3, Run that installer and it always says that it needs to install .NET 3.5 SP1 on the machine. But it obviously only really needs 2.0 and so I do not want customers to be forced to install .NET 3.5 when they do not need it. They might already have 2.0 installed and so forcing the upgrade is not desirable! I have looked at the prerequisites of the setup project and checked the .NET Framework 2.0 entry and all the rest are unchecked. So I cannot find any reason for this strange runtime requirement. Anybody know how to resolve this one? | No need to edit the file manually. The hint is just above the GUID there:"LaunchCondition". Right click the setup project Select "View" -> "Launch Conditions" Expand the "Launch Conditions" node if it isn't already expanded Right click the ".NET Framework" node and select "Properties Window" In the "Properties" window change the "Version" value to the appropriate value, in your case 2.0.50727. I'm not sure why this isn't set appropriately from the start. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/68561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6276/"
]
} |
68,569 | I am a C++/C# developer and never spent time working on web pages. I would like to put text (randomly and diagonally perhaps) in large letters across the background of some pages. I want to be able to read the foreground text and also be able to read the "watermark". I understand that is probably more of a function of color selection. I have been unsuccessful in my attempts to do what I want. I would imagine this to be very simple for someone with the web design tools or html knowledge. | <style type="text/css">#watermark { color: #d0d0d0; font-size: 200pt; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); position: absolute; width: 100%; height: 100%; margin: 0; z-index: -1; left:-100px; top:-200px;}</style> This lets you use just text as the watermark - good for dev/test versions of a web page. <div id="watermark"><p>This is the test version.</p></div> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/68569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10755/"
]
} |
68,572 | I have a question that I may be over thinking at this point but here goes... I have 2 classes Users and Groups. Users and groups have a many to many relationship and I was thinking that the join table group_users I wanted to have an IsAuthorized property (because some groups are private -- users will need authorization). Would you recommend creating a class for the join table as well as the User and Groups table? Currently my classes look like this. public class Groups{ public Groups() { members = new List<Person>(); } ... public virtual IList<Person> members { get; set; }}public class User{ public User() { groups = new Groups() } ... public virtual IList<Groups> groups{ get; set; }} My mapping is like the following in both classes (I'm only showing the one in the users mapping but they are very similar): HasManyToMany<Groups>(x => x.Groups).WithTableName("GroupMembers").WithParentKeyColumn("UserID").WithChildKeyColumn("GroupID").Cascade.SaveUpdate(); Should I write a class for the join table that looks like this? public class GroupMembers{ public virtual string GroupID { get; set; } public virtual string PersonID { get; set; } public virtual bool WaitingForAccept { get; set; }} I would really like to be able to adjust the group membership status and I guess I'm trying to think of the best way to go about this. | <style type="text/css">#watermark { color: #d0d0d0; font-size: 200pt; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); position: absolute; width: 100%; height: 100%; margin: 0; z-index: -1; left:-100px; top:-200px;}</style> This lets you use just text as the watermark - good for dev/test versions of a web page. <div id="watermark"><p>This is the test version.</p></div> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/68572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
]
} |
68,578 | Is there a way to fall through multiple case statements without stating case value: repeatedly? I know this works: switch (value){ case 1: case 2: case 3: // Do some stuff break; case 4: case 5: case 6: // Do some different stuff break; default: // Default stuff break;} but I'd like to do something like this: switch (value){ case 1,2,3: // Do something break; case 4,5,6: // Do something break; default: // Do the Default break;} Is this syntax I'm thinking of from a different language, or am I missing something? | There is no syntax in C++ nor C# for the second method you mentioned. There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/68578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7870/"
]
} |
68,583 | I have the following code snippet. $items['A'] = "Test";$items['B'] = "Test";$items['C'] = "Test";$items['D'] = "Test";$index = 0;foreach($items as $key => $value){ echo "$index is a $key containing $value\n"; $index++;} Expected output: 0 is a A containing Test1 is a B containing Test2 is a C containing Test3 is a D containing Test Is there a way to leave out the $index variable? | Your $index variable there kind of misleading. That number isn't the index, your "A", "B", "C", "D" keys are. You can still access the data through the numbered index $index[1], but that's really not the point. If you really want to keep the numbered index, I'd almost restructure the data: $items[] = array("A", "Test");$items[] = array("B", "Test");$items[] = array("C", "Test");$items[] = array("D", "Test");foreach($items as $key => $value) { echo $key.' is a '.$value[0].' containing '.$value[1];} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/68583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264/"
]
} |
68,598 | I've seen this done in Borland's Turbo C++ environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for? | Some sample code: public partial class Form1 : Form { public Form1() { InitializeComponent(); this.AllowDrop = true; this.DragEnter += new DragEventHandler(Form1_DragEnter); this.DragDrop += new DragEventHandler(Form1_DragDrop); } void Form1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } void Form1_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (string file in files) Console.WriteLine(file); } } | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/68598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
68,624 | I would like to parse a string such as p1=6&p2=7&p3=8 into a NameValueCollection . What is the most elegant way of doing this when you don't have access to the Page.Request object? | There's a built-in .NET utility for this: HttpUtility.ParseQueryString // C#NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring); ' VB.NETDim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring) You may need to replace querystring with new Uri(fullUrl).Query . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/68624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4998/"
]
} |
68,630 | Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? | The dis module disassembles the byte code for a function and is useful to see the difference between tuples and lists. In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list. >>> def a():... x=[1,2,3,4,5]... y=x[2]...>>> def b():... x=(1,2,3,4,5)... y=x[2]...>>> import dis>>> dis.dis(a) 2 0 LOAD_CONST 1 (1) 3 LOAD_CONST 2 (2) 6 LOAD_CONST 3 (3) 9 LOAD_CONST 4 (4) 12 LOAD_CONST 5 (5) 15 BUILD_LIST 5 18 STORE_FAST 0 (x) 3 21 LOAD_FAST 0 (x) 24 LOAD_CONST 2 (2) 27 BINARY_SUBSCR 28 STORE_FAST 1 (y) 31 LOAD_CONST 0 (None) 34 RETURN_VALUE>>> dis.dis(b) 2 0 LOAD_CONST 6 ((1, 2, 3, 4, 5)) 3 STORE_FAST 0 (x) 3 6 LOAD_FAST 0 (x) 9 LOAD_CONST 2 (2) 12 BINARY_SUBSCR 13 STORE_FAST 1 (y) 16 LOAD_CONST 0 (None) 19 RETURN_VALUE | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/68630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
68,633 | I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer. Here is my regex: "\w+ +\w+ *\(.*\) *\{" For those who do not know what a java method looks like I'll provide a basic one: int foo(){} There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have. Update:My current Regex is "\w+ +\w+ *\([^\)]*\) *\{" so as to prevent the situation that Mike and adkom described. | (public|protected|private|static|\s) +[\w\<\>\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;]) I think that the above regexp can match almost all possible combinations of Java method declarations, even those including generics and arrays are return arguments, which the regexp provided by the original author did not match. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/68633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340/"
]
} |
68,640 | Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both? | Yes, you can. The pointer to the class member variable is stored on the stack with the rest of the struct's values, and the class instance's data is stored on the heap. Structs can also contain class definitions as members (inner classes). Here's some really useless code that at least compiles and runs to show that it's possible: using System;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { MyStr m = new MyStr(); m.Foo(); MyStr.MyStrInner mi = new MyStr.MyStrInner(); mi.Bar(); Console.ReadLine(); } } public class Myclass { public int a; } struct MyStr { Myclass mc; public void Foo() { mc = new Myclass(); mc.a = 1; } public class MyStrInner { string x = "abc"; public string Bar() { return x; } } }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/68640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722/"
]
} |
68,645 | How do I create class (i.e. static ) variables or methods in Python? | Variables declared inside the class definition, but not inside a method are class or static variables: >>> class MyClass:... i = 3...>>> MyClass.i3 As @ millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have >>> m = MyClass()>>> m.i = 4>>> MyClass.i, m.i>>> (3, 4) This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance. See what the Python tutorial has to say on the subject of classes and class objects . @Steve Johnson has already answered regarding static methods , also documented under "Built-in Functions" in the Python Library Reference . class C: @staticmethod def f(arg1, arg2, ...): ... @beidy recommends classmethod s over staticmethod, as the method then receives the class type as the first argument. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/68645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2246/"
]
} |
68,651 | If I pass PHP variables with . in their names via $_GET PHP auto-replaces them with _ characters. For example: <?phpecho "url is ".$_SERVER['REQUEST_URI']."<p>";echo "x.y is ".$_GET['x.y'].".<p>";echo "x_y is ".$_GET['x_y'].".<p>"; ... outputs the following: url is /SpShipTool/php/testGetUrl.php?x.y=a.bx.y is .x_y is a.b. ... my question is this: is there any way I can get this to stop? Cannot for the life of me figure out what I've done to deserve this PHP version I'm running with is 5.2.4-2ubuntu5.3. | Here's PHP.net's explanation of why it does it: Dots in incoming variable names Typically, PHP does not alter thenames of variables when they arepassed into a script. However, itshould be noted that the dot (period,full stop) is not a valid character ina PHP variable name. For the reason,look at it: <?php$varname.ext; /* invalid variable name */?> Now, whatthe parser sees is a variable named$varname, followed by the stringconcatenation operator, followed bythe barestring (i.e. unquoted stringwhich doesn't match any known key orreserved words) 'ext'. Obviously, thisdoesn't have the intended result. For this reason, it is important tonote that PHP will automaticallyreplace any dots in incoming variablenames with underscores. That's from http://ca.php.net/variables.external . Also, according to this comment these other characters are converted to underscores: The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot): chr(32) ( ) (space) chr(46) (.) (dot) chr(91) ([) (open square bracket) chr(128) - chr(159) (various) So it looks like you're stuck with it, so you'll have to convert the underscores back to dots in your script using dawnerd's suggestion (I'd just use str_replace though.) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
68,666 | Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN": Clipboard.SetText(str); This usually occurs the first time the Clipboard is used in the application and not after that. | Actually, I think this is the fault of the Win32 API . To set data in the clipboard, you have to open it first. Only one process can have the clipboard open at a time. So, when you check, if another process has the clipboard open for any reason , your attempt to open it will fail. It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you. The only solution is to wait until Terminal Services closes the clipboard and try again. It's important to realize that this is not specific to Terminal Services, though: it can happen with anything. Working with the clipboard in Win32 is a giant race condition. But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/68666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10784/"
]
} |
68,677 | I'm using SQL Server 2000 to print out some values from a table using PRINT . With most non-string data, I can cast to nvarchar to be able to print it, but binary values attempt to convert using the bit representation of characters. For example: DECLARE @binvalue binary(4)SET @binvalue = 0x12345678PRINT CAST(@binvalue AS nvarchar) Expected: 0x12345678 Instead, it prints two gibberish characters. How can I print the value of binary data? Is there a built-in or do I need to roll my own? Update: This isn't the only value on the line, so I can't just PRINT @binvalue. It's something more like PRINT N'other stuff' + ???? + N'more stuff'. Not sure if that makes a difference: I didn't try just PRINT @binvalue by itself. | If you were on Sql Server 2005 you could use this: print master.sys.fn_varbintohexstr(@binvalue) I don't think that exists on 2000, though, so you might have to roll your own. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/68677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3750/"
]
} |
68,749 | Using .Net (C#), how can you work with USB devices? How can you detect USB events (connections/disconnections) and how do you communicate with devices (read/write). Is there a native .Net solution to do this? | There is no native (e.g., System libraries) solution for this. That's the reason why SharpUSBLib exists as mentioned by moobaa . If you wish to roll your own handler for USB devices, you can check out the SerialPort class of System.IO.Ports . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/68749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5903/"
]
} |
68,750 | This should hopefully be a simple one. I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class. How should this extension method look? My first intuitive thought is something like this: namespace System.Web.Mvc{ public static class ViewPageExtensions { public static string GetDefaultPageTitle(this ViewPage<Type> v) { return ""; } }} Solution The general solution is this answer . The specific solution to extending the System.Web.Mvc.ViewPage class is my answer below, which started from the general solution . The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type. | I don't have VS installed on my current machine, but I think the syntax would be: namespace System.Web.Mvc{ public static class ViewPageExtensions { public static string GetDefaultPageTitle<T>(this ViewPage<T> v) { return ""; } }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/68750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
} |
68,774 | I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way? | Opening sockets in python is pretty simple. You really just need something like this: import socketsock = socket.socket()sock.connect((address, port)) and then you can send() and recv() like any other socket | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/68774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
]
} |
68,999 | I'm using a Java socket, connected to a server. If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way? I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only. | I would say it depends on what exact interval you are trying measure, the amount of time from the last byte of the request that you send until the first byte of the response that you receive? Or until the entire response is received? Or are you trying to measure the server-side time only? If you're trying to measure the server side processing time only, you're going to have a difficult time factoring out the amount of time spent in network transit for your request to arrive and the response to return. Otherwise, since you're managing the request yourself through a Socket, you can measure the elapsed time between any two moments by checking the System timer and computing the difference. For example: public void sendHttpRequest(byte[] requestData, Socket connection) { long startTime = System.nanoTime(); writeYourRequestData(connection.getOutputStream(), requestData); byte[] responseData = readYourResponseData(connection.getInputStream()); long elapsedTime = System.nanoTime() - startTime; System.out.println("Total elapsed http request/response time in nanoseconds: " + elapsedTime);} This code would measure the time from when you begin writing out your request to when you finish receiving the response, and print the result (assuming you have your specific read/write methods implemented). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/68999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10889/"
]
} |
69,063 | Most of our Eclipse projects have multiple source folders, for example: src/main/java src/test/java When you right-click on a class and choose New JUnit Test, the default source folder for the new test is "src/main/java" (presumably the first source folder listed in the project properties). Is there any way to change the default source folder for new JUnit tests, so that when I do the above action, the new test will be created in say the "src/test/java" folder by default? | I use moreUnit , an Eclipse plugin to assist writing unit tests. Among other features, it lets you configure the default source folder of tests. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/69063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10433/"
]
} |
69,068 | How can I split long commands over multiple lines in a batch file? | You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. ( More on that below. ) Example: copy file1.txt file2.txt would be written as: copy file1.txt^ file2.txt | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/69068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
69,112 | Can someone describe what a symbol table is within the context of C and C++? | There are two common and related meaning of symbol tables here. First, there's the symbol table in your object files. Usually, a C or C++ compiler compiles a single source file into an object file with a .obj or .o extension. This contains a collection of executable code and data that the linker can process into a working application or shared library. The object file has a data structure called a symbol table in it that maps the different items in the object file to names that the linker can understand. If you call a function from your code, the compiler doesn't put the final address of the routine in the object file. Instead, it puts a placeholder value into the code and adds a note that tells the linker to look up the reference in the various symbol tables from all the object files it's processing and stick the final location there. Second, there's also the symbol table in a shared library or DLL. This is produced by the linker and serves to name all the functions and data items that are visible to users of the library. This allows the system to do run-time linking, resolving open references to those names to the location where the library is loaded in memory. If you want to learn more, I suggest John Levine's excellent book "Linkers and Loaders". link text | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/69112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10774/"
]
} |
69,128 | I've seen SaaS applications hosted in many different ways. Is it a good idea to split features and modules across multiple databases? For example, putting things like the User table on one DB and feature/app specific tables on another DB and perhaps other commonly shared tables in another DB? | Start with one database. Split data/functionality when project requires it. Here is what we can learn from LinkedIn: A single database does not work Referential integrity will not be possible Any data loss is a problem Caching is good even when it's modestly effective Never underestimate growth trajectory Source: LinkedIn architecture LinkedIn communication architecture | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/69128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10941/"
]
} |
69,192 | Suppose we have two stacks and no other temporary variable. Is to possible to "construct" a queue data structure using only the two stacks? | Keep 2 stacks, let's call them inbox and outbox . Enqueue : Push the new element onto inbox Dequeue : If outbox is empty, refill it by popping each element from inbox and pushing it onto outbox Pop and return the top element from outbox Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations. Here's an implementation in Java: public class Queue<E>{ private Stack<E> inbox = new Stack<E>(); private Stack<E> outbox = new Stack<E>(); public void queue(E item) { inbox.push(item); } public E dequeue() { if (outbox.isEmpty()) { while (!inbox.isEmpty()) { outbox.push(inbox.pop()); } } return outbox.pop(); }} | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/69192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7086/"
]
} |
69,209 | Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to the previous node?After deletion the previous node should point to the node next to deleted node. | It's definitely more a quiz rather than a real problem. However, if we are allowed to make some assumption, it can be solved in O(1) time. To do it, the strictures the list points to must be copyable. The algorithm is as the following: We have a list looking like: ... -> Node(i-1) -> Node(i) -> Node(i+1) -> ... and we need to delete Node(i). Copy data (not pointer, the data itself) from Node(i+1) to Node(i), the list will look like: ... -> Node(i-1) -> Node(i+1) -> Node(i+1) -> ... Copy the NEXT of second Node(i+1) into a temporary variable. Now Delete the second Node(i+1), it doesn't require pointer to the previous node. Pseudocode: void delete_node(Node* pNode){ pNode->Data = pNode->Next->Data; // Assume that SData::operator=(SData&) exists. Node* pTemp = pNode->Next->Next; delete(pNode->Next); pNode->Next = pTemp;} Mike. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/69209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7086/"
]
} |
69,250 | In most C or C++ environments, there is a "debug" mode and a "release" mode compilation. Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations. In "release" mode, you usually have all sorts of optimizations turned on. Why the difference? | Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations. For example: void foo() {1: int i;2: for(i = 0; i < 2; )3: i++;4: return; In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4 With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...) Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions. Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case. While the optimized and non-optimized code should be "functionally" equivalent, under certain circumstances, the behavior will change. Here is a simplistic example: int* ptr = 0xdeadbeef; // some address to memory-mapped I/O device *ptr = 0; // setup hardware device while(*ptr == 1) { // loop until hardware device is done // do something } With optimization off, this is straightforward, and you kinda know what to expect.However, if you turn optimization on, a couple of things might happen: The compiler might optimize the while block away (we init to 0, it'll never be 1) Instead of accessing memory, pointer access might be moved to a register->No I/O Update memory access might be cached (not necessarily compiler optimization related) In all these cases, the behavior would be drastically different and most likely wrong. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/69250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
69,262 | I am wondering if there is a method or format string I'm missing in .NET to convert the following: 1 to 1st 2 to 2nd 3 to 3rd 4 to 4th 11 to 11th 101 to 101st 111 to 111th This link has a bad example of the basic principle involved in writing your own function, but I am more curious if there is an inbuilt capacity I'm missing. Solution Scott Hanselman's answer is the accepted one because it answers the question directly. For a solution however, see this great answer . | No, there is no inbuilt capability in the .NET Base Class Library. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/69262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
} |
69,281 | I've recently started using Eclipse Ganymede CDT for C development and I couldn't like it more. I'm aware the learning curve could be sort of pronounced, therefore and with your help, my goal is to flatten it as much as possible. I'm looking for the best hacks, hints, tips, tricks, and best practices to really unleash the full power of the IDE. | Accurate Indexing With CDT you should be sure to enable the "Full Indexing" option rather than the "Fast Indexing" default. It's not perceptibly slower on modern hardware and it does a much better job. In that vein, you should be sure to enable semantic highlighting. This isn't as important in C/C++ as it is in a language like Scala, but it's still extremely useful. Streamlined Editing Get used to using Ctrl + O and Ctrl + Alt + H . The former pops up an incrementally searchable outline view, while the latter opens the "Call Hierarchy" view and searches on the currently selected function. This is incredibly useful for tracing execution. Ctrl + Shift + T (Open Type) isn't exactly an "editing" combo per se, but it is equally important in my workflow. The C++ Open Type dialog not only allows incremental filtering by type, but also selecting of definition ( .h ) or declaration ( .cpp ) and even filtering by element type ( typedef , struct , class , etc). Task Oriented Programming Mylyn: never leave home without it. I just can't say enough about this tool. Every time I'm forced to do without it I find myself having to re-learn how to deal with all of the code noise. Very, very handy to have. Stripped Down Views The default Eclipse workspace layout is extremely inefficient both in space and in usability. Everyone has their favorite layout, take some time and find yours. I like to minimize (not necessarily close) everything except for Outline and keep the C/C++ Project Explorer docked in the sidebar configured to precisely hide the Outline when expanded. In this way I can always keep the editor visible while simultaneously reducing the space used by views irrelevant to the current task. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/69281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
]
} |
69,316 | What are the biggest pros and cons of Apache Thrift vs Google's Protocol Buffers ? | They both offer many of the same features; however, there are some differences: Thrift supports 'exceptions' Protocol Buffers have much better documentation/examples Thrift has a builtin Set type Protocol Buffers allow "extensions" - you can extend an external proto to add extra fields, while still allowing external code to operate on the values. There is no way to do this in Thrift I find Protocol Buffers much easier to read Basically, they are fairly equivalent (with Protocol Buffers slightly more efficient from what I have read). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/69316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
69,332 | I suspect that one of my applications eats more CPU cycles than I want it to. The problem is - it happens in bursts, and just looking at the task manager doesn't help me as it shows immediate usage only. Is there a way (on Windows) to track the history of CPU & Memory usage for some process. E.g. I will start tracking "firefox", and after an hour or so will see a graph of its CPU & memory usage during that hour. I'm looking for either a ready-made tool or a programmatic way to achieve this. | Press Win + R , type perfmon and press Enter . When the Performance window is open, click on the + sign to add new counters to the graph. The counters are different aspects of how your PC works and are grouped by similarity into groups called "Performance Object". For your questions, you can choose the "Process", "Memory" and "Processor" performance objects. You then can see these counters in real time You can also specify the utility to save the performance data for your inspection later. To do this, select "Performance Logs and Alerts" in the left-hand panel. (It's right under the System Monitor console which provides us with the above mentioned counters. If it is not there, click "File" > "Add/remove snap-in", click Add and select "Performance Logs and Alerts" in the list".) From the "Performance Logs and Alerts", create a new monitoring configuration under "Counter Logs". Then you can add the counters, specify the sampling rate, the log format (binary or plain text) and log location. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/69332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
]
} |
69,352 | What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form. | private void Form1_KeyPress(object sender, KeyPressEventArgs e){ if(e.KeyChar == 'm') this.WindowState = FormWindowState.Minimized;} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/69352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7516/"
]
} |
69,411 | What is the best way to copy a directory (with sub-dirs and files) from one remote Linux server to another remote Linux server? I have connected to both using SSH client (like Putty). I have root access to both. | There are two ways I usually do this, both use ssh: scp -r sourcedir/ [email protected]:/dest/dir/ or, the more robust and faster (in terms of transfer speed) method: rsync -auv -e ssh --progress sourcedir/ [email protected]:/dest/dir/ Read the man pages for each command if you want more details about how they work. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/69411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
69,430 | I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers. I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers. | In most browsers, this can be achieved using CSS: *.unselectable { -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; /* Introduced in IE 10. See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/ */ -ms-user-select: none; user-select: none;} For IE < 10 and Opera, you will need to use the unselectable attribute of the element you wish to be unselectable. You can set this using an attribute in HTML: <div id="foo" unselectable="on" class="unselectable">...</div> Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <div> . If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants: function makeUnselectable(node) { if (node.nodeType == 1) { node.setAttribute("unselectable", "on"); } var child = node.firstChild; while (child) { makeUnselectable(child); child = child.nextSibling; }}makeUnselectable(document.getElementById("foo")); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/69430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3561/"
]
} |
69,440 | I'm wondering if there's any way to write CSS specifically for Safari using only CSS. I know there has to be something out there, but I haven't found it yet. | I think the question is valid. I agree with the other responses, but it doesn't mean it's a terrible question. I've only ever had to use a Safari CSS hack once as a temporary solution and later got rid of it. I agree that you shouldn't have to target just Safari, but no harm in knowing how to do it. FYI, this hack only targets Safari 3, and also targets Opera 9. @media screen and (-webkit-min-device-pixel-ratio:0) { /* Safari 3.0 and Opera 9 rules here */} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/69440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8970/"
]
} |
69,448 | I am using VS2008 and Resharper. Resharper creates a directory _Resharper.ProjectName. These files provide no value for source control that I am aware of and cause issues when committing changes. How can I get SVN to ignore them? I am using TortoiseSVN as my interface for SVN. EDIT: You guys are fast. | Here's a link to show the ignoring process in TortoiseSVN | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/69448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865/"
]
} |
69,480 | I have a script that renders graphs in gnuplot. The graphs all end up with an ugly white background. How do I change this? (Ideally, with a command that goes into a gnuplot script, as opposed to a command-line option or something in a settings file) | You can change the background color by command set object 1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb"green" behind to set the background color to the the color you specified (here is green). To get more knowledge about setting the background in gnuplot, you can visit this blog . There are even provided methods to set a gradient color background and background pictures. Good luck! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/69480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
} |
69,497 | I'm sick and tired of manually tracking my branches and merges across my repository! It's too error prone. In a world where everyone seems to get the idea of reducing duplication and automating everything, subversion branching/merging feels like it's left over from the 80's. What is a good alternative to subversion that has excellent branching and merging support without adding the complexity of a distributed SCM paradigm? Ideally it would be free, but if I have to shell out some cash I might be inclined if it's good enough. | Have you upgraded to Subversion 1.5? It includes automated merge tracking. This may address your issue. It sounds like you're already familiar with the tool itself and it's free. So, if you upgrade your current solution to 1.5 you'll have almost no learning curve and zero cost - plus you won't have to go through the pain of porting your existing code to a new source code control system. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/69497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10945/"
]
} |
69,539 | I am curious if anyone have used UnderC, Cint, Cling, Ch, or any other C++ interpreter and could share their experience. | There is cling Cern's project of C++ interpreter based on clang - it's new approach based on 20 years of experience in ROOT cint and it's quite stable and recommended by Cern guys. Here is nice Google Talk: Introducing cling, a C++ Interpreter Based on clang/LLVM . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/69539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9706/"
]
} |
69,591 | I want to create a regexp in Emacs that matches exactly 3 digits. For example, I want to match the following: 123345789 But not 12341212 23 If I use [0-9]+ I match any single string of digits. I thought [0-9]{3} would work, but when tested in re-builder it doesn't match anything. | If you're entering the regex interactively, and want to use {3} , you need to use backslashes to escape the curly braces. If you don't want to match any part of the longer strings of numbers, use \b to match word boundaries around the numbers. This leaves: \b[0-9]\{3\}\b For those wanting more information about \b , see the docs : matches the empty string, but only at the beginning or end of a word. Thus, \bfoo\b matches any occurrence of foo as a separate word. \bballs?\b matches ball or balls as a separate word. \b matches at the beginning or end of the buffer regardless of what text appears next to it. If you do want to use this regex from elisp code, as always, you must escape the backslashes one more time. For example: (highlight-regexp "\\b[0-9]\\{3\\}\\b") | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/69591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
]
} |
69,627 | I am looking for a simple unpatented one-way encryption algorithm, preferably in c.I would like to use it to validate passwords. | SHA-1 and the rest of its family were patented by the US government which "has released the patent under a royalty free license". Many public-domain implementations may be found through Google . :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/69627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
]
} |
69,645 | I want to take a screenshot via a python script and unobtrusively save it. I'm only interested in the Linux solution, and should support any X based environment. | This works without having to use scrot or ImageMagick. import gtk.gdkw = gtk.gdk.get_default_root_window()sz = w.get_size()print "The size of the window is %d x %d" % szpb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])if (pb != None): pb.save("screenshot.png","png") print "Screenshot saved to screenshot.png."else: print "Unable to get the screenshot." Borrowed from http://ubuntuforums.org/showpost.php?p=2681009&postcount=5 | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/69645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1724701/"
]
} |
69,738 | I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependencies are preferred. Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to_str() member function for A. In pseudocode: class A {public: ... void print(FILE* f); B b; ... };...void A::print(FILE *f){ std::string s = "stuff"; fprintf(f, "some %s", s); b.print(f);}class C { ... std::string foo; bool set_foo(std::str); ...}...A a = new A();C c = new C();...// wish i knew how to write A's to_str()c.set_foo(a.to_str()); I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE* F) interface also needs to be preserved. I have considered several approaches to implementing A::to_str(), each with advantages and disadvantages: Change the calls to fprintf() to sprintf() I wouldn't have to rewrite any format strings print() could be reimplemented as: fprint(f, this.to_str()); But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string Try to catch the results of a.print() in a string stream I would have to convert all of the format strings to << output format. There are hundreds of fprintf()s to convert :-{ print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though this guy says it may be possible ). Use Boost's string format library More external dependencies. Yuck. Format's syntax is different enough from printf() to be annoying: printf(format_str, args) -> cout << boost::format(format_str) % arg1 % arg2 % etc Use Qt's QString::asprintf() A different external dependency. So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked? Thanks. | I am using #3: the boost string format library - but I have to admit that I've never had any problem with the differences in format specifications. Works like a charm for me - and the external dependencies could be worse (a very stable library) Edited: adding an example how to use boost::format instead of printf: sprintf(buffer, "This is a string with some %s and %d numbers", "strings", 42); would be something like this with the boost::format library: string = boost::str(boost::format("This is a string with some %s and %d numbers") %"strings" %42); Hope this helps clarify the usage of boost::format I've used boost::format as a sprintf / printf replacement in 4 or 5 applications (writing formatted strings to files, or custom output to logfiles) and never had problems with format differences. There may be some (more or less obscure) format specifiers which are differently - but I never had a problem. In contrast I had some format specifications I couldn't really do with streams (as much as I remember) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/69738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8146/"
]
} |
69,761 | I'd like to to associate a file extension to the current executable in C#.This way when the user clicks on the file afterwards in explorer, it'll run my executable with the given file as the first argument.Ideally it'd also set the icon for the given file extensions to the icon for my executable.Thanks all. | There doesn't appear to be a .Net API for directly managing file associations but you can use the Registry classes for reading and writing the keys you need to. You'll need to create a key under HKEY_CLASSES_ROOT with the name set to your file extension (eg: ".txt"). Set the default value of this key to a unique name for your file type, such as "Acme.TextFile". Then create another key under HKEY_CLASSES_ROOT with the name set to "Acme.TextFile". Add a subkey called "DefaultIcon" and set the default value of the key to the file containing the icon you wish to use for this file type. Add another sibling called "shell". Under the "shell" key, add a key for each action you wish to have available via the Explorer context menu, setting the default value for each key to the path to your executable followed by a space and "%1" to represent the path to the file selected. For instance, here's a sample registry file to create an association between .txt files and EmEditor: Windows Registry Editor Version 5.00[HKEY_CLASSES_ROOT\.txt]@="emeditor.txt"[HKEY_CLASSES_ROOT\emeditor.txt]@="Text Document"[HKEY_CLASSES_ROOT\emeditor.txt\DefaultIcon]@="%SystemRoot%\\SysWow64\\imageres.dll,-102"[HKEY_CLASSES_ROOT\emeditor.txt\shell][HKEY_CLASSES_ROOT\emeditor.txt\shell\open][HKEY_CLASSES_ROOT\emeditor.txt\shell\open\command]@="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" \"%1\""[HKEY_CLASSES_ROOT\emeditor.txt\shell\print][HKEY_CLASSES_ROOT\emeditor.txt\shell\print\command]@="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" /p \"%1\"" | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/69761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
69,768 | Mac OS X ships with apache pre-installed, but the files are in non-standard locations. This question is a place to collect information about where configuration files live, and how to tweak the apache installation to do things like serve php pages. | Apache Config file is: /private/etc/apache2/httpd.conf Default DocumentRoot is: /Library/Webserver/Documents/ To enable PHP, at around line 114 (maybe) in the /private/etc/apache2/httpd.conf file is the following line: #LoadModule php5_module libexec/apache2/libphp5.so Remove the pound sign to uncomment the line so now it looks like this: LoadModule php5_module libexec/apache2/libphp5.so Restart Apache: System Preferences -> Sharing -> Un-check "Web Sharing" and re-check it. OR $ sudo apachectl restart | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/69768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575/"
]
} |
69,835 | I have to admit that I always forgot the syntactical intracacies of the naming patterns for Nant (eg. those used in filesets). The double asterisk/single asterisk stuff seems to be very forgettable in my mind. Can someone provide a definitive guide to the naming patterns? | The rules are: a single star (*) matches zero or more characters within a path name a double star (**) matches zero or more characters across directory levels a question mark (?) matches exactly one character within a path name Another way to think about it is double star (**) matches slash (/) but single star (*) does not. Let's say you have the files: bar.txt src/bar.c src/baz.c src/test/bartest.c Then the patterns: *.c matches nothing (there are no .c files in the current directory) src/*.c matches 2 and 3 */*.c matches 2 and 3 (because * only matches one level) **/*.c matches 2, 3, and 4 (because ** matches any number of levels) bar.* matches 1 **/bar.* matches 1 and 2 **/bar*.* matches 1, 2, and 4 src/ba?.c matches 2 and 3 | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/69835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884/"
]
} |
69,843 | Does anybody have useful example of this assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself. | The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you can for a struct type: public struct MyValueType{ public int Id; public void Swap(ref MyValueType other) { MyValueType temp = this; this = other; other = temp; }} At any point a struct can alter itself by assigning to 'this' like so. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/69843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
]
} |
69,849 | When is it a good idea to use factory methods within an object instead of a Factory class? | I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other. So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it. So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually hire someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that. In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want. public interface IThingFactory{ Thing GetThing(string theString);}public class ThingFactory : IThingFactory{ public Thing GetThing(string theString) { return new Thing(theString, firstDependency, secondDependency); }} So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/69849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
69,913 | What is the reason browsers do not correctly recognize: <script src="foobar.js" /> <!-- self-closing script element --> Only this is recognized: <script src="foobar.js"></script> Does this break the concept of XHTML support? Note: This statement is correct at least for all IE (6-8 beta 2). | The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says: С.3. Element Minimization and Empty Element Content Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use <p> </p> and not <p /> ). XHTML DTD specifies script elements as: <!-- script statements, which may include CDATA sections --><!ELEMENT script (#PCDATA)> | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/69913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10778/"
]
} |
69,934 | I've been unsuccessful in getting Emacs to switch from 8 space tabs to 4 space tabs when pressing the TAB in buffers with the major mode text-mode . I've added the following to my .emacs : (setq-default indent-tabs-mode nil)(setq-default tab-width 4);;; And I have tried(setq indent-tabs-mode nil)(setq tab-width 4) No matter how I change my .emacs file (or my buffer's local variables) the TAB button always does the same thing. If there is no text above, indent 8 spaces If there is text on the previous line, indent to the beginning of the second word As much as I love Emacs this is getting annoying. Is there a way to make Emacs to at least indent 4 space when there's not text in the previous line? | Short answer: The key point is to tell emacs to insert whatever you want when indenting, this is done by changing the indent-line-function. It is easier to change it to insert a tab and then change tabs into 4 spaces than change it to insert 4 spaces. The following configuration will solve your problem: (setq-default indent-tabs-mode nil)(setq-default tab-width 4)(setq indent-line-function 'insert-tab) Explanation: From Indentation Controlled by Major Mode @ emacs manual : An important function of each major mode is to customize the key to indent properly for the language being edited. [...] The indent-line-function variable is the function to be used by (and various commands, like when calling indent-region) to indent the current line. The command indent-according-to-mode does no more than call this function. [...] The default value is indent-relative for many modes. From indent-relative @ emacs manual: Indent-relative Space out to under next indent point in previous nonblank line. [...] If the previous nonblank line has no indent points beyond the column point starts at, `tab-to-tab-stop' is done instead. Just change the value of indent-line-function to the insert-tab function and configure tab insertion as 4 spaces. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/69934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
]
} |
69,998 | How do I prevent vim from replacing spaces with tabs when autoindent is on? An example: if I have two tabs and 7 spaces in the beginning of the line, and tabstop=3 , and I press Enter, the next line has four tabs and 1 space in the beginning, but I don't want that... | It is perhaps a good idea not to use tabs at all. :set expandtab If you want to replace all the tabs in your file to 3 spaces (which will look pretty similar to tabstop=3 ): :%s/^I/ / (where ^I is the TAB character) From the VIM online help: 'tabstop' 'ts' number (default 8) local to bufferNumber of spaces that a <Tab> in the file counts for. Also see|:retab| command, and 'softtabstop' option.Note: Setting 'tabstop' to any other value than 8 can make your fileappear wrong in many places (e.g., when printing it).There are four main ways to use tabs in Vim:1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4 (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim will use a mix of tabs and spaces, but typing <Tab> and <BS> will behave like a tab appears every 4 (or 3) characters.2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use 'expandtab'. This way you will always insert spaces. The formatting will never be messed up when 'tabstop' is changed.3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a |modeline| to set these values when editing the file again. Only works when using Vim to edit the file.4. Always set 'tabstop' and 'shiftwidth' to the same value, and 'noexpandtab'. This should then work (for initial indents only) for any tabstop setting that people use. It might be nice to have tabs after the first non-blank inserted as spaces if you do this though. Otherwise aligned comments will be wrong when 'tabstop' is changed. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/69998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
70,004 | As a lot of people pointed out in this question , Lisp is mostly used as a learning experience. Nevertheless, it would be great if I could somehow use my Lisp algorithms and combine them with my C# programs.In college my profs never could tell me how to use my Lisp routines in a program (no, not writing a GUI in Lisp, thank you).So how can I? | Try these .Net implementations of Lisp: IronScheme IronScheme will aim to be a R6RS conforming Scheme implementation based on the Microsoft DLR. L Sharp .NET L Sharp .NET is a powerful Lisp-like scripting language for .NET. It uses a Lisp dialect similar to Arc but tightly integrates with the .NET Framework which provides a rich set of libraries. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
]
} |
70,013 | Is there any way to know if I'm compiling under a specific Microsoft Visual Studio version? | _MSC_VER and possibly _MSC_FULL_VER is what you need. You can also examine visualc.hpp in any recent boost install for some usage examples. Some values for the more recent versions of the compiler are: MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)MSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)MSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)MSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 version 16.0)MSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)MSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)MSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)MSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)MSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)MSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)MSVC++ 14.1 _MSC_VER == 1910 (Visual Studio 2017 version 15.0)MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015 version 14.0)MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013 version 12.0)MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012 version 11.0)MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010 version 10.0)MSVC++ 9.0 _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008 version 9.0)MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005 version 8.0)MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)MSVC++ 5.0 _MSC_VER == 1100 (Visual Studio 97 version 5.0) The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found here . Starting recently , Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values. cl.exe /? will give a hint of the used version, e.g.: c:\program files (x86)\microsoft visual studio 11.0\vc\bin>cl /?Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86..... | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/70013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
]
} |
70,109 | I'm writing an ASP.Net webform with some DropDownList controls on it. Then user changes selected item in one of dropdowns, ASP.Net doesn't seem to handle SelectedIndexChanged event until form is submitted with a 'Submit' button click.How do I make my dropdowns handle SelectedIndexChanged instantly? P.S. It's a classic question I have answered too many times, but it seems no one asked it before on stackoverflow. | Setting the AutoPostback property to true will cause it to postback when the selection is changed. Please note that this requires javascript to be enabled. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/70109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9024/"
]
} |
70,140 | I'm cleaning up some old Maildir folders, and finding messages with names like: 1095812260.M625118P61205V0300FF04I002DC537_0.redoak.cise.ufl.edu,S=2576:2,ST They don't show up in my IMAP client, so I presume there's some semaphore indicating the message already got moved somewhere else. Is that the case, and can the files be deleted without remorse? | The 'M' is just part of the unique filename and has nothing to do with the fact that the mail doesn't show up in mail clients. The 'T' at the end of the filename, after the ':' sign, however tells the IMAP server that this message is Trashed. See http://cr.yp.to/proto/maildir.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10841/"
]
} |
70,143 | I have a xslt stylesheet with multiple xsl:import s and I want to merge them all into the one xslt file. It is a limitation of the system we are using where it passes around the xsl stylesheet as a string object stored in memory. This is transmitted to remote machine where it performs the transformation. Since it is not being loaded from disk the href links are broken, so we need to remove the xsl:import s from the stylesheet. Are there any tools out there which can do this? | You can use an XSL stylesheet to merge your stylesheets. However, this is equivalent to using the xsl:include element, not xsl:import (as Azat Razetdinov has already pointed out). You can read up on the difference here . Therefore you should first replace the xsl:import's with xsl:include's, resolve any conflicts and test whether you still get the correct results. After that, you could use the following stylesheet to merge your existing stylesheets into one. Just apply it to your master stylesheet: <?xml version="1.0" ?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"><xsl:template match="xsl:include"> <xsl:copy-of select="document(@href)/xsl:stylesheet/*"/></xsl:template><xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy></xsl:template></xsl:stylesheet> The first template replaces all xsl:include's with the included stylesheets by using the document function, which reads in the file referenced in the href attribute. The second template is the identity transformation . I've tested it with Xalan and it seems to work fine. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
]
} |
70,161 | As we all know numbers can be written either in numerics, or called by their names. While there are a lot of examples to be found that convert 123 into one hundred twenty three, I could not find good examples of how to convert it the other way around. Some of the caveats: cardinal/nominal or ordinal: "one" and "first" common spelling mistakes: "forty"/"fourty" hundreds/thousands: 2100 -> "twenty one hundred" and also "two thousand and one hundred" separators: "eleven hundred fifty two", but also "elevenhundred fiftytwo" or "eleven-hundred fifty-two" and whatnot colloquialisms: "thirty-something" fractions: 'one third', 'two fifths' common names: 'a dozen', 'half' And there are probably more caveats possible that are not yet listed.Suppose the algorithm needs to be very robust, and even understand spelling mistakes. What fields/papers/studies/algorithms should I read to learn how to write all this?Where is the information? PS: My final parser should actually understand 3 different languages, English, Russian and Hebrew. And maybe at a later stage more languages will be added. Hebrew also has male/female numbers, like "one man" and "one woman" have a different "one" — "ehad" and "ahat". Russian also has some of its own complexities. Google does a great job at this. For example: http://www.google.com/search?q=two+thousand+and+one+hundred+plus+five+dozen+and+four+fifths+in+decimal (the reverse is also possible http://www.google.com/search?q=999999999999+in+english ) | I was playing around with a PEG parser to do what you wanted (and may post that as a separate answer later) when I noticed that there's a very simple algorithm that does a remarkably good job with common forms of numbers in English, Spanish, and German, at the very least. Working with English for example, you need a dictionary that maps words to values in the obvious way: "one" -> 1, "two" -> 2, ... "twenty" -> 20,"dozen" -> 12, "score" -> 20, ..."hundred" -> 100, "thousand" -> 1000, "million" -> 1000000 ...and so forth The algorithm is just: total = 0prior = nullfor each word w v <- value(w) or next if no value defined prior <- case when prior is null: v when prior > v: prior+v else prior*v else if w in {thousand,million,billion,trillion...} total <- total + prior prior <- nulltotal = total + prior unless prior is null For example, this progresses as follows: total prior v unconsumed string 0 _ four score and seven 4 score and seven 0 4 20 and seven 0 80 _ seven 0 80 7 0 87 87total prior v unconsumed string 0 _ two million four hundred twelve thousand eight hundred seven 2 million four hundred twelve thousand eight hundred seven 0 2 1000000 four hundred twelve thousand eight hundred seven2000000 _ 4 hundred twelve thousand eight hundred seven2000000 4 100 twelve thousand eight hundred seven2000000 400 12 thousand eight hundred seven2000000 412 1000 eight hundred seven2000000 412000 1000 eight hundred seven2412000 _ 8 hundred seven2412000 8 100 seven2412000 800 72412000 8072412807 And so on. I'm not saying it's perfect, but for a quick and dirty it does quite well. Addressing your specific list on edit: cardinal/nominal or ordinal: "one" and "first" -- just put them in the dictionary english/british: "fourty"/"forty" -- ditto hundreds/thousands: 2100 -> "twenty one hundred" and also "two thousand and one hundred" -- works as is separators: "eleven hundred fifty two", but also "elevenhundred fiftytwo" or "eleven-hundred fifty-two" and whatnot -- just define "next word" to be the longest prefix that matches a defined word, or up to the next non-word if none do, for a start colloqialisms: "thirty-something" -- works fragments: 'one third', 'two fifths' -- uh, not yet... common names: 'a dozen', 'half' -- works; you can even do things like "a half dozen" Number 6 is the only one I don't have a ready answer for, and that's because of the ambiguity between ordinals and fractions (in English at least) added to the fact that my last cup of coffee was many hours ago. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/70161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11414/"
]
} |
70,169 | I want to highlight C/C++/Java/C# etc source codes in my website. How can I do this? Is it a CPU intensive job to highlight the source code? | You can either do this server-side or client-side. It's not very processor intensive, but if you do it client side (using Javascript) there will be a noticeable lag. Most client side solutions revolve around Google Code's syntax highlighting engine. This seems to be the most popular one: SyntaxHighlighter Server-side solutions tend to be more flexible, especially in the way of defining new languages and configuring how they are highlighted (e.g. colors used). I use GeSHi, which is a PHP solution with a moderately nice plugin for Wordpress. There are also a few libraries built for Java, and even some that are based upon VIM (usually requiring a Perl module to be installed from CPAN). In short: you have quite a few options, what are your criteria? It's hard to make a solid recommendation without knowing your requirements. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/70169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
70,216 | In Java, you often see a META-INF folder containing some meta files. What is the purpose of this folder and what can I put there? | From the official JAR File Specification (link goes to the Java 7 version, but the text hasn't changed since at least v1.3): The META-INF directory The following files/directories in the META-INF directory are recognized and interpreted by the Java 2 Platform to configure applications, extensions, class loaders and services: MANIFEST.MF The manifest file that is used to define extension and package related data. INDEX.LIST This file is generated by the new " -i " option of the jar tool, which contains location information for packages defined in an application or extension. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process. x.SF The signature file for the JAR file. 'x' stands for the base file name. x.DSA The signature block file associated with the signature file with the same base file name. This file stores the digital signature of the corresponding signature file. services/ This directory stores all the service provider configuration files. New since Java 9 implementing JEP 238 are multi-release JARs. One will see a sub folder versions . This is a feature which allows to package classes which are meant for different Java version in one jar. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/70216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11429/"
]
} |
70,272 | I have an application with one form in it, and on the Load method I need to hide the form. The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy. Any suggestions? | I'm coming at this from C#, but should be very similar in vb.net. In your main program file, in the Main method, you will have something like: Application.Run(new MainForm()); This creates a new main form and limits the lifetime of the application to the lifetime of the main form. However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like. Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling Form.Show() or Form.Hide() from handlers of NotifyIcon events will show and hide the form respectively. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/70272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1500/"
]
} |
70,303 | I have a structure in C#: public struct UserInfo{ public string str1 { get; set; } public string str2 { get; set; } } The only rule is that UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA")) How to override the GetHashCode function for this structure? | MSDN : A hash function must have the following properties: If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values. The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again. For the best performance, a hash function must generate a random distribution for all input. Taking it into account correct way is: return str1.GetHashCode() ^ str2.GetHashCode() ^ can be substituted with other commutative operation | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/70303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
} |
70,324 | What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these? | From the Java Tutorial : Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. Static nested classes are accessed using the enclosing class name: OuterClass.StaticNestedClass For example, to create an object for the static nested class, use this syntax: OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes: class OuterClass { ... class InnerClass { ... }} An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass()OuterClass.InnerClass innerObject = outerObject.new InnerClass(); see: Java Tutorial - Nested Classes For completeness note that there is also such a thing as an inner class without an enclosing instance : class A { int t() { return 1; } static A a = new A() { int t() { return 2; } };} Here, new A() { ... } is an inner class defined in a static context and does not have an enclosing instance. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/70324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
]
} |
70,377 | Is there any way to prevent Visual Studio from creating a VSMacros80 folder in my default project directory? | I just found it out myself: If you add a trailing backslash to the Project Folder setting e.g. changing it from C:\dev to C:\dev\ , the VSMacros80 directory will no longer be created. I tested it with Visual Studio 2005 SP1, with all windows updates installed. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11387/"
]
} |
70,392 | Is there a distributed version control system (git, bazaar, mercurial, darcs etc.) that can handle files larger than available RAM? I need to be able to commit large binary files (i.e. datasets, source video/images, archives), but I don't need to be able to diff them, just be able to commit and then update when the file changes. I last looked at this about a year ago, and none of the obvious candidates allowed this, since they're all designed to diff in memory for speed. That left me with a VCS for managing code and something else ("asset management" software or just rsync and scripts) for large files, which is pretty ugly when the directory structures of the two overlap. | It's been 3 years since I asked this question, but, as of version 2.0 Mercurial includes the largefiles extension , which accomplishes what I was originally looking for: The largefiles extension allows for tracking large, incompressible binary files in Mercurial without requiring excessive bandwidth for clones and pulls. Files added as largefiles are not tracked directly by Mercurial; rather, their revisions are identified by a checksum, and Mercurial tracks these checksums. This way, when you clone a repository or pull in changesets, the large files in older revisions of the repository are not needed, and only the ones needed to update to the current version are downloaded. This saves both disk space and bandwidth. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11438/"
]
} |
70,402 | I was asked this question during an interview. They're both O(nlogn) and yet most people use Quicksort instead of Mergesort. Why is that? | Quicksort has O( n 2 ) worst-case runtime and O( n log n ) average case runtime. However, it’s superior to merge sort in many scenarios because many factors influence an algorithm’s runtime, and, when taking them all together, quicksort wins out. In particular, the often-quoted runtime of sorting algorithms refers to the number of comparisons or the number of swaps necessary to perform to sort the data. This is indeed a good measure of performance, especially since it’s independent of the underlying hardware design. However, other things – such as locality of reference (i.e. do we read lots of elements which are probably in cache?) – also play an important role on current hardware. Quicksort in particular requires little additional space and exhibits good cache locality, and this makes it faster than merge sort in many cases. In addition, it’s very easy to avoid quicksort’s worst-case run time of O( n 2 ) almost entirely by using an appropriate choice of the pivot – such as picking it at random (this is an excellent strategy). In practice, many modern implementations of quicksort (in particular libstdc++’s std::sort ) are actually introsort , whose theoretical worst-case is O( n log n ), same as merge sort. It achieves this by limiting the recursion depth, and switching to a different algorithm ( heapsort ) once it exceeds log n . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/70402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
]
} |
70,405 | I'm doing simple string input parsing and I am in need of a string tokenizer. I am new to C# but have programmed Java, and it seems natural that C# should have a string tokenizer. Does it? Where is it? How do I use it? | You could use String.Split method . class ExampleClass{ public ExampleClass() { string exampleString = "there is a cat"; // Split string on spaces. This will separate all the words in a string string[] words = exampleString.Split(' '); foreach (string word in words) { Console.WriteLine(word); // there // is // a // cat } }} For more information see Sam Allen's article about splitting strings in c# (Performance, Regex) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/70405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
70,417 | I have the following code: Dim obj As New Access.Applicationobj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")obj.Run "Routine"obj.CloseCurrentDatabaseSet obj = Nothing The problem I'm experimenting is a pop-up that tells me Access can't set the focus on the other database. As you can see from the code, I want to run a Subroutine in another mdb. Any other way to achieve this will be appreciated. I'm working with MS Access 2003. This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened. I suspect this may occur when someone is working with this or the other database. The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database. Maybe, it's because of the first line in the 'Routines' code: If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then Exit Function End If I'll make another subroutine without the MsgBox. I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user. This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened. I suspect this may occur when someone is working with this or the other database. The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database. Maybe, it's because of the first line in the 'Routines' code: If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then Exit Function End If I'll make another subroutine without the MsgBox. I've tried this in our development database and it works. This doesn't mean anything as the other code also workes fine in development. | You could use String.Split method . class ExampleClass{ public ExampleClass() { string exampleString = "there is a cat"; // Split string on spaces. This will separate all the words in a string string[] words = exampleString.Split(' '); foreach (string word in words) { Console.WriteLine(word); // there // is // a // cat } }} For more information see Sam Allen's article about splitting strings in c# (Performance, Regex) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/70417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11498/"
]
} |
70,446 | There are multiple Ruby implementations in the works right now. Which are you looking forward to and why? Do you actively use a non-MRI implementation in production? Some of the options include: Ruby MRI (original 1.8 branch) YARV (official 1.9) JRuby Rubinius IronRuby - Ironruby.net MagLev (Thanks Julian ) Github link MacRuby (Thanks Damien Pollet ) | Maglev . It will have the speed benefit of all the optimization that has gone into a major Smalltalk VM over many, many year. Plus it will automatically persist all your data pretty much automatically so there is no more need to monkey around with Object-Relational mapping layers and so on. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10322/"
]
} |
70,450 | I'm already using salted hashing to store passwords in my database, which means that I should be immune to rainbow table attacks. I had a thought, though: what if someone does get hold of my database? It contains the users' email addresses. I can't really hash these, because I'll be using them to send notification emails, etc.. Should I encrypt them? | Bruce Schneier has a good response to this kind of problem. Cryptography is not the solution to your security problems. It might be part of the solution, or it might be part of the problem. In many situations, cryptography starts out by making the problem worse, and it isn't at all clear that using cryptography is an improvement. Essentially encrypting your emails in the database 'just in case' is not really making the database more secure. Where are the keys stored for the database? What file permissions are used for these keys? Is the database accesable publically? Why? What kind of account restrictions are in place for these accounts? Where is the machine stored, who has physical access to this box? What about remote login/ssh access etc. etc. etc. So I guess you can encrypt the emails if you want, but if that is the extent of the security of the system then it really isn't doing much, and would actually make the job of maintaining the database harder. Of course this could be part of an extensive security policy for your system - if so then great! I'm not saying that it is a bad idea - But why have a lock on the door from Deadlocks'R'us which cost $5000 when they can cut through the plywood around the door? Or come in through the window which you left open? Or even worse they find the key which was left under the doormat. Security of a system is only as good as the weakest link. If they have root access then they can pretty much do what they want. Steve Morgan makes a good point that even if they cannot understand the email addresses, they can still do a lot of harm (which could be mitigated if they only had SELECT access) Its also important to know what your reasons are for storing the email address at all. I might have gone a bit overboard with this answer , but my point is do you really need to store an email address for an account? The most secure data is data that doesn't exist. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/70450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
]
} |
70,453 | For writing scripts for process automisation in Linux platform, which scripting language will be better? Shell script, Perl or Python or is there anything else? I am new to all of them. So, am just thinking to which one to go for? | The answer is: Whatever best fits the job! My rule of thumb; Bash - for a short script that might need a for loop to do something repetitively. Perl - anything to do with some kind of text processing or file processing, especially if it's a one off. Just do a dirty nasty perl script and be done with it Python - If it's something you might want to do again or something very like it. Then at least you have a chance of being able to reuse the script. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/70453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11372/"
]
} |
70,455 | I want to port data from one server's database to another server's database.The databases are both on a different mssql 2005 server.Replication is probably not an option since the destination database is generated from scratch on a [time interval] basis. Preferebly I would do something like insert *from db1/table1into db2/table2where rule1 = true It's obvious that connection credentials would go in somehwere in this script. | I think what you want to do is create a linked server as per this webarchive snapshot of msdn article from 2015 or this article from learn.microsoft.com . You would then select using a 4 part object name eg: Select * From ServerName.DbName.SchemaName.TableName | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/70455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
]
} |
70,471 | So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties! Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something? | There is a "standard" pattern for getters and setters in Java, called Bean properties . Basically any method starting with get , taking no arguments and returning a value, is a property getter for a property named as the rest of the method name (with a lowercased start letter). Likewise set creates a setter of a void method with a single argument. For example: // Getter for "awesomeString"public String getAwesomeString() { return awesomeString;}// Setter for "awesomeString"public void setAwesomeString( String awesomeString ) { this.awesomeString = awesomeString;} Most Java IDEs will generate these methods for you if you ask them (in Eclipse it's as simple as moving the cursor to a field and hitting Ctrl - 1 , then selecting the option from the list). For what it's worth, for readability you can actually use is and has in place of get for boolean-type properties too, as in: public boolean isAwesome();public boolean hasAwesomeStuff(); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/70471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227/"
]
} |
70,513 | This question is overflow from the following question: How do I programmatically convert mp3 to an itunes-playable aac/m4a file? Anyway, I learned how to create an aac file and then i found out that an aac is not just an m4a file with a different file extension. In fact, I need to somehow wrap the aac into an m4a container. Ideally I'd be able to simply make a call to the command line. | ffmpeg is a general purpose (de)muxer/transcoder. MP4Box is a (de)muxer/transcoder from GPAC , a package dedicated to MP4 related software tech. Right now it seems wiser to use MP4Box because it writes the moov atom at the beginning of the file, which is important for streaming and ipod playing. Use ffmpeg like this: ffmpeg -i input.aac -codec: copy output.m4a Use MP4Box like this: MP4Box -add input.aac#audio output.m4a | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
70,516 | I have the ISO week and year but how do I correctly convert that into two dates representing the start and end of that week? | ffmpeg is a general purpose (de)muxer/transcoder. MP4Box is a (de)muxer/transcoder from GPAC , a package dedicated to MP4 related software tech. Right now it seems wiser to use MP4Box because it writes the moov atom at the beginning of the file, which is important for streaming and ipod playing. Use ffmpeg like this: ffmpeg -i input.aac -codec: copy output.m4a Use MP4Box like this: MP4Box -add input.aac#audio output.m4a | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/70516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/966/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.