qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
166,340
|
<p>I need to zip and password-protect a file. Is there a good (free) library for this?</p>
<p>This needs to be opened by a third party, so the password protection needs to work with standard tools.</p>
|
[
{
"answer_id": 13055556,
"author": "Marc",
"author_id": 97438,
"author_profile": "https://Stackoverflow.com/users/97438",
"pm_score": 2,
"selected": false,
"text": "import de.idyl.winzipaes.AesZipFileEncrypter;\nimport de.idyl.winzipaes.impl.AESEncrypterBC;\n\nFile aNewZipFile = new File(\"/tmp/foo.zip\");\nFile existingUnzippedFile = new File(\"/tmp/src.txt\");\n\n// We use the bouncy castle encrypter, as opposed to the JCA encrypter\nAESEncrypterBC encrypter = new AESEncrypterBC();\nencrypter.init(\"my-password\", 0); // The 0 is keySize, it is ignored for AESEncrypterBC\n\nAesZipFileEncrypter zipEncrypter = new AesZipFileEncrypter(aNewZipFile, encrypter);\nzipEncrypter.add(existingUnzippedFile, \"src.txt\", \"my-password\"); \n\n// remember to close the zipEncrypter\nzipEncrypter.close();\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23447/"
] |
166,347
|
<p>I have some simple shell scripting tasks that I want to do </p>
<p>For example: Selecting a file in the working directory from a list of the files matching some regular expression.</p>
<p>I know that I can do this sort of thing using standard bash and grep but I would be nice to be able to hack quick scripts that will work in windows and linux without me having to memorize a heap of command line programs and flags etc.</p>
<p>I tried to get this going but ended up getting confused about where I should be getting information such as a reference to the current directory</p>
<p>So the question is what parts of the Ruby libraries do I need to know to write ruby shell scripts?</p>
|
[
{
"answer_id": 166357,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 3,
"selected": false,
"text": "#!/path/to/ruby\n chmod a+x myscript.rb\n"
},
{
"answer_id": 166373,
"author": "Vasil",
"author_id": 7883,
"author_profile": "https://Stackoverflow.com/users/7883",
"pm_score": 4,
"selected": false,
"text": "script.rb #!/usr/bin/env ruby\n chmod +x script.rb"
},
{
"answer_id": 166432,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env ruby\n chmod +x script.rb\n"
},
{
"answer_id": 166445,
"author": "Georg Schölly",
"author_id": 24587,
"author_profile": "https://Stackoverflow.com/users/24587",
"pm_score": 7,
"selected": false,
"text": "#!/usr/bin/env ruby\n chmod +x test.rb\n File.open(\"file\", \"r\") do |io|\n # do something with io\nend\n pwd $0 #!/usr/bin/env ruby\nrequire 'pathname'\np Pathname.new($0).realpath()\n"
},
{
"answer_id": 166541,
"author": "bltxd",
"author_id": 11892,
"author_profile": "https://Stackoverflow.com/users/11892",
"pm_score": 2,
"selected": false,
"text": "__FILE__ /usr/bin/env #! /usr/bin/env ruby\n# Extension of this script does not matter as long\n# as it is executable (chmod +x)\nputs File.expand_path(__FILE__)\n # This script filename must end with .rb\nputs File.expand_path(__FILE__)\n @ruby %~dp0\\my_script.rb\n puts File.expand_path(__FILE__)\n"
},
{
"answer_id": 166854,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 8,
"selected": true,
"text": "Dir['*.rb'] #basic globs\nDir['**/*.rb'] #** == any depth of directory, including current dir.\n#=> array of relative names\n\nFile.expand_path('~/file.txt') #=> \"/User/mat/file.txt\"\nFile.dirname('dir/file.txt') #=> 'dir'\nFile.basename('dir/file.txt') #=> 'file.txt'\nFile.join('a', 'bunch', 'of', 'strings') #=> 'a/bunch/of/strings'\n\n__FILE__ #=> the name of the current file\n require 'fileutils' #I know, no underscore is not ruby-like\ninclude FileUtils\n# Gives you access (without prepending by 'FileUtils.') to\ncd(dir, options)\ncd(dir, options) {|dir| .... }\npwd()\nmkdir(dir, options)\nmkdir(list, options)\nmkdir_p(dir, options)\nmkdir_p(list, options)\nrmdir(dir, options)\nrmdir(list, options)\nln(old, new, options)\nln(list, destdir, options)\nln_s(old, new, options)\nln_s(list, destdir, options)\nln_sf(src, dest, options)\ncp(src, dest, options)\ncp(list, dir, options)\ncp_r(src, dest, options)\ncp_r(list, dir, options)\nmv(src, dest, options)\nmv(list, dir, options)\nrm(list, options)\nrm_r(list, options)\nrm_rf(list, options)\ninstall(src, dest, mode = <src's>, options)\nchmod(mode, list, options)\nchmod_R(mode, list, options)\nchown(user, group, list, options)\nchown_R(user, group, list, options)\ntouch(list, options)\n"
},
{
"answer_id": 1806991,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 6,
"selected": false,
"text": "#!/usr/bin/env ruby\nputs \"I was passed: \"\nARGV.each do |value|\n puts value\nend\n chmod u+x my_shell_script\n > ./my_shell_script one two three four five\n I was passed: \none\ntwo\nthree\nfour\nfive\n ./my_shell_script *\n\nI was passed: \na_file_in_the_current_directory\nanother_file \nmy_shell_script\nthe_last_file\n"
},
{
"answer_id": 2392597,
"author": "Dan Rosenstark",
"author_id": 8047,
"author_profile": "https://Stackoverflow.com/users/8047",
"pm_score": 5,
"selected": false,
"text": "puts `find . | grep -i lib`\n out = `git status 2>&1`\n blah = 'lib'\n`touch #{blah}`\n shell_here #!/usr/bin/env ruby\n`env | pbcopy` \ncmd = %Q@tell app \"Terminal\" to do script \"$(paste_env)\"@\nputs cmd\n\n`osascript -e \"${cmd}\"`\n"
},
{
"answer_id": 40916488,
"author": "Houcheng",
"author_id": 1196716,
"author_profile": "https://Stackoverflow.com/users/1196716",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/env ruby\nmodule ShellHelper\n def test(command)\n `#{command} 2> /dev/null`\n $?.success?\n end\n\n def execute(command, raise_on_error = true)\n result = `#{command}`\n raise \"execute command failed\\n\" if (not $?.success?) and raise_on_error\n return $?.success?\n end\n\n def print_exit(message)\n print \"#{message}\\n\"\n exit\n end\n\n module_function :execute, :print_exit, :test\nend\n #!/usr/bin/env ruby\nrequire './shell_helper'\ninclude ShellHelper\n\nprint_exit \"config already exists\" if test \"ls config\"\n\nthings.each do |thing|\n next if not test \"ls #{thing}/config\"\n execute \"cp -fr #{thing}/config_template config/#{thing}\"\nend\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24773/"
] |
166,356
|
<p>This semester, I took a course in computer graphics at my University. At the moment, we're starting to get into some of the more advanced stuff like heightmaps, averaging normals, tesselation etc.</p>
<p>I come from an object-oriented background, so I'm trying to put everything we do into reusable classes. I've had good success creating a camera class, since it depends mostly on the one call to gluLookAt(), which is pretty much independent of the rest of the OpenGL state machine.</p>
<p>However, I'm having some trouble with other aspects. Using objects to represent primitives hasn't really been a success for me. This is because the actual render calls depend on so many external things, like the currently bound texture etc. If you suddenly want to change from a surface normal to a vertex normal for a particular class it causes a severe headache.</p>
<p>I'm starting to wonder whether OO principles are applicable in OpenGL coding. At the very least, I think that I should make my classes less granular.</p>
<p>What is the stack overflow community's views on this? What are your best practices for OpenGL coding?</p>
|
[
{
"answer_id": 166613,
"author": "timday",
"author_id": 24283,
"author_profile": "https://Stackoverflow.com/users/24283",
"pm_score": 2,
"selected": false,
"text": " glPushAttrib(GL_ALL_ATTRIB_BITS);\n glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);\n glPopClientAttrib();\n glPopAttrib();\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12828/"
] |
166,360
|
<p>Not too practical maybe, but still interesting.</p>
<p>Having some abstract question on matrix multiplication I have quickly implemented a matrix for ints, then tested my assumptions.</p>
<p>And here I noticed that just int matrix is not good, if I occasionally want to use it with decimal or double. Of course, I <em>could</em> try just to cast all to double, but that's not convenient way.</p>
<p>Continue with assumption we could have a bunch of objects we are able to add and multiply - why don't use them in my matrix?</p>
<p>So, just after considering it would be a Matrix class now I faced that generic T could not be used, I need it to support some interface which could add and multiply.</p>
<p>And the problem is I could override operators in my class, but I could not introduce an interface which would support operators. And I have an operators in built-in types, but still no interface over them.</p>
<p>What would you do in such a case considering you do not want to duplicate worker class body? Wrappers and implicit casting didn't help me much, I'm interested in a beautiful solution.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 168524,
"author": "Ihar Bury",
"author_id": 18001,
"author_profile": "https://Stackoverflow.com/users/18001",
"pm_score": 2,
"selected": false,
"text": "public interface ICalculator<T>\n{\n\n T Add(T x, T y);\n T Multiply(T x, T y);\n\n}\n\npublic class MatrixMultiplier<T>\n{\n\n public MatrixMultiplier(ICalculator<T> calculator) { ... }\n\n}\n\npublic class IntCalculator : ICalculator<int>\n{\n\n public int Add(int x, int y)\n {\n return x + y;\n }\n\n public int Multiply(int x, int y)\n {\n return x * y;\n }\n\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21603/"
] |
166,364
|
<p>I am running a Django through mod_python on Apache on a linux box. I have a custom authentication backend, and middleware that requires authentication for all pages, except static content.</p>
<p>My problem is that after I log in, I will still randomly get the log in screen now and again. It seems to me that each apache process has it's own python process, which in turn has it's own internals. So as long as I get served by the same process I logged in to, everything is fine and dandy. But if my request gets served by a different apache process, I am no longer authenticated.</p>
<p>I have checked the HTTP headers I send with FireBug, and they are the same each time, ie. same cookie.</p>
<p>Is this a known issue and are there workarounds/fixes?</p>
<p>Edit: I have a page that displays a lot of generated images. Some off these will not display. This is because they are too behind the authenticating middleware, so they will randomly put up a login image. However, refreshing this page enough times, and it will eventually work, meaning all processes recognize my session.</p>
|
[
{
"answer_id": 166539,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 2,
"selected": false,
"text": "MaxRequestsPerChild"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
] |
166,370
|
<p>I wonder what's the best deployment directory for Rails apps? Some developers use directories such as <code>/u/apps/#{appname}</code>. Are there <strong>any</strong> advantages when using <code>/u/apps/#{appname}</code> instead of <code>/var/www/#{appname}</code> or other OS default directories?</p>
<p>Obviously I want to pick the directory with the best security properties and the least friction for setting up the server environment.</p>
<p>How do you deploy your Rails apps? Why are you using a specific directory? Do you think it really matters anyway?</p>
|
[
{
"answer_id": 166415,
"author": "changelog",
"author_id": 5646,
"author_profile": "https://Stackoverflow.com/users/5646",
"pm_score": 2,
"selected": false,
"text": "www-data /home/mephisto/www /home/warehouse/www"
},
{
"answer_id": 171184,
"author": "Grant Hutchins",
"author_id": 6304,
"author_profile": "https://Stackoverflow.com/users/6304",
"pm_score": 1,
"selected": false,
"text": "man hier /var RAILS_ROOT"
},
{
"answer_id": 481727,
"author": "Abie",
"author_id": 53166,
"author_profile": "https://Stackoverflow.com/users/53166",
"pm_score": 2,
"selected": false,
"text": "/srv/www/#{appname}"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467/"
] |
166,411
|
<p>I was wondering if it would be possible to retrieve the complete list of security roles defined in a web.xml file in the java code? And if so how to do it?</p>
<p>I am aware of the 'isUserInRole' method but I also want to handle cases where a role is requested but not defined (or spelled differently) in the web.xml file.</p>
|
[
{
"answer_id": 167140,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 3,
"selected": true,
"text": "protected List<String> getSecurityRoles() {\n List<String> roles = new ArrayList<String>();\n ServletContext sc = this.getServletContext();\n InputStream is = sc.getResourceAsStream(\"/WEB-INF/web.xml\");\n\n try {\n SAXReader reader = new SAXReader();\n Document doc = reader.read(is);\n\n Element webApp = doc.getRootElement();\n\n // Type safety warning: dom4j doesn't use generics\n List<Element> roleElements = webApp.elements(\"security-role\");\n for (Element roleEl : roleElements) {\n roles.add(roleEl.element(\"role-name\").getText());\n }\n } catch (DocumentException e) {\n e.printStackTrace();\n }\n\n return roles;\n}\n"
},
{
"answer_id": 36058398,
"author": "Foyta",
"author_id": 322240,
"author_profile": "https://Stackoverflow.com/users/322240",
"pm_score": 0,
"selected": false,
"text": "private List<String> readRoles() {\n List<String> roles = new ArrayList<>();\n InputStream is = getServletContext().getResourceAsStream(\"/WEB-INF/web.xml\");\n\n try {\n DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n Document doc = builder.parse(new InputSource(is));\n\n NodeList securityRoles = doc.getDocumentElement().getElementsByTagName(\"security-role\");\n for (int i = 0; i < securityRoles.getLength(); i++) {\n Node n = securityRoles.item(i);\n if (n.getNodeType() == Node.ELEMENT_NODE) {\n NodeList roleNames = ((Element) n).getElementsByTagName(\"role-name\");\n roles.add(roleNames.item(0).getTextContent().trim()); // lets's assume that <role-name> is always present\n }\n }\n } catch (ParserConfigurationException | SAXException | IOException e) {\n throw new IllegalStateException(\"Exception while reading security roles from web.xml\", e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n logger.warn(\"Exception while closing stream\", e);\n }\n }\n }\n\n return roles;\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18702/"
] |
166,418
|
<p>I have asked our hosting provider to add mod_python to our httpd server. The server appears to be in an hsphere cluster and they appear to use yum to administer it. He is reporting some dependencies missing and I do't quite understand how that could have come about.</p>
<p>versions (this is as much as I have been given):
CentOS 5
apache - 2 (but he's not sure about the exact version)
mod_python - 3.3.1
numpy - 1.1.1
scipy - 0.6.0
yum - 3.2.8
hsphere - 3.1 patch 1</p>
<p>The error he is reporting is as follows:</p>
<pre><code>yum install mod_python
...
Package mod_python.i386 0:3.2.8-3.1 set to be updated
Processing Dependency: httpd >- 2.0.40 for package: mod_python
Processing Dependency: httpd-mmn = 20051115 for package: mod_python
Finished Dependency Resolution
Error: Missing Dependency: httpd >= 2.0.40 is needed by package mod_python
Error: Missing Dependency: httpd-mmn = 20051115 is needed by package mod_python
</code></pre>
<p>Not being a UNIX admin I only have a naive guess about this, but the message would seem to suggest that there is a version mismatch between httpd and mod_python rather than the dependencies being missing completely. </p>
<p>So my question is, what should I ask/tell the Administrator to do?</p>
<p>Is there something obviously wrong with the combination of components above?</p>
|
[
{
"answer_id": 321653,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "yum update apache yum update yum install mod_python"
},
{
"answer_id": 953856,
"author": "GuiSim",
"author_id": 116301,
"author_profile": "https://Stackoverflow.com/users/116301",
"pm_score": 1,
"selected": false,
"text": "$ ./configure --with-apxs=/usr/local/apache2/bin/apxs\n$ ./make\n$ su\n$ make install\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24039/"
] |
166,424
|
<p>I have a web application that generates a long report and I need to print it. If I just print the page it will break at the end of the physical page. How can I calculate where to make a break in the web page so that the page breaks line up with the physical pages when they print?</p>
|
[
{
"answer_id": 166448,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 0,
"selected": false,
"text": "page-break-before/after"
},
{
"answer_id": 166459,
"author": "slashnick",
"author_id": 21030,
"author_profile": "https://Stackoverflow.com/users/21030",
"pm_score": 1,
"selected": false,
"text": "page-break-before: always"
},
{
"answer_id": 166471,
"author": "ewengcameron",
"author_id": 7464,
"author_profile": "https://Stackoverflow.com/users/7464",
"pm_score": 3,
"selected": false,
"text": "<br style=\"page-break-before:always;\">\n <link rel=\"stylesheet\" href=\"print.css\" type=\"text/css\" media=\"print\" />\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386/"
] |
166,431
|
<p>I find it annoying that I can't clear a list. In this example:</p>
<pre><code>a = []
a.append(1)
a.append(2)
a = []
</code></pre>
<p>The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.</p>
<p>The only way I can see of retaining the same pointer is doing something like the following:</p>
<pre><code>for i in range(len(a)):
a.pop()
</code></pre>
<p>This seems pretty long-winded though, is there a better way of solving this?</p>
|
[
{
"answer_id": 166441,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 6,
"selected": true,
"text": "del L[:]\n"
},
{
"answer_id": 57217653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "L[:] = []\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] |
166,438
|
<p>I have been looking for a logging framework for .net (c#) and decided to give log4net a go after reading up on a few question/answer threads here on stackoverflow. I see people mentioning over and over that they use a wrapper class for log4net and I am wonder what that would look like.</p>
<p>I have my code split up into different projects (data access/business/webservice/..).
How would a log4net wrapper class look like? Would the wrapper class need to be included in all of the projects? Should I build it as a separate project all together? </p>
<p>Should the wrapper be a singleton class? </p>
|
[
{
"answer_id": 166477,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 6,
"selected": false,
"text": "public interface ILogger\n{\n void Debug(object message);\n bool IsDebugEnabled { get; }\n\n // continue for all methods like Error, Fatal ...\n}\n\npublic class Log4NetWrapper : ILogger\n{\n private readonly log4net.ILog _logger;\n\n public Log4NetWrapper(Type type)\n {\n _logger = log4net.LogManager.GetLogger(type);\n }\n\n public void Debug(object message)\n {\n _logger.Debug(message);\n }\n\n public bool IsDebugEnabled\n {\n get { return _logger.IsDebugEnabled; }\n }\n\n // complete ILogger interface implementation\n}\n\npublic static class LogManager\n{\n public static ILogger GetLogger(Type type)\n {\n // if configuration file says log4net...\n return new Log4NetWrapper(type);\n // if it says Joe's Logger...\n // return new JoesLoggerWrapper(type);\n }\n}\n private static readonly ILogger _logger =\n LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n private static readonly ILogger _logger = \n LogManager.GetLogger(typeof(YourTypeName));\n"
},
{
"answer_id": 588912,
"author": "Alconja",
"author_id": 68727,
"author_profile": "https://Stackoverflow.com/users/68727",
"pm_score": 5,
"selected": false,
"text": "LogManager public static ILogger GetLogger()\n{\n var stack = new StackTrace();\n var frame = stack.GetFrame(1);\n return new Log4NetWrapper(frame.GetMethod().DeclaringType);\n}\n private static readonly ILogger _logger = LogManager.GetLogger();\n private static readonly ILogger _logger =\n LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\nprivate static readonly ILogger _logger = \n LogManager.GetLogger(typeof(YourTypeName));\n MethodBase.GetCurrentMethod().DeclaringType"
},
{
"answer_id": 1286900,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "LoggingService.LogError(\"my error message\");\n public static class LoggingService\n{\n private static ILog GetLogger()\n { \n var stack = new StackTrace(); \n var frame = stack.GetFrame(2); \n return log4net.LogManager.GetLogger(frame.GetMethod().DeclaringType);\n }\n\n public static void LogError(string message)\n {\n ILog logger = GetLogger();\n if (logger.IsErrorEnabled)\n logger.Error(message);\n }\n ...\n}\n"
},
{
"answer_id": 35164947,
"author": "Jeson Martajaya",
"author_id": 868532,
"author_profile": "https://Stackoverflow.com/users/868532",
"pm_score": 1,
"selected": false,
"text": "using System;\n\nnamespace Framework.Logging\n{\n public class Logger\n {\n private readonly log4net.ILog _log;\n\n public Logger()\n {\n _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);\n }\n\n public Logger(string name)\n {\n _log = log4net.LogManager.GetLogger(name);\n }\n\n public Logger(Type type)\n {\n _log = log4net.LogManager.GetLogger(type);\n }\n\n public void Debug(object message, Exception ex = null)\n {\n if (_log.IsDebugEnabled)\n {\n if (ex == null)\n {\n _log.Debug(message);\n }\n else\n {\n _log.Debug(message, ex);\n }\n }\n }\n\n public void Info(object message, Exception ex = null)\n {\n if (_log.IsInfoEnabled)\n {\n if (ex == null)\n {\n _log.Info(message);\n }\n else\n {\n _log.Info(message, ex);\n }\n }\n }\n\n public void Warn(object message, Exception ex = null)\n {\n if (_log.IsWarnEnabled)\n {\n if (ex == null)\n {\n _log.Warn(message);\n }\n else\n {\n _log.Warn(message, ex);\n }\n }\n }\n\n public void Error(object message, Exception ex = null)\n {\n if (_log.IsErrorEnabled)\n {\n if (ex == null)\n {\n _log.Error(message);\n }\n else\n {\n _log.Error(message, ex);\n }\n }\n }\n\n public void Fatal(object message, Exception ex = null)\n {\n if (_log.IsFatalEnabled)\n {\n if (ex == null)\n {\n _log.Fatal(message);\n }\n else\n {\n _log.Fatal(message, ex);\n }\n }\n }\n }\n}\n AssemblyInfo.cs [assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = \"log4net.config\")]\n log4net.config Content Copy Always"
},
{
"answer_id": 38394820,
"author": "Leonardo",
"author_id": 497058,
"author_profile": "https://Stackoverflow.com/users/497058",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing log4net;\nusing log4net.Core;\nusing Prism.Logging;\n\npublic class Log4NetLoggerFacade : ILoggerFacade\n{\n private static readonly ILog Log4NetLog = LogManager.GetLogger(typeof (Log4NetLoggerFacade));\n\n public void Log(string message, Category category, Priority priority)\n {\n switch (category)\n {\n case Category.Debug:\n Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Debug, message, null);\n break;\n case Category.Exception:\n Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Error, message, null);\n break;\n case Category.Info:\n Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Info, message, null);\n break;\n case Category.Warn:\n Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Warn, message, null);\n break;\n default:\n throw new ArgumentOutOfRangeException(nameof(category), category, null);\n }\n }\n}\n callerStackBoundaryDeclaringType %C %M <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date [%thread] %-5level %C.%M - %message%newline\" />\n</layout>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
] |
166,452
|
<p>Is there any performance comparison of System.IO.File.ReadAllxxx / WriteAllxxx methods vs StreamReader / StremWriter classes available on web. What you think is the best way(from a performance perspective) to read/write text files in .net 3.0?</p>
<p>When I checked the <strong><a href="http://msdn.microsoft.com/en-us/library/system.io.file.aspx" rel="nofollow noreferrer">MSDN page of System.IO.File class</a></strong>, in the sample code MS is using StreamReader / StreamWriter for file operations. Is there any specific reason for avoiding File.ReadAllxxx / WriteAllxxx methods, even though they look much easier to understand?</p>
|
[
{
"answer_id": 166513,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "public static string ReadAllText(string path, Encoding encoding)\n{\n using (StreamReader reader = new StreamReader(path, encoding))\n {\n return reader.ReadToEnd();\n }\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22016/"
] |
166,472
|
<p>I have never quite understood how/why I would use Maven modules (reactor builds).</p>
<p>We have tens of libraries that we share (as dependencies) among our products, and between libraries as well. If we were to switch to making them Maven modules, how would we set it up, both in SVN and in our working copies?</p>
<p>Do Maven modules really need to be subfolders? Do they need to be subfolders in the SVN repo too?</p>
<p>Assuming you just need subfolders in the working copy, I suppose <code>svn:externals</code> would work to make, say, a "util" library be a module of multiple projects at the same time. But I've read many bad things about using <code>svn:externals</code> because there is nothing to stop you from modifying the code in the external, but its not tracked. </p>
<p>Any suggestions? Am I missing the boat on modules?</p>
|
[
{
"answer_id": 169048,
"author": "Hugo",
"author_id": 972,
"author_profile": "https://Stackoverflow.com/users/972",
"pm_score": 2,
"selected": true,
"text": "relativePath parent svn:externals"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24795/"
] |
166,474
|
<p>In a C++ file, I have a code like this:</p>
<pre><code>#if ACTIVATE
# pragma message( "Activated" )
#else
# pragma message( "Not Activated")
#endif
</code></pre>
<p>I want to set this ACTIVE define to 1 with the msbuild command line.</p>
<p>It tried this but it doesn't work:</p>
<pre><code>msbuild /p:DefineConstants="ACTIVATE=1"
</code></pre>
<p>Any idea?</p>
|
[
{
"answer_id": 166505,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 4,
"selected": false,
"text": "/p:DefineConstants=ACTIVATE\n"
},
{
"answer_id": 166524,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": -1,
"selected": false,
"text": "#ifdef ACTIVATE\n# pragma message( \"Activated\" )\n#else\n# pragma message( \"Not Activated\")\n#endif\n"
},
{
"answer_id": 166556,
"author": "Mac",
"author_id": 8696,
"author_profile": "https://Stackoverflow.com/users/8696",
"pm_score": 4,
"selected": false,
"text": "ACTIVATE=1 <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />"
},
{
"answer_id": 14206134,
"author": "bigh_29",
"author_id": 163679,
"author_profile": "https://Stackoverflow.com/users/163679",
"pm_score": 5,
"selected": false,
"text": "/D $(ExternalCompilerOptions) /D c:\\> set ExternalCompilerOptions=/DFOO /DBAR \n c:\\> msbuild\n <ClCompile>\n <AdditionalOptions>$(ExternalCompilerOptions) ... </AdditionalOptions>\n </ClCompile>\n /DACTIVATE=1"
},
{
"answer_id": 15746207,
"author": "4LegsDrivenCat",
"author_id": 2006632,
"author_profile": "https://Stackoverflow.com/users/2006632",
"pm_score": 4,
"selected": false,
"text": "true false MSBuild /p:MyDefine=MyValue\n <ClCompile> <ResourceCompile> <PreprocessorDefinitions>MY_DEFINE=$(MyDefine);$(PreprocessorDefinitions)</PreprocessorDefinitions>\n /p:MyDefine=MyValue MSBuild MY_DEFINE MY_DEFINE <ClCompile>\n ....\n <PreprocessorDefinitions>_DEBUG;_CONSOLE;OTHER_UNCONDITIONAL_MACROS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n <PreprocessorDefinitions Condition=\"'$(MyDefine)'!=''\">MY_DEFINE=$(MyDefine);%(PreprocessorDefinitions)</PreprocessorDefinitions>\n ....\n</ClCompile>\n PreprocessorDefinitions PreprocessorDefinitions MY_DEFINE MyDefine #define STRINGIZE2(x) #x\n#define STRINGIZE(x) STRINGIZE2(x)\n\n#ifndef MY_DEFINE\n#pragma message(\"MY_DEFINE is not defined.\")\n#else\n#pragma message(\"MY_DEFINE is defined to: [\" STRINGIZE(MY_DEFINE) \"]\")\n#endif\n > MSBuild SandBox.sln /p:Configuration=Debug /p:MyDefine=test /t:Rebuild\n...\nMY_DEFINE is defined to: [test]\n...\n\n> MSBuild SandBox.sln /p:Configuration=Debug /p:MyDefine= /t:Rebuild\n...\nMY_DEFINE is not defined.\n...\n\n> MSBuild SandBox.sln /p:Configuration=Debug /t:Rebuild\n...\nMY_DEFINE is not defined.\n...\n"
},
{
"answer_id": 49115730,
"author": "Lex Sergeev",
"author_id": 5658348,
"author_profile": "https://Stackoverflow.com/users/5658348",
"pm_score": 0,
"selected": false,
"text": "@echo off\n\n:: it is considered that Visual Studio tools are in the PATH\nif \"%1\"==\"USE_ACTIVATE_MACRO\" (\n :: if parameter USE_ACTIVATE_MACRO is passed to script\n :: the macro ACTIVATE will be defined for the project\n set CL=/DACTIVATE#1\n)\ncall msbuild /t:Rebuild /p:Configuration=Release\n set CL=/DACTIVATE=1"
},
{
"answer_id": 49630451,
"author": "Jay",
"author_id": 4213883,
"author_profile": "https://Stackoverflow.com/users/4213883",
"pm_score": 3,
"selected": false,
"text": "set CL=/DACTIVATE set CL=/DACTIVATE#1"
},
{
"answer_id": 72157847,
"author": "tschumann",
"author_id": 5158636,
"author_profile": "https://Stackoverflow.com/users/5158636",
"pm_score": -1,
"selected": false,
"text": "feature_flag.h #if FEATURE_FLAG #if !__has_include(\"feature_flag.h\") feature_flag.h"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
] |
166,482
|
<p>I have a website which uses the custom 404 error handling in PHP/Apache to display specific pages.<br>
e.g. <a href="http://metachat.org/recent" rel="nofollow noreferrer">http://metachat.org/recent</a> </p>
<p>I've a feeling this is a bad way of doing this, but it's code I inherited...</p>
<p>Although the page displays correctly on most browsers, I'm getting a situation where AVG Anti-Virus is hijacking the page and redirecting it to an offsite 404 page. </p>
<p>I've tried to force a header (Status: 200 OK) using the header command in PHP, but if I do a curl -I of the page, I get the following...</p>
<pre><code>HTTP/1.1 404 Not Found
Date: Fri, 03 Oct 2008 11:43:01 GMT
Server: Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 PHP/4.3.10-16 mod_ssl/2
.0.54 OpenSSL/0.9.7e
X-Powered-By: PHP/4.3.10-16
Status: 200 OK
Content-Type: text/html
</code></pre>
<p>I guess that first line is the line AVG traps for its forced redirect.
Without rewriting the software to use Mod_rewrite (which I don't really understand), how can I (in PHP) stop the "HTTP:/1/1 404 Not Found" line being sent in the headers when displaying this page?</p>
<p>Thanks. </p>
|
[
{
"answer_id": 166496,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "RewriteEngine On\nRewriteCond %{REQUEST_URI} !-f\nRewriteCond %{REQUEST_URI} !-d\nRewriteRule (.*) index.php?missing_content=$1\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726/"
] |
166,491
|
<p>I have a .bat and inside the .bat i would like to execute a special code if there's some modification inside the svn repository (for example, compile).</p>
|
[
{
"answer_id": 166514,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 1,
"selected": false,
"text": "svn st \"C:\\path\\to\\working\\directory\\\" >> C:\\path\\to\\working\\project.log\n"
},
{
"answer_id": 166662,
"author": "Tooony",
"author_id": 23864,
"author_profile": "https://Stackoverflow.com/users/23864",
"pm_score": 4,
"selected": true,
"text": "@echo off\nset svnOut=\nset svnDir=C:Your\\path\\to\\svn\\dir\\to\\check\nfor /F \"tokens=*\" %%I in ('svn status %svnDir%') do set svnOut=%%I\n\nif \"%svnOut%\"==\"\" (\n echo No changes\n) else (\n echo Changed files!\n)\n set svnOut=\n"
},
{
"answer_id": 167362,
"author": "acemtp",
"author_id": 6605,
"author_profile": "https://Stackoverflow.com/users/6605",
"pm_score": 2,
"selected": false,
"text": "set vHEAD = 0\nset vBASE = 0\n\nset svnDir=<path to local svn directory>\n\nfor /F \"tokens=1,2\" %%I in ('svn info -r HEAD %svnDir%') do if \"%%I\"==\"Revision:\" set vHEAD=%%J\nfor /F \"tokens=1,2\" %%I in ('svn info -r BASE %svnDir%') do if \"%%I\"==\"Revision:\" set vBASE=%%J\n\nif \"%vBASE%\"==\"%vHEAD%\" (\n echo No changes\n) else (\n echo Changed files!\n)\n"
},
{
"answer_id": 171086,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 2,
"selected": false,
"text": "svnversion SvnWCRev.exe svnversion SvnWCRev.exe"
},
{
"answer_id": 40875217,
"author": "Bryan Legend",
"author_id": 52771,
"author_profile": "https://Stackoverflow.com/users/52771",
"pm_score": 0,
"selected": false,
"text": "@echo off\nset svnOut=\n\nrem Check svn server status of current working directory repository and see if first or second token is an *\nfor /F \"tokens=1\" %%I in ('svn status --show-updates') do if \"%%I\"==\"*\" set svnOut=%%I\nrem echo \"%svnOut%\"\n\nif \"%svnOut%\"==\"\" (\n echo No changes\n) else (\n echo Changed files!\n)\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
] |
166,503
|
<p>How do I set the code page to UTF-8 in a C Windows program? </p>
<p>I have a third party library that uses fopen to open files. I can use wcstombs to convert my Unicode filenames to the current code page, however if the user has a filename with a character outside the code page then this breaks. </p>
<p>Ideally I would just call _setmbcp(65001) to set the code page to UTF-8, however the MSDN documentation for _setmbcp states that UTF-8 is not supported. </p>
<p>How can I get around this?</p>
|
[
{
"answer_id": 166926,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 4,
"selected": false,
"text": "std::wstring Utf8ToUtf16(const char* u8string)\n{\n int wcharcount = strlen(u8string);\n wchar_t *tempWstr = new wchar_t[wcharcount];\n MultiByteToWideChar(CP_UTF8, 0, u8string, -1, tempWstr, wcharcount);\n wstring w(tempWstr);\n delete [] tempWstr;\n return w;\n}\n"
},
{
"answer_id": 167157,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 6,
"selected": true,
"text": "CP_UTF7 CP_UTF8 char*"
},
{
"answer_id": 4618341,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": -1,
"selected": false,
"text": "_wfopen"
},
{
"answer_id": 50217129,
"author": "Mingye Wang",
"author_id": 3770260,
"author_profile": "https://Stackoverflow.com/users/3770260",
"pm_score": 3,
"selected": false,
"text": "conhost chcp 65001 cmd.exe"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2651243/"
] |
166,506
|
<p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
|
[
{
"answer_id": 166520,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 10,
"selected": true,
"text": "import socket\nsocket.gethostbyname(socket.gethostname())\n 127.0.0.1 /etc/hosts 127.0.0.1 socket.getfqdn()"
},
{
"answer_id": 166589,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 9,
"selected": false,
"text": "import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.connect((\"8.8.8.8\", 80))\nprint(s.getsockname()[0])\ns.close()\n"
},
{
"answer_id": 166591,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 7,
"selected": false,
"text": "pip install netifaces\n from netifaces import interfaces, ifaddresses, AF_INET\nfor ifaceName in interfaces():\n addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]\n print '%s: %s' % (ifaceName, ', '.join(addresses))\n"
},
{
"answer_id": 166992,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 5,
"selected": false,
"text": "def getIPAddresses():\n from ctypes import Structure, windll, sizeof\n from ctypes import POINTER, byref\n from ctypes import c_ulong, c_uint, c_ubyte, c_char\n MAX_ADAPTER_DESCRIPTION_LENGTH = 128\n MAX_ADAPTER_NAME_LENGTH = 256\n MAX_ADAPTER_ADDRESS_LENGTH = 8\n class IP_ADDR_STRING(Structure):\n pass\n LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)\n IP_ADDR_STRING._fields_ = [\n (\"next\", LP_IP_ADDR_STRING),\n (\"ipAddress\", c_char * 16),\n (\"ipMask\", c_char * 16),\n (\"context\", c_ulong)]\n class IP_ADAPTER_INFO (Structure):\n pass\n LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)\n IP_ADAPTER_INFO._fields_ = [\n (\"next\", LP_IP_ADAPTER_INFO),\n (\"comboIndex\", c_ulong),\n (\"adapterName\", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),\n (\"description\", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),\n (\"addressLength\", c_uint),\n (\"address\", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),\n (\"index\", c_ulong),\n (\"type\", c_uint),\n (\"dhcpEnabled\", c_uint),\n (\"currentIpAddress\", LP_IP_ADDR_STRING),\n (\"ipAddressList\", IP_ADDR_STRING),\n (\"gatewayList\", IP_ADDR_STRING),\n (\"dhcpServer\", IP_ADDR_STRING),\n (\"haveWins\", c_uint),\n (\"primaryWinsServer\", IP_ADDR_STRING),\n (\"secondaryWinsServer\", IP_ADDR_STRING),\n (\"leaseObtained\", c_ulong),\n (\"leaseExpires\", c_ulong)]\n GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo\n GetAdaptersInfo.restype = c_ulong\n GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]\n adapterList = (IP_ADAPTER_INFO * 10)()\n buflen = c_ulong(sizeof(adapterList))\n rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))\n if rc == 0:\n for a in adapterList:\n adNode = a.ipAddressList\n while True:\n ipAddr = adNode.ipAddress\n if ipAddr:\n yield ipAddr\n adNode = adNode.next\n if not adNode:\n break\n >>> for addr in getIPAddresses():\n>>> print addr\n192.168.0.100\n10.5.9.207\n windll"
},
{
"answer_id": 1267524,
"author": "Alexander",
"author_id": 131264,
"author_profile": "https://Stackoverflow.com/users/131264",
"pm_score": 7,
"selected": false,
"text": "myip alias myip=\"python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\\\"127.\\\")][:1], [[(s.connect((\\\"8.8.8.8\\\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'\"\n import socket\nprint([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])\n import socket\nprint((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")] or [[(s.connect((\"8.8.8.8\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + [\"no IP found\"])[0])\n socket.gethostbyname(socket.gethostname()) /etc/hosts socket.gethostbyname() /etc/hosts \"127.\" import socket\nprint([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1])\n 8.8.8.8 53 import socket\nprint([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])\n myip"
},
{
"answer_id": 1947766,
"author": "smerlin",
"author_id": 231717,
"author_profile": "https://Stackoverflow.com/users/231717",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/python\n# module for getting the lan ip address of the computer\n\nimport os\nimport socket\n\nif os.name != \"nt\":\n import fcntl\n import struct\n def get_interface_ip(ifname):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', bytes(ifname[:15], 'utf-8'))\n # Python 2.7: remove the second argument for the bytes call\n )[20:24])\n\ndef get_lan_ip():\n ip = socket.gethostbyname(socket.gethostname())\n if ip.startswith(\"127.\") and os.name != \"nt\":\n interfaces = [\"eth0\",\"eth1\",\"eth2\",\"wlan0\",\"wlan1\",\"wifi0\",\"ath0\",\"ath1\",\"ppp0\"]\n for ifname in interfaces:\n try:\n ip = get_interface_ip(ifname)\n break;\n except IOError:\n pass\n return ip\n"
},
{
"answer_id": 1980854,
"author": "gavaletz",
"author_id": 240954,
"author_profile": "https://Stackoverflow.com/users/240954",
"pm_score": 3,
"selected": false,
"text": "import socket\naddr = socket.gethostbyname(socket.gethostname())\n if addr == \"127.0.0.1\":\n import commands\n output = commands.getoutput(\"/sbin/ifconfig\")\n addr = parseaddress(output)\n"
},
{
"answer_id": 3177266,
"author": "shino",
"author_id": 244843,
"author_profile": "https://Stackoverflow.com/users/244843",
"pm_score": 5,
"selected": false,
"text": "import commands\ncommands.getoutput(\"/sbin/ifconfig\").split(\"\\n\")[1].split()[1][5:]\n"
},
{
"answer_id": 5111878,
"author": "Kulbir Saini",
"author_id": 625510,
"author_profile": "https://Stackoverflow.com/users/625510",
"pm_score": 2,
"selected": false,
"text": "import subprocess\nco = subprocess.Popen(['ifconfig'], stdout = subprocess.PIPE)\nifconfig = co.stdout.read()\nip_regex = re.compile('((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-4]|2[0-5][0-9]|[01]?[0-9][0-9]?))')\n[match[0] for match in ip_regex.findall(ifconfig, re.MULTILINE)]\n"
},
{
"answer_id": 6327620,
"author": "viker",
"author_id": 795536,
"author_profile": "https://Stackoverflow.com/users/795536",
"pm_score": 3,
"selected": false,
"text": "import commands\nips = commands.getoutput(\"/sbin/ifconfig | grep -i \\\"inet\\\" | grep -iv \\\"inet6\\\" | \" +\n \"awk {'print $2'} | sed -ne 's/addr\\:/ /p'\")\nprint ips\n"
},
{
"answer_id": 6453024,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 2,
"selected": false,
"text": "127.0.1.1 SIOCGIFCONF"
},
{
"answer_id": 6453053,
"author": "ninjagecko",
"author_id": 711085,
"author_profile": "https://Stackoverflow.com/users/711085",
"pm_score": 6,
"selected": false,
"text": "from urllib.request import urlopen\nimport re\ndef getPublicIp():\n data = str(urlopen('http://checkip.dyndns.com/').read())\n # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\\r\\n'\n\n return re.compile(r'Address: (\\d+\\.\\d+\\.\\d+\\.\\d+)').search(data).group(1)\n from urllib import urlopen\nimport re\ndef getPublicIp():\n data = str(urlopen('http://checkip.dyndns.com/').read())\n # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\\r\\n'\n\n return re.compile(r'Address: (\\d+\\.\\d+\\.\\d+\\.\\d+)').search(data).group(1)\n gateways and routes"
},
{
"answer_id": 9267833,
"author": "tMC",
"author_id": 592851,
"author_profile": "https://Stackoverflow.com/users/592851",
"pm_score": 5,
"selected": false,
"text": ">>> import socket, struct, fcntl\n>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n>>> sockfd = sock.fileno()\n>>> SIOCGIFADDR = 0x8915\n>>>\n>>> def get_ip(iface = 'eth0'):\n... ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\\x00'*14)\n... try:\n... res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)\n... except:\n... return None\n... ip = struct.unpack('16sH2x4s8x', res)[2]\n... return socket.inet_ntoa(ip)\n... \n>>> get_ip('eth0')\n'10.80.40.234'\n>>> \n"
},
{
"answer_id": 10192097,
"author": "snakebarber",
"author_id": 688589,
"author_profile": "https://Stackoverflow.com/users/688589",
"pm_score": 1,
"selected": false,
"text": "Import WMI\n\ndef getlocalip():\n local = wmi.WMI()\n for interface in local.Win32_NetworkAdapterConfiguration(IPEnabled=1):\n for ip_address in interface.IPAddress:\n if ip_address != '0.0.0.0':\n localip = ip_address\n return localip\n\n\n\n\n\n\n\n>>>getlocalip()\nu'xxx.xxx.xxx.xxx'\n>>>\n"
},
{
"answer_id": 10325724,
"author": "Etienne Perot",
"author_id": 109696,
"author_profile": "https://Stackoverflow.com/users/109696",
"pm_score": 2,
"selected": false,
"text": "_local_ip_cache = []\n_nonlocal_ip_cache = []\ndef ip_islocal(ip):\n if ip in _local_ip_cache:\n return True\n if ip in _nonlocal_ip_cache:\n return False\n s = socket.socket()\n try:\n try:\n s.bind((ip, 0))\n except socket.error, e:\n if e.args[0] == errno.EADDRNOTAVAIL:\n _nonlocal_ip_cache.append(ip)\n return False\n else:\n raise\n finally:\n s.close()\n _local_ip_cache.append(ip)\n return True\n"
},
{
"answer_id": 10350424,
"author": "fccoelho",
"author_id": 34747,
"author_profile": "https://Stackoverflow.com/users/34747",
"pm_score": 3,
"selected": false,
"text": "import socket, subprocess, re\ndef get_ipv4_address():\n \"\"\"\n Returns IP address(es) of current machine.\n :return:\n \"\"\"\n p = subprocess.Popen([\"ifconfig\"], stdout=subprocess.PIPE)\n ifc_resp = p.communicate()\n patt = re.compile(r'inet\\s*\\w*\\S*:\\s*(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})')\n resp = patt.findall(ifc_resp[0])\n print resp\n\nget_ipv4_address()\n"
},
{
"answer_id": 10377262,
"author": "Ben Last",
"author_id": 661571,
"author_profile": "https://Stackoverflow.com/users/661571",
"pm_score": 2,
"selected": false,
"text": "import commands,re,socket\n\n#A generator that returns stripped lines of output from \"ip address show\"\niplines=(line.strip() for line in commands.getoutput(\"ip address show\").split('\\n'))\n\n#Turn that into a list of IPv4 and IPv6 address/mask strings\naddresses1=reduce(lambda a,v:a+v,(re.findall(r\"inet ([\\d.]+/\\d+)\",line)+re.findall(r\"inet6 ([\\:\\da-f]+/\\d+)\",line) for line in iplines))\n#addresses1 now looks like ['127.0.0.1/8', '::1/128', '10.160.114.60/23', 'fe80::1031:3fff:fe00:6dce/64']\n\n#Get a list of IPv4 addresses as (IPstring,subnetsize) tuples\nipv4s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if '.' in addr)]\n#ipv4s now looks like [('127.0.0.1', 8), ('10.160.114.60', 23)]\n\n#Get IPv6 addresses\nipv6s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if ':' in addr)]\n"
},
{
"answer_id": 10946468,
"author": "Oink",
"author_id": 422242,
"author_profile": "https://Stackoverflow.com/users/422242",
"pm_score": 1,
"selected": false,
"text": "import socket\nsocket.gethostbyname(socket.getfqdn())\n"
},
{
"answer_id": 10992813,
"author": "WolfRage",
"author_id": 1450678,
"author_profile": "https://Stackoverflow.com/users/1450678",
"pm_score": 3,
"selected": false,
"text": "socket.gethostbyname(socket.gethostname()) import select\nimport socket\nimport threading\nfrom queue import Queue, Empty\n\ndef get_local_ip():\n def udp_listening_server():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.bind(('<broadcast>', 8888))\n s.setblocking(0)\n while True:\n result = select.select([s],[],[])\n msg, address = result[0][0].recvfrom(1024)\n msg = str(msg, 'UTF-8')\n if msg == 'What is my LAN IP address?':\n break\n queue.put(address)\n\n queue = Queue()\n thread = threading.Thread(target=udp_listening_server)\n thread.queue = queue\n thread.start()\n s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s2.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n waiting = True\n while waiting:\n s2.sendto(bytes('What is my LAN IP address?', 'UTF-8'), ('<broadcast>', 8888))\n try:\n address = queue.get(False)\n except Empty:\n pass\n else:\n waiting = False\n return address[0]\n\nif __name__ == '__main__':\n print(get_local_ip())\n"
},
{
"answer_id": 16412954,
"author": "Nakilon",
"author_id": 322020,
"author_profile": "https://Stackoverflow.com/users/322020",
"pm_score": 3,
"selected": false,
"text": "import socket\n[i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)]\n"
},
{
"answer_id": 18542718,
"author": "Artur Barseghyan",
"author_id": 2318839,
"author_profile": "https://Stackoverflow.com/users/2318839",
"pm_score": 2,
"selected": false,
"text": "from pif import get_public_ip\nget_public_ip()\n"
},
{
"answer_id": 20275076,
"author": "DarkXDroid",
"author_id": 2179483,
"author_profile": "https://Stackoverflow.com/users/2179483",
"pm_score": 2,
"selected": false,
"text": "#! /usr/bin/env python\n\nimport sys , pynotify\n\nif sys.version_info[1] != 7:\n raise RuntimeError('Python 2.7 And Above Only') \n\nfrom subprocess import check_output # Available on Python 2.7+ | N/A \n\nIP = check_output(['ip', 'route'])\nSplit_Result = IP.split()\n\n# print Split_Result[2] # Remove \"#\" to enable\n\npynotify.init(\"image\")\nnotify = pynotify.Notification(\"Ip\", \"Server Running At:\" + Split_Result[2] , \"/home/User/wireless.png\") \nnotify.show() \n easy_install py-notify\n pip install py-notify\n from pip import main\n\nmain(['install', 'py-notify'])\n"
},
{
"answer_id": 20312936,
"author": "Matt",
"author_id": 3054551,
"author_profile": "https://Stackoverflow.com/users/3054551",
"pm_score": -1,
"selected": false,
"text": "def getip():\n\n import socket\n hostname= socket.gethostname()\n ip=socket.gethostbyname(hostname)\n\n return(ip)\n"
},
{
"answer_id": 20710035,
"author": "Eli Collins",
"author_id": 681277,
"author_profile": "https://Stackoverflow.com/users/681277",
"pm_score": 3,
"selected": false,
"text": "get_local_addr() # imports\nimport errno\nimport socket\nimport logging\n\n# localhost prefixes\n_local_networks = (\"127.\", \"0:0:0:0:0:0:0:1\")\n\n# ignore these prefixes -- localhost, unspecified, and link-local\n_ignored_networks = _local_networks + (\"0.\", \"0:0:0:0:0:0:0:0\", \"169.254.\", \"fe80:\")\n\ndef detect_family(addr):\n if \".\" in addr:\n assert \":\" not in addr\n return socket.AF_INET\n elif \":\" in addr:\n return socket.AF_INET6\n else:\n raise ValueError(\"invalid ipv4/6 address: %r\" % addr)\n\ndef expand_addr(addr):\n \"\"\"convert address into canonical expanded form --\n no leading zeroes in groups, and for ipv6: lowercase hex, no collapsed groups.\n \"\"\"\n family = detect_family(addr)\n addr = socket.inet_ntop(family, socket.inet_pton(family, addr))\n if \"::\" in addr:\n count = 8-addr.count(\":\")\n addr = addr.replace(\"::\", (\":0\" * count) + \":\")\n if addr.startswith(\":\"):\n addr = \"0\" + addr\n return addr\n\ndef _get_local_addr(family, remote):\n try:\n s = socket.socket(family, socket.SOCK_DGRAM)\n try:\n s.connect((remote, 9))\n return s.getsockname()[0]\n finally:\n s.close()\n except socket.error:\n # log.info(\"trapped error connecting to %r via %r\", remote, family, exc_info=True)\n return None\n\ndef get_local_addr(remote=None, ipv6=True):\n \"\"\"get LAN address of host\n\n :param remote:\n return LAN address that host would use to access that specific remote address.\n by default, returns address it would use to access the public internet.\n\n :param ipv6:\n by default, attempts to find an ipv6 address first.\n if set to False, only checks ipv4.\n\n :returns:\n primary LAN address for host, or ``None`` if couldn't be determined.\n \"\"\"\n if remote:\n family = detect_family(remote)\n local = _get_local_addr(family, remote)\n if not local:\n return None\n if family == socket.AF_INET6:\n # expand zero groups so the startswith() test works.\n local = expand_addr(local)\n if local.startswith(_local_networks):\n # border case where remote addr belongs to host\n return local\n else:\n # NOTE: the two addresses used here are TESTNET addresses,\n # which should never exist in the real world.\n if ipv6:\n local = _get_local_addr(socket.AF_INET6, \"2001:db8::1234\")\n # expand zero groups so the startswith() test works.\n if local:\n local = expand_addr(local)\n else:\n local = None\n if not local:\n local = _get_local_addr(socket.AF_INET, \"192.0.2.123\")\n if not local:\n return None\n if local.startswith(_ignored_networks):\n return None\n return local\n"
},
{
"answer_id": 23822431,
"author": "dlm",
"author_id": 748925,
"author_profile": "https://Stackoverflow.com/users/748925",
"pm_score": 5,
"selected": false,
"text": "import socket\ndef getNetworkIp():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n s.connect(('<broadcast>', 0))\n return s.getsockname()[0]\n\nprint (getNetworkIp())\n"
},
{
"answer_id": 24171358,
"author": "user3712955",
"author_id": 3712955,
"author_profile": "https://Stackoverflow.com/users/3712955",
"pm_score": 2,
"selected": false,
"text": "import netifaces\n\nPROTO = netifaces.AF_INET # We want only IPv4, for now at least\n\n# Get list of network interfaces\n# Note: Can't filter for 'lo' here because Windows lacks it.\nifaces = netifaces.interfaces()\n\n# Get all addresses (of all kinds) for each interface\nif_addrs = [netifaces.ifaddresses(iface) for iface in ifaces]\n\n# Filter for the desired address type\nif_inet_addrs = [addr[PROTO] for addr in if_addrs if PROTO in addr]\n\niface_addrs = [s['addr'] for a in if_inet_addrs for s in a if 'addr' in s]\n# Can filter for '127.0.0.1' here.\n import netifaces\n\nPROTO = netifaces.AF_INET # We want only IPv4, for now at least\n\n# Get list of network interfaces\nifaces = netifaces.interfaces()\n\n# Get addresses for each interface\nif_addrs = [(netifaces.ifaddresses(iface), iface) for iface in ifaces]\n\n# Filter for only IPv4 addresses\nif_inet_addrs = [(tup[0][PROTO], tup[1]) for tup in if_addrs if PROTO in tup[0]]\n\niface_addrs = [(s['addr'], tup[1]) for tup in if_inet_addrs for s in tup[0] if 'addr' in s]\n from __future__ import print_function # For 2.x folks\nfrom pprint import pprint as pp\n\nprint('\\nifaces = ', end='')\npp(ifaces)\n\nprint('\\nif_addrs = ', end='')\npp(if_addrs)\n\nprint('\\nif_inet_addrs = ', end='')\npp(if_inet_addrs)\n\nprint('\\niface_addrs = ', end='')\npp(iface_addrs)\n"
},
{
"answer_id": 24564613,
"author": "www-0av-Com",
"author_id": 1863152,
"author_profile": "https://Stackoverflow.com/users/1863152",
"pm_score": 4,
"selected": false,
"text": "import commands\n\nRetMyIP = commands.getoutput(\"hostname -I\")\n import socket\n\nsocket.gethostbyname(socket.gethostname())\n"
},
{
"answer_id": 25850698,
"author": "Collin Anderson",
"author_id": 131881,
"author_profile": "https://Stackoverflow.com/users/131881",
"pm_score": 6,
"selected": false,
"text": "import socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.connect(('8.8.8.8', 1)) # connect() for UDP doesn't send packets\nlocal_ip_address = s.getsockname()[0]\n"
},
{
"answer_id": 27788672,
"author": "Graham Chap",
"author_id": 3842040,
"author_profile": "https://Stackoverflow.com/users/3842040",
"pm_score": 4,
"selected": false,
"text": "import socket\nimport fcntl\nimport struct\n\ndef get_ip_address(ifname):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', ifname[:15])\n )[20:24])\n >>> get_ip_address('eth0')\n'38.113.228.130'\n"
},
{
"answer_id": 28950776,
"author": "fatal_error",
"author_id": 1301627,
"author_profile": "https://Stackoverflow.com/users/1301627",
"pm_score": 9,
"selected": false,
"text": " import socket\n def get_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.settimeout(0)\n try:\n # doesn't even have to be reachable\n s.connect(('10.254.254.254', 1))\n IP = s.getsockname()[0]\n except Exception:\n IP = '127.0.0.1'\n finally:\n s.close()\n return IP\n print(get_ip())\n"
},
{
"answer_id": 29931604,
"author": "LRund",
"author_id": 4713795,
"author_profile": "https://Stackoverflow.com/users/4713795",
"pm_score": 1,
"selected": false,
"text": "def getWinIP(version = 'IPv4'):\n import subprocess\n if version not in ['IPv4', 'IPv6']:\n print 'error - protocol version must be \"IPv4\" or \"IPv6\"'\n return None\n ipconfig = subprocess.check_output('ipconfig')\n my_ip = []\n for line in ipconfig.split('\\n'):\n if 'Address' in line and version in line:\n my_ip.append(line.split(' : ')[1].strip())\n return my_ip\n\nprint getWinIP()\n"
},
{
"answer_id": 36446068,
"author": "Frederik Aalund",
"author_id": 554283,
"author_profile": "https://Stackoverflow.com/users/554283",
"pm_score": 2,
"selected": false,
"text": "async def get_local_ip():\n loop = asyncio.get_event_loop()\n transport, protocol = await loop.create_datagram_endpoint(\n asyncio.DatagramProtocol,\n remote_addr=('8.8.8.8', 80))\n result = transport.get_extra_info('sockname')[0]\n transport.close()\n return result\n"
},
{
"answer_id": 37618645,
"author": "RiccardoCh",
"author_id": 2000573,
"author_profile": "https://Stackoverflow.com/users/2000573",
"pm_score": 2,
"selected": false,
"text": "import socket, subprocess\n\ndef get_ip_and_hostname():\n hostname = socket.gethostname()\n\n shell_cmd = \"ifconfig | awk '/inet addr/{print substr($2,6)}'\"\n proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)\n (out, err) = proc.communicate()\n\n ip_list = out.split('\\n')\n ip = ip_list[0]\n\n for _ip in ip_list:\n try:\n if _ip != \"127.0.0.1\" and _ip.split(\".\")[3] != \"1\":\n ip = _ip\n except:\n pass\n return ip, hostname\n\nip_addr, hostname = get_ip_and_hostname()\n"
},
{
"answer_id": 38814772,
"author": "Apalala",
"author_id": 545637,
"author_profile": "https://Stackoverflow.com/users/545637",
"pm_score": -1,
"selected": false,
"text": "#!/usr/bin/env python3\nfrom urllib.request import urlopen\n\n\ndef public_ip():\n data = urlopen('https://api.ipify.org').read()\n return str(data, encoding='utf-8')\n\n\nprint(public_ip())\n"
},
{
"answer_id": 41002096,
"author": "Wyrmwood",
"author_id": 1368703,
"author_profile": "https://Stackoverflow.com/users/1368703",
"pm_score": -1,
"selected": false,
"text": "import socket\nprint next(i[4][0] for i in socket.getaddrinfo(\n socket.gethostname(), 80) if '127.' not in i[4][0] and '.' in i[4][0]);\"\n"
},
{
"answer_id": 44581122,
"author": "Villiam",
"author_id": 7727270,
"author_profile": "https://Stackoverflow.com/users/7727270",
"pm_score": 0,
"selected": false,
"text": "from netifaces import interfaces, ifaddresses, AF_INET\niplist = [ifaddresses(face)[AF_INET][0][\"addr\"] for face in interfaces() if AF_INET in ifaddresses(face)]\nprint(iplist)\n['10.8.0.2', '192.168.1.10', '127.0.0.1']\n"
},
{
"answer_id": 45222755,
"author": "NandaKrishnan",
"author_id": 8318939,
"author_profile": "https://Stackoverflow.com/users/8318939",
"pm_score": -1,
"selected": false,
"text": "import socket\nprint(socket.gethostbyname(socket.getfqdn()))\n"
},
{
"answer_id": 48004756,
"author": "Ishwarya",
"author_id": 9148547,
"author_profile": "https://Stackoverflow.com/users/9148547",
"pm_score": 2,
"selected": false,
"text": "import netifaces as ni \n\nni.ifaddresses('eth0')\nip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']\nprint(ip)\n"
},
{
"answer_id": 49269943,
"author": "hmofrad",
"author_id": 5412470,
"author_profile": "https://Stackoverflow.com/users/5412470",
"pm_score": 3,
"selected": false,
"text": "127.0.0.1 import subprocess\naddress = subprocess.check_output(['hostname', '-s', '-I'])\naddress = address.decode('utf-8') \naddress=address[:-1]\n address = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1]\n localhost /etc/hostname"
},
{
"answer_id": 55824993,
"author": "Compl Yue",
"author_id": 6394508,
"author_profile": "https://Stackoverflow.com/users/6394508",
"pm_score": 0,
"selected": false,
"text": "my-ip-to #!/usr/bin/env python\n\nimport sys, socket\n\nif len(sys.argv) > 1:\n for remote_host in sys.argv[1:]:\n # determine local host ip by outgoing test to another host\n # use port 9 (discard protocol - RFC 863) over UDP4\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n s.connect((remote_host, 9))\n my_ip = s.getsockname()[0]\n print(my_ip, flush=True)\nelse:\n import platform\n\n my_name = platform.node()\n my_ip = socket.gethostbyname(my_name)\n print(my_ip)\n\n $ my-ip-to z.cn g.cn localhost\n192.168.11.102\n192.168.11.102\n127.0.0.1\n$\n $ my-ip-to\n192.168.11.102\n"
},
{
"answer_id": 57196643,
"author": "Kasper Skytte Andersen",
"author_id": 8575867,
"author_profile": "https://Stackoverflow.com/users/8575867",
"pm_score": 4,
"selected": false,
"text": "check_output hostname -I from subprocess import check_output\ncheck_output(['hostname', '-I'])\n"
},
{
"answer_id": 60048761,
"author": "Josh",
"author_id": 10794945,
"author_profile": "https://Stackoverflow.com/users/10794945",
"pm_score": -1,
"selected": false,
"text": "from pyroute2 import IPRoute\nip = IPRoute()\n\ndef get_ipv4_address(intf):\n return dict(ip.get_addr(label=intf)[0]['attrs'])['IFA_LOCAL']\n\nprint(get_ipv4_address('eth0'))\n"
},
{
"answer_id": 65130655,
"author": "nikhil swami",
"author_id": 12179956,
"author_profile": "https://Stackoverflow.com/users/12179956",
"pm_score": 0,
"selected": false,
"text": "shell command: ipconfig def wlan_ip():\n import subprocess\n result=subprocess.run('ipconfig',stdout=subprocess.PIPE,text=True).stdout.lower()\n scan=0\n for i in result.split('\\n'):\n if 'wireless' in i: #use \"wireless\" or wireless adapters and \"ethernet\" for wired connections\n scan=1\n if scan:\n if 'ipv4' in i:\n return i.split(':')[1].strip()\nprint(wlan_ip())\n Wireless LAN adapter Wi-Fi:\n\n Connection-specific DNS Suffix . :\n Link-local IPv6 Address . . . . . : fe80::f485:4a6a:e7d5:1b1c%4\n IPv4 Address. . . . . . . . . . . : 192.168.0.131\n Subnet Mask . . . . . . . . . . . : 255.255.255.0\n Default Gateway . . . . . . . . . : 192.168.0.1\n"
},
{
"answer_id": 68378891,
"author": "Laurens",
"author_id": 3640844,
"author_profile": "https://Stackoverflow.com/users/3640844",
"pm_score": -1,
"selected": false,
"text": "const dgram = require('dgram');\n\nasync function get_local_ip() {\n const s = new dgram.createSocket('udp4');\n return new Promise((resolve, reject) => {\n try {\n s.connect(1, '8.8.8.8', function () {\n const ip = s.address();\n s.close();\n resolve(ip.address)\n });\n } catch (e) {\n console.error(e);\n s.close();\n reject(e);\n }\n })\n}\n"
},
{
"answer_id": 69369114,
"author": "TCB919",
"author_id": 8345316,
"author_profile": "https://Stackoverflow.com/users/8345316",
"pm_score": 0,
"selected": false,
"text": "iproute2 subprocess.run() -j json.loads() import subprocess\nimport json\n\nip = json.loads(subprocess.run('ip -j a'.split(),capture_output=True).stdout.decode())[1]['addr_info'][0]['local'] \n\nprint(ip)\n ip -j route get 8.8.8.8 import subprocess \nimport json \n\nip = json.loads(subprocess.run('ip -j route get 8.8.8.8'.split(),capture_output=True).stdout.decode())[0]['prefsrc']\n\nprint(ip)\n ip -j a import subprocess\nimport json\n\nlist_of_dicts = json.loads(subprocess.run('ip -j a'.split(),capture_output=True).stdout.decode())\n\nfor interface in list_of_dicts:\n try:print(f\"Interface: {interface['ifname']:10} IP: {interface['addr_info'][0]['local']}\")\n except:pass\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
166,508
|
<p>Is there any way so that i can echo password when asked for in unix shell without use of external binaries ? Something like simple function triggered when password prompt is displayed</p>
|
[
{
"answer_id": 166520,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 10,
"selected": true,
"text": "import socket\nsocket.gethostbyname(socket.gethostname())\n 127.0.0.1 /etc/hosts 127.0.0.1 socket.getfqdn()"
},
{
"answer_id": 166589,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 9,
"selected": false,
"text": "import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.connect((\"8.8.8.8\", 80))\nprint(s.getsockname()[0])\ns.close()\n"
},
{
"answer_id": 166591,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 7,
"selected": false,
"text": "pip install netifaces\n from netifaces import interfaces, ifaddresses, AF_INET\nfor ifaceName in interfaces():\n addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]\n print '%s: %s' % (ifaceName, ', '.join(addresses))\n"
},
{
"answer_id": 166992,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 5,
"selected": false,
"text": "def getIPAddresses():\n from ctypes import Structure, windll, sizeof\n from ctypes import POINTER, byref\n from ctypes import c_ulong, c_uint, c_ubyte, c_char\n MAX_ADAPTER_DESCRIPTION_LENGTH = 128\n MAX_ADAPTER_NAME_LENGTH = 256\n MAX_ADAPTER_ADDRESS_LENGTH = 8\n class IP_ADDR_STRING(Structure):\n pass\n LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)\n IP_ADDR_STRING._fields_ = [\n (\"next\", LP_IP_ADDR_STRING),\n (\"ipAddress\", c_char * 16),\n (\"ipMask\", c_char * 16),\n (\"context\", c_ulong)]\n class IP_ADAPTER_INFO (Structure):\n pass\n LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)\n IP_ADAPTER_INFO._fields_ = [\n (\"next\", LP_IP_ADAPTER_INFO),\n (\"comboIndex\", c_ulong),\n (\"adapterName\", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),\n (\"description\", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),\n (\"addressLength\", c_uint),\n (\"address\", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),\n (\"index\", c_ulong),\n (\"type\", c_uint),\n (\"dhcpEnabled\", c_uint),\n (\"currentIpAddress\", LP_IP_ADDR_STRING),\n (\"ipAddressList\", IP_ADDR_STRING),\n (\"gatewayList\", IP_ADDR_STRING),\n (\"dhcpServer\", IP_ADDR_STRING),\n (\"haveWins\", c_uint),\n (\"primaryWinsServer\", IP_ADDR_STRING),\n (\"secondaryWinsServer\", IP_ADDR_STRING),\n (\"leaseObtained\", c_ulong),\n (\"leaseExpires\", c_ulong)]\n GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo\n GetAdaptersInfo.restype = c_ulong\n GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]\n adapterList = (IP_ADAPTER_INFO * 10)()\n buflen = c_ulong(sizeof(adapterList))\n rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))\n if rc == 0:\n for a in adapterList:\n adNode = a.ipAddressList\n while True:\n ipAddr = adNode.ipAddress\n if ipAddr:\n yield ipAddr\n adNode = adNode.next\n if not adNode:\n break\n >>> for addr in getIPAddresses():\n>>> print addr\n192.168.0.100\n10.5.9.207\n windll"
},
{
"answer_id": 1267524,
"author": "Alexander",
"author_id": 131264,
"author_profile": "https://Stackoverflow.com/users/131264",
"pm_score": 7,
"selected": false,
"text": "myip alias myip=\"python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\\\"127.\\\")][:1], [[(s.connect((\\\"8.8.8.8\\\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'\"\n import socket\nprint([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])\n import socket\nprint((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")] or [[(s.connect((\"8.8.8.8\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + [\"no IP found\"])[0])\n socket.gethostbyname(socket.gethostname()) /etc/hosts socket.gethostbyname() /etc/hosts \"127.\" import socket\nprint([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1])\n 8.8.8.8 53 import socket\nprint([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])\n myip"
},
{
"answer_id": 1947766,
"author": "smerlin",
"author_id": 231717,
"author_profile": "https://Stackoverflow.com/users/231717",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/python\n# module for getting the lan ip address of the computer\n\nimport os\nimport socket\n\nif os.name != \"nt\":\n import fcntl\n import struct\n def get_interface_ip(ifname):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', bytes(ifname[:15], 'utf-8'))\n # Python 2.7: remove the second argument for the bytes call\n )[20:24])\n\ndef get_lan_ip():\n ip = socket.gethostbyname(socket.gethostname())\n if ip.startswith(\"127.\") and os.name != \"nt\":\n interfaces = [\"eth0\",\"eth1\",\"eth2\",\"wlan0\",\"wlan1\",\"wifi0\",\"ath0\",\"ath1\",\"ppp0\"]\n for ifname in interfaces:\n try:\n ip = get_interface_ip(ifname)\n break;\n except IOError:\n pass\n return ip\n"
},
{
"answer_id": 1980854,
"author": "gavaletz",
"author_id": 240954,
"author_profile": "https://Stackoverflow.com/users/240954",
"pm_score": 3,
"selected": false,
"text": "import socket\naddr = socket.gethostbyname(socket.gethostname())\n if addr == \"127.0.0.1\":\n import commands\n output = commands.getoutput(\"/sbin/ifconfig\")\n addr = parseaddress(output)\n"
},
{
"answer_id": 3177266,
"author": "shino",
"author_id": 244843,
"author_profile": "https://Stackoverflow.com/users/244843",
"pm_score": 5,
"selected": false,
"text": "import commands\ncommands.getoutput(\"/sbin/ifconfig\").split(\"\\n\")[1].split()[1][5:]\n"
},
{
"answer_id": 5111878,
"author": "Kulbir Saini",
"author_id": 625510,
"author_profile": "https://Stackoverflow.com/users/625510",
"pm_score": 2,
"selected": false,
"text": "import subprocess\nco = subprocess.Popen(['ifconfig'], stdout = subprocess.PIPE)\nifconfig = co.stdout.read()\nip_regex = re.compile('((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-4]|2[0-5][0-9]|[01]?[0-9][0-9]?))')\n[match[0] for match in ip_regex.findall(ifconfig, re.MULTILINE)]\n"
},
{
"answer_id": 6327620,
"author": "viker",
"author_id": 795536,
"author_profile": "https://Stackoverflow.com/users/795536",
"pm_score": 3,
"selected": false,
"text": "import commands\nips = commands.getoutput(\"/sbin/ifconfig | grep -i \\\"inet\\\" | grep -iv \\\"inet6\\\" | \" +\n \"awk {'print $2'} | sed -ne 's/addr\\:/ /p'\")\nprint ips\n"
},
{
"answer_id": 6453024,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 2,
"selected": false,
"text": "127.0.1.1 SIOCGIFCONF"
},
{
"answer_id": 6453053,
"author": "ninjagecko",
"author_id": 711085,
"author_profile": "https://Stackoverflow.com/users/711085",
"pm_score": 6,
"selected": false,
"text": "from urllib.request import urlopen\nimport re\ndef getPublicIp():\n data = str(urlopen('http://checkip.dyndns.com/').read())\n # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\\r\\n'\n\n return re.compile(r'Address: (\\d+\\.\\d+\\.\\d+\\.\\d+)').search(data).group(1)\n from urllib import urlopen\nimport re\ndef getPublicIp():\n data = str(urlopen('http://checkip.dyndns.com/').read())\n # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\\r\\n'\n\n return re.compile(r'Address: (\\d+\\.\\d+\\.\\d+\\.\\d+)').search(data).group(1)\n gateways and routes"
},
{
"answer_id": 9267833,
"author": "tMC",
"author_id": 592851,
"author_profile": "https://Stackoverflow.com/users/592851",
"pm_score": 5,
"selected": false,
"text": ">>> import socket, struct, fcntl\n>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n>>> sockfd = sock.fileno()\n>>> SIOCGIFADDR = 0x8915\n>>>\n>>> def get_ip(iface = 'eth0'):\n... ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\\x00'*14)\n... try:\n... res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)\n... except:\n... return None\n... ip = struct.unpack('16sH2x4s8x', res)[2]\n... return socket.inet_ntoa(ip)\n... \n>>> get_ip('eth0')\n'10.80.40.234'\n>>> \n"
},
{
"answer_id": 10192097,
"author": "snakebarber",
"author_id": 688589,
"author_profile": "https://Stackoverflow.com/users/688589",
"pm_score": 1,
"selected": false,
"text": "Import WMI\n\ndef getlocalip():\n local = wmi.WMI()\n for interface in local.Win32_NetworkAdapterConfiguration(IPEnabled=1):\n for ip_address in interface.IPAddress:\n if ip_address != '0.0.0.0':\n localip = ip_address\n return localip\n\n\n\n\n\n\n\n>>>getlocalip()\nu'xxx.xxx.xxx.xxx'\n>>>\n"
},
{
"answer_id": 10325724,
"author": "Etienne Perot",
"author_id": 109696,
"author_profile": "https://Stackoverflow.com/users/109696",
"pm_score": 2,
"selected": false,
"text": "_local_ip_cache = []\n_nonlocal_ip_cache = []\ndef ip_islocal(ip):\n if ip in _local_ip_cache:\n return True\n if ip in _nonlocal_ip_cache:\n return False\n s = socket.socket()\n try:\n try:\n s.bind((ip, 0))\n except socket.error, e:\n if e.args[0] == errno.EADDRNOTAVAIL:\n _nonlocal_ip_cache.append(ip)\n return False\n else:\n raise\n finally:\n s.close()\n _local_ip_cache.append(ip)\n return True\n"
},
{
"answer_id": 10350424,
"author": "fccoelho",
"author_id": 34747,
"author_profile": "https://Stackoverflow.com/users/34747",
"pm_score": 3,
"selected": false,
"text": "import socket, subprocess, re\ndef get_ipv4_address():\n \"\"\"\n Returns IP address(es) of current machine.\n :return:\n \"\"\"\n p = subprocess.Popen([\"ifconfig\"], stdout=subprocess.PIPE)\n ifc_resp = p.communicate()\n patt = re.compile(r'inet\\s*\\w*\\S*:\\s*(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})')\n resp = patt.findall(ifc_resp[0])\n print resp\n\nget_ipv4_address()\n"
},
{
"answer_id": 10377262,
"author": "Ben Last",
"author_id": 661571,
"author_profile": "https://Stackoverflow.com/users/661571",
"pm_score": 2,
"selected": false,
"text": "import commands,re,socket\n\n#A generator that returns stripped lines of output from \"ip address show\"\niplines=(line.strip() for line in commands.getoutput(\"ip address show\").split('\\n'))\n\n#Turn that into a list of IPv4 and IPv6 address/mask strings\naddresses1=reduce(lambda a,v:a+v,(re.findall(r\"inet ([\\d.]+/\\d+)\",line)+re.findall(r\"inet6 ([\\:\\da-f]+/\\d+)\",line) for line in iplines))\n#addresses1 now looks like ['127.0.0.1/8', '::1/128', '10.160.114.60/23', 'fe80::1031:3fff:fe00:6dce/64']\n\n#Get a list of IPv4 addresses as (IPstring,subnetsize) tuples\nipv4s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if '.' in addr)]\n#ipv4s now looks like [('127.0.0.1', 8), ('10.160.114.60', 23)]\n\n#Get IPv6 addresses\nipv6s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if ':' in addr)]\n"
},
{
"answer_id": 10946468,
"author": "Oink",
"author_id": 422242,
"author_profile": "https://Stackoverflow.com/users/422242",
"pm_score": 1,
"selected": false,
"text": "import socket\nsocket.gethostbyname(socket.getfqdn())\n"
},
{
"answer_id": 10992813,
"author": "WolfRage",
"author_id": 1450678,
"author_profile": "https://Stackoverflow.com/users/1450678",
"pm_score": 3,
"selected": false,
"text": "socket.gethostbyname(socket.gethostname()) import select\nimport socket\nimport threading\nfrom queue import Queue, Empty\n\ndef get_local_ip():\n def udp_listening_server():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.bind(('<broadcast>', 8888))\n s.setblocking(0)\n while True:\n result = select.select([s],[],[])\n msg, address = result[0][0].recvfrom(1024)\n msg = str(msg, 'UTF-8')\n if msg == 'What is my LAN IP address?':\n break\n queue.put(address)\n\n queue = Queue()\n thread = threading.Thread(target=udp_listening_server)\n thread.queue = queue\n thread.start()\n s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s2.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n waiting = True\n while waiting:\n s2.sendto(bytes('What is my LAN IP address?', 'UTF-8'), ('<broadcast>', 8888))\n try:\n address = queue.get(False)\n except Empty:\n pass\n else:\n waiting = False\n return address[0]\n\nif __name__ == '__main__':\n print(get_local_ip())\n"
},
{
"answer_id": 16412954,
"author": "Nakilon",
"author_id": 322020,
"author_profile": "https://Stackoverflow.com/users/322020",
"pm_score": 3,
"selected": false,
"text": "import socket\n[i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)]\n"
},
{
"answer_id": 18542718,
"author": "Artur Barseghyan",
"author_id": 2318839,
"author_profile": "https://Stackoverflow.com/users/2318839",
"pm_score": 2,
"selected": false,
"text": "from pif import get_public_ip\nget_public_ip()\n"
},
{
"answer_id": 20275076,
"author": "DarkXDroid",
"author_id": 2179483,
"author_profile": "https://Stackoverflow.com/users/2179483",
"pm_score": 2,
"selected": false,
"text": "#! /usr/bin/env python\n\nimport sys , pynotify\n\nif sys.version_info[1] != 7:\n raise RuntimeError('Python 2.7 And Above Only') \n\nfrom subprocess import check_output # Available on Python 2.7+ | N/A \n\nIP = check_output(['ip', 'route'])\nSplit_Result = IP.split()\n\n# print Split_Result[2] # Remove \"#\" to enable\n\npynotify.init(\"image\")\nnotify = pynotify.Notification(\"Ip\", \"Server Running At:\" + Split_Result[2] , \"/home/User/wireless.png\") \nnotify.show() \n easy_install py-notify\n pip install py-notify\n from pip import main\n\nmain(['install', 'py-notify'])\n"
},
{
"answer_id": 20312936,
"author": "Matt",
"author_id": 3054551,
"author_profile": "https://Stackoverflow.com/users/3054551",
"pm_score": -1,
"selected": false,
"text": "def getip():\n\n import socket\n hostname= socket.gethostname()\n ip=socket.gethostbyname(hostname)\n\n return(ip)\n"
},
{
"answer_id": 20710035,
"author": "Eli Collins",
"author_id": 681277,
"author_profile": "https://Stackoverflow.com/users/681277",
"pm_score": 3,
"selected": false,
"text": "get_local_addr() # imports\nimport errno\nimport socket\nimport logging\n\n# localhost prefixes\n_local_networks = (\"127.\", \"0:0:0:0:0:0:0:1\")\n\n# ignore these prefixes -- localhost, unspecified, and link-local\n_ignored_networks = _local_networks + (\"0.\", \"0:0:0:0:0:0:0:0\", \"169.254.\", \"fe80:\")\n\ndef detect_family(addr):\n if \".\" in addr:\n assert \":\" not in addr\n return socket.AF_INET\n elif \":\" in addr:\n return socket.AF_INET6\n else:\n raise ValueError(\"invalid ipv4/6 address: %r\" % addr)\n\ndef expand_addr(addr):\n \"\"\"convert address into canonical expanded form --\n no leading zeroes in groups, and for ipv6: lowercase hex, no collapsed groups.\n \"\"\"\n family = detect_family(addr)\n addr = socket.inet_ntop(family, socket.inet_pton(family, addr))\n if \"::\" in addr:\n count = 8-addr.count(\":\")\n addr = addr.replace(\"::\", (\":0\" * count) + \":\")\n if addr.startswith(\":\"):\n addr = \"0\" + addr\n return addr\n\ndef _get_local_addr(family, remote):\n try:\n s = socket.socket(family, socket.SOCK_DGRAM)\n try:\n s.connect((remote, 9))\n return s.getsockname()[0]\n finally:\n s.close()\n except socket.error:\n # log.info(\"trapped error connecting to %r via %r\", remote, family, exc_info=True)\n return None\n\ndef get_local_addr(remote=None, ipv6=True):\n \"\"\"get LAN address of host\n\n :param remote:\n return LAN address that host would use to access that specific remote address.\n by default, returns address it would use to access the public internet.\n\n :param ipv6:\n by default, attempts to find an ipv6 address first.\n if set to False, only checks ipv4.\n\n :returns:\n primary LAN address for host, or ``None`` if couldn't be determined.\n \"\"\"\n if remote:\n family = detect_family(remote)\n local = _get_local_addr(family, remote)\n if not local:\n return None\n if family == socket.AF_INET6:\n # expand zero groups so the startswith() test works.\n local = expand_addr(local)\n if local.startswith(_local_networks):\n # border case where remote addr belongs to host\n return local\n else:\n # NOTE: the two addresses used here are TESTNET addresses,\n # which should never exist in the real world.\n if ipv6:\n local = _get_local_addr(socket.AF_INET6, \"2001:db8::1234\")\n # expand zero groups so the startswith() test works.\n if local:\n local = expand_addr(local)\n else:\n local = None\n if not local:\n local = _get_local_addr(socket.AF_INET, \"192.0.2.123\")\n if not local:\n return None\n if local.startswith(_ignored_networks):\n return None\n return local\n"
},
{
"answer_id": 23822431,
"author": "dlm",
"author_id": 748925,
"author_profile": "https://Stackoverflow.com/users/748925",
"pm_score": 5,
"selected": false,
"text": "import socket\ndef getNetworkIp():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n s.connect(('<broadcast>', 0))\n return s.getsockname()[0]\n\nprint (getNetworkIp())\n"
},
{
"answer_id": 24171358,
"author": "user3712955",
"author_id": 3712955,
"author_profile": "https://Stackoverflow.com/users/3712955",
"pm_score": 2,
"selected": false,
"text": "import netifaces\n\nPROTO = netifaces.AF_INET # We want only IPv4, for now at least\n\n# Get list of network interfaces\n# Note: Can't filter for 'lo' here because Windows lacks it.\nifaces = netifaces.interfaces()\n\n# Get all addresses (of all kinds) for each interface\nif_addrs = [netifaces.ifaddresses(iface) for iface in ifaces]\n\n# Filter for the desired address type\nif_inet_addrs = [addr[PROTO] for addr in if_addrs if PROTO in addr]\n\niface_addrs = [s['addr'] for a in if_inet_addrs for s in a if 'addr' in s]\n# Can filter for '127.0.0.1' here.\n import netifaces\n\nPROTO = netifaces.AF_INET # We want only IPv4, for now at least\n\n# Get list of network interfaces\nifaces = netifaces.interfaces()\n\n# Get addresses for each interface\nif_addrs = [(netifaces.ifaddresses(iface), iface) for iface in ifaces]\n\n# Filter for only IPv4 addresses\nif_inet_addrs = [(tup[0][PROTO], tup[1]) for tup in if_addrs if PROTO in tup[0]]\n\niface_addrs = [(s['addr'], tup[1]) for tup in if_inet_addrs for s in tup[0] if 'addr' in s]\n from __future__ import print_function # For 2.x folks\nfrom pprint import pprint as pp\n\nprint('\\nifaces = ', end='')\npp(ifaces)\n\nprint('\\nif_addrs = ', end='')\npp(if_addrs)\n\nprint('\\nif_inet_addrs = ', end='')\npp(if_inet_addrs)\n\nprint('\\niface_addrs = ', end='')\npp(iface_addrs)\n"
},
{
"answer_id": 24564613,
"author": "www-0av-Com",
"author_id": 1863152,
"author_profile": "https://Stackoverflow.com/users/1863152",
"pm_score": 4,
"selected": false,
"text": "import commands\n\nRetMyIP = commands.getoutput(\"hostname -I\")\n import socket\n\nsocket.gethostbyname(socket.gethostname())\n"
},
{
"answer_id": 25850698,
"author": "Collin Anderson",
"author_id": 131881,
"author_profile": "https://Stackoverflow.com/users/131881",
"pm_score": 6,
"selected": false,
"text": "import socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.connect(('8.8.8.8', 1)) # connect() for UDP doesn't send packets\nlocal_ip_address = s.getsockname()[0]\n"
},
{
"answer_id": 27788672,
"author": "Graham Chap",
"author_id": 3842040,
"author_profile": "https://Stackoverflow.com/users/3842040",
"pm_score": 4,
"selected": false,
"text": "import socket\nimport fcntl\nimport struct\n\ndef get_ip_address(ifname):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', ifname[:15])\n )[20:24])\n >>> get_ip_address('eth0')\n'38.113.228.130'\n"
},
{
"answer_id": 28950776,
"author": "fatal_error",
"author_id": 1301627,
"author_profile": "https://Stackoverflow.com/users/1301627",
"pm_score": 9,
"selected": false,
"text": " import socket\n def get_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.settimeout(0)\n try:\n # doesn't even have to be reachable\n s.connect(('10.254.254.254', 1))\n IP = s.getsockname()[0]\n except Exception:\n IP = '127.0.0.1'\n finally:\n s.close()\n return IP\n print(get_ip())\n"
},
{
"answer_id": 29931604,
"author": "LRund",
"author_id": 4713795,
"author_profile": "https://Stackoverflow.com/users/4713795",
"pm_score": 1,
"selected": false,
"text": "def getWinIP(version = 'IPv4'):\n import subprocess\n if version not in ['IPv4', 'IPv6']:\n print 'error - protocol version must be \"IPv4\" or \"IPv6\"'\n return None\n ipconfig = subprocess.check_output('ipconfig')\n my_ip = []\n for line in ipconfig.split('\\n'):\n if 'Address' in line and version in line:\n my_ip.append(line.split(' : ')[1].strip())\n return my_ip\n\nprint getWinIP()\n"
},
{
"answer_id": 36446068,
"author": "Frederik Aalund",
"author_id": 554283,
"author_profile": "https://Stackoverflow.com/users/554283",
"pm_score": 2,
"selected": false,
"text": "async def get_local_ip():\n loop = asyncio.get_event_loop()\n transport, protocol = await loop.create_datagram_endpoint(\n asyncio.DatagramProtocol,\n remote_addr=('8.8.8.8', 80))\n result = transport.get_extra_info('sockname')[0]\n transport.close()\n return result\n"
},
{
"answer_id": 37618645,
"author": "RiccardoCh",
"author_id": 2000573,
"author_profile": "https://Stackoverflow.com/users/2000573",
"pm_score": 2,
"selected": false,
"text": "import socket, subprocess\n\ndef get_ip_and_hostname():\n hostname = socket.gethostname()\n\n shell_cmd = \"ifconfig | awk '/inet addr/{print substr($2,6)}'\"\n proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)\n (out, err) = proc.communicate()\n\n ip_list = out.split('\\n')\n ip = ip_list[0]\n\n for _ip in ip_list:\n try:\n if _ip != \"127.0.0.1\" and _ip.split(\".\")[3] != \"1\":\n ip = _ip\n except:\n pass\n return ip, hostname\n\nip_addr, hostname = get_ip_and_hostname()\n"
},
{
"answer_id": 38814772,
"author": "Apalala",
"author_id": 545637,
"author_profile": "https://Stackoverflow.com/users/545637",
"pm_score": -1,
"selected": false,
"text": "#!/usr/bin/env python3\nfrom urllib.request import urlopen\n\n\ndef public_ip():\n data = urlopen('https://api.ipify.org').read()\n return str(data, encoding='utf-8')\n\n\nprint(public_ip())\n"
},
{
"answer_id": 41002096,
"author": "Wyrmwood",
"author_id": 1368703,
"author_profile": "https://Stackoverflow.com/users/1368703",
"pm_score": -1,
"selected": false,
"text": "import socket\nprint next(i[4][0] for i in socket.getaddrinfo(\n socket.gethostname(), 80) if '127.' not in i[4][0] and '.' in i[4][0]);\"\n"
},
{
"answer_id": 44581122,
"author": "Villiam",
"author_id": 7727270,
"author_profile": "https://Stackoverflow.com/users/7727270",
"pm_score": 0,
"selected": false,
"text": "from netifaces import interfaces, ifaddresses, AF_INET\niplist = [ifaddresses(face)[AF_INET][0][\"addr\"] for face in interfaces() if AF_INET in ifaddresses(face)]\nprint(iplist)\n['10.8.0.2', '192.168.1.10', '127.0.0.1']\n"
},
{
"answer_id": 45222755,
"author": "NandaKrishnan",
"author_id": 8318939,
"author_profile": "https://Stackoverflow.com/users/8318939",
"pm_score": -1,
"selected": false,
"text": "import socket\nprint(socket.gethostbyname(socket.getfqdn()))\n"
},
{
"answer_id": 48004756,
"author": "Ishwarya",
"author_id": 9148547,
"author_profile": "https://Stackoverflow.com/users/9148547",
"pm_score": 2,
"selected": false,
"text": "import netifaces as ni \n\nni.ifaddresses('eth0')\nip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']\nprint(ip)\n"
},
{
"answer_id": 49269943,
"author": "hmofrad",
"author_id": 5412470,
"author_profile": "https://Stackoverflow.com/users/5412470",
"pm_score": 3,
"selected": false,
"text": "127.0.0.1 import subprocess\naddress = subprocess.check_output(['hostname', '-s', '-I'])\naddress = address.decode('utf-8') \naddress=address[:-1]\n address = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1]\n localhost /etc/hostname"
},
{
"answer_id": 55824993,
"author": "Compl Yue",
"author_id": 6394508,
"author_profile": "https://Stackoverflow.com/users/6394508",
"pm_score": 0,
"selected": false,
"text": "my-ip-to #!/usr/bin/env python\n\nimport sys, socket\n\nif len(sys.argv) > 1:\n for remote_host in sys.argv[1:]:\n # determine local host ip by outgoing test to another host\n # use port 9 (discard protocol - RFC 863) over UDP4\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n s.connect((remote_host, 9))\n my_ip = s.getsockname()[0]\n print(my_ip, flush=True)\nelse:\n import platform\n\n my_name = platform.node()\n my_ip = socket.gethostbyname(my_name)\n print(my_ip)\n\n $ my-ip-to z.cn g.cn localhost\n192.168.11.102\n192.168.11.102\n127.0.0.1\n$\n $ my-ip-to\n192.168.11.102\n"
},
{
"answer_id": 57196643,
"author": "Kasper Skytte Andersen",
"author_id": 8575867,
"author_profile": "https://Stackoverflow.com/users/8575867",
"pm_score": 4,
"selected": false,
"text": "check_output hostname -I from subprocess import check_output\ncheck_output(['hostname', '-I'])\n"
},
{
"answer_id": 60048761,
"author": "Josh",
"author_id": 10794945,
"author_profile": "https://Stackoverflow.com/users/10794945",
"pm_score": -1,
"selected": false,
"text": "from pyroute2 import IPRoute\nip = IPRoute()\n\ndef get_ipv4_address(intf):\n return dict(ip.get_addr(label=intf)[0]['attrs'])['IFA_LOCAL']\n\nprint(get_ipv4_address('eth0'))\n"
},
{
"answer_id": 65130655,
"author": "nikhil swami",
"author_id": 12179956,
"author_profile": "https://Stackoverflow.com/users/12179956",
"pm_score": 0,
"selected": false,
"text": "shell command: ipconfig def wlan_ip():\n import subprocess\n result=subprocess.run('ipconfig',stdout=subprocess.PIPE,text=True).stdout.lower()\n scan=0\n for i in result.split('\\n'):\n if 'wireless' in i: #use \"wireless\" or wireless adapters and \"ethernet\" for wired connections\n scan=1\n if scan:\n if 'ipv4' in i:\n return i.split(':')[1].strip()\nprint(wlan_ip())\n Wireless LAN adapter Wi-Fi:\n\n Connection-specific DNS Suffix . :\n Link-local IPv6 Address . . . . . : fe80::f485:4a6a:e7d5:1b1c%4\n IPv4 Address. . . . . . . . . . . : 192.168.0.131\n Subnet Mask . . . . . . . . . . . : 255.255.255.0\n Default Gateway . . . . . . . . . : 192.168.0.1\n"
},
{
"answer_id": 68378891,
"author": "Laurens",
"author_id": 3640844,
"author_profile": "https://Stackoverflow.com/users/3640844",
"pm_score": -1,
"selected": false,
"text": "const dgram = require('dgram');\n\nasync function get_local_ip() {\n const s = new dgram.createSocket('udp4');\n return new Promise((resolve, reject) => {\n try {\n s.connect(1, '8.8.8.8', function () {\n const ip = s.address();\n s.close();\n resolve(ip.address)\n });\n } catch (e) {\n console.error(e);\n s.close();\n reject(e);\n }\n })\n}\n"
},
{
"answer_id": 69369114,
"author": "TCB919",
"author_id": 8345316,
"author_profile": "https://Stackoverflow.com/users/8345316",
"pm_score": 0,
"selected": false,
"text": "iproute2 subprocess.run() -j json.loads() import subprocess\nimport json\n\nip = json.loads(subprocess.run('ip -j a'.split(),capture_output=True).stdout.decode())[1]['addr_info'][0]['local'] \n\nprint(ip)\n ip -j route get 8.8.8.8 import subprocess \nimport json \n\nip = json.loads(subprocess.run('ip -j route get 8.8.8.8'.split(),capture_output=True).stdout.decode())[0]['prefsrc']\n\nprint(ip)\n ip -j a import subprocess\nimport json\n\nlist_of_dicts = json.loads(subprocess.run('ip -j a'.split(),capture_output=True).stdout.decode())\n\nfor interface in list_of_dicts:\n try:print(f\"Interface: {interface['ifname']:10} IP: {interface['addr_info'][0]['local']}\")\n except:pass\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24789/"
] |
166,530
|
<p>Does NetworkStream.DataAvailable know whether the sender's send buffer is empty? Or does it simply indicate whether the receiver's read buffer has data? My assumption is the latter...</p>
<p>Specifically, for some socket work involving an ongoing conversation, I currently use a length-prefix so the the receiver knows exactly how much data is in the current batch; however, I've been sent a .patch suggesting I use NetworkStream.DataAvailable instead. My concern is that this will just tell me what the receiver has got - not what the sender originally sent - but I'm not a sockets expert.</p>
<p>Am I wrong? Or is length-prefix the way to go?</p>
<p>(note I can't simply Read() until the stream is closed, since multiple batches are sent on the same connection, and it is vital that I treat each batch as separate; if I read too much in one batch (even if it gets buffered and discarded) then the conversation will break).</p>
|
[
{
"answer_id": 167399,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 4,
"selected": true,
"text": "DataAvailable Read()"
},
{
"answer_id": 167895,
"author": "Lounges",
"author_id": 8918,
"author_profile": "https://Stackoverflow.com/users/8918",
"pm_score": 2,
"selected": false,
"text": "struct Header\n{\n int packetIdentifier;\n int protocolVersion;\n int messageType;\n int payloadSize;\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23354/"
] |
166,542
|
<p>We are using c++ to develop an application that runs in Windows CE 4 on an embedded system.</p>
<p>One of our constraint is that all the memory used by the application shall be allocated during <b>startup only</b>. We wrote a lot of containers and algorithms that are using only preallocated memory instead of allocating new one.</p>
<p>Do you think it is possible for us to use the boost libraries instead of our own containers in these conditions?</p>
<p>Any comments and/or advice are welcomed!</p>
<p>Thanks a lot,</p>
<p>Nic</p>
|
[
{
"answer_id": 169755,
"author": "Ted",
"author_id": 8965,
"author_profile": "https://Stackoverflow.com/users/8965",
"pm_score": 4,
"selected": false,
"text": "smart_ptr boost::bind"
},
{
"answer_id": 44555988,
"author": "ulatekh",
"author_id": 603828,
"author_profile": "https://Stackoverflow.com/users/603828",
"pm_score": 0,
"selected": false,
"text": "shared_ptr intrusive_ptr shared_ptr shared_ptr intrusive_ptr"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18800/"
] |
166,545
|
<p>How can I find the public facing IP for my net work in Python?</p>
|
[
{
"answer_id": 166552,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 5,
"selected": true,
"text": "import urllib\nip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()\n <?php echo $_SERVER['REMOTE_ADDR']; ?>\n <%\nDim UserIPAddress\nUserIPAddress = Request.ServerVariables(\"REMOTE_ADDR\")\n%>\n"
},
{
"answer_id": 166563,
"author": "Steve Losh",
"author_id": 13498,
"author_profile": "https://Stackoverflow.com/users/13498",
"pm_score": 3,
"selected": false,
"text": "import urllib\nip = urllib.urlopen('http://whatismyip.org').read()\n"
},
{
"answer_id": 36406616,
"author": "Arch Angeles",
"author_id": 6156770,
"author_profile": "https://Stackoverflow.com/users/6156770",
"pm_score": 2,
"selected": false,
"text": "import urllib2\ntext = urllib2.urlopen('http://www.whatismyip.org').read()\nurlRE=re.findall('[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}',text)\nurlRE \n\n['146.148.123.123']\n"
},
{
"answer_id": 38436633,
"author": "twig",
"author_id": 253704,
"author_profile": "https://Stackoverflow.com/users/253704",
"pm_score": 4,
"selected": false,
"text": "requests.get(\"https://api.ipify.org/?format=json\").json()['ip']"
},
{
"answer_id": 38445997,
"author": "loretoparisi",
"author_id": 758836,
"author_profile": "https://Stackoverflow.com/users/758836",
"pm_score": 1,
"selected": false,
"text": ">>> import urllib\n>>> urllib.urlopen('http://icanhazip.com/').read().strip('\\n')\n'xx.xx.xx.xx'\n"
},
{
"answer_id": 47548460,
"author": "Abhijeet",
"author_id": 452708,
"author_profile": "https://Stackoverflow.com/users/452708",
"pm_score": 3,
"selected": false,
"text": "import requests\nr = requests.get(r'http://jsonip.com')\n# r = requests.get(r'https://ifconfig.co/json')\nip= r.json()['ip']\nprint('Your IP is {}'.format(ip))\n"
},
{
"answer_id": 71074002,
"author": "htaccess",
"author_id": 599390,
"author_profile": "https://Stackoverflow.com/users/599390",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\n\n# pip install --user dnspython\n\nimport dns.resolver\n\nresolver1_opendns_ip = False\nresolver = dns.resolver.Resolver()\nopendns_result = resolver.resolve(\"resolver1.opendns.com\", \"A\")\nfor record in opendns_result:\n resolver1_opendns_ip = record.to_text()\n\nif resolver1_opendns_ip:\n resolver.nameservers = [resolver1_opendns_ip]\n myip_result = resolver.resolve(\"myip.opendns.com\", \"A\")\n for record in myip_result:\n print(f\"Your external ip is {record.to_text()}\")\n dig +short -4 myip.opendns.com @resolver1.opendns.com"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
166,550
|
<p>This is a minor style question, but every bit of readability you add to your code counts.</p>
<p>So if you've got:</p>
<pre><code>if (condition) then
{
// do stuff
}
else
{
// do other stuff
}
</code></pre>
<p>How do you decide if it's better like that, or like this:</p>
<pre><code> if (!condition) then
{
// do other stuff
{
else
{
// do stuff
}
</code></pre>
<p>My heuristics are:</p>
<ol>
<li>Keep the condition positive (less
mental calculation when reading it)</li>
<li>Put the most common path into the
first block</li>
</ol>
|
[
{
"answer_id": 166564,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 5,
"selected": true,
"text": "if (condition)\n return;\n\nDoSomething();\n"
},
{
"answer_id": 166573,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "bool MyFunc(variable) {\n if (variable != something_i_want)\n return false;\n\n // a large block of code\n // ...\n return true;\n}\n if (positive_clause) {} else {}"
},
{
"answer_id": 166576,
"author": "Ian Jacobs",
"author_id": 22818,
"author_profile": "https://Stackoverflow.com/users/22818",
"pm_score": 1,
"selected": false,
"text": "if (!PreserveData.Checked)\n{ resetfields();}\n"
},
{
"answer_id": 166579,
"author": "Simon Howard",
"author_id": 24806,
"author_profile": "https://Stackoverflow.com/users/24806",
"pm_score": 2,
"selected": false,
"text": " if (!some_function_that_could_fail())\n {\n // Error handling code\n }\n else\n {\n // Success code\n }\n"
},
{
"answer_id": 166580,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 2,
"selected": false,
"text": "if (somePositiveCondition)\nelse {\n //stuff\n}\n"
},
{
"answer_id": 166583,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 0,
"selected": false,
"text": "if"
},
{
"answer_id": 166584,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 0,
"selected": false,
"text": "!full == empty"
},
{
"answer_id": 166612,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "if (blah == false)\n{\n return; // perhaps with a message\n}\n\n// do rest of code here...\n"
},
{
"answer_id": 166644,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "if (not_dead) {\n} else {\n}\n if (alive) {\n} else {\n}\n if (!alive) {\n} else {\n}\n if (dead || (!dead && sleeping)) {\n} else {\n}\n if (dead || sleeping) {\n} else {\n}\n"
},
{
"answer_id": 166674,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "if TerminatingCondition1 then\n Exit\nif TerminatingCondition2 then\n Exit\n if NormalThing then\n DoNormalThing\nelse\n DoAbnormalThing\n"
},
{
"answer_id": 166696,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "if( common ) {\n // pass\n}\nelse {\n // great big block of exception-handling folderol\n}\n if( ! common ) {\n // great big block of except-handling folderol\n}\n"
},
{
"answer_id": 166721,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 2,
"selected": false,
"text": "if DataIsGood() then\n DoMyNormalStuff\nelse\n TakeEvasiveAction\n if SomeErrorTest then\n TakeSomeEvasiveAction\nelse if SomeOtherErrorCondition then\n CorrectMoreStupidUserProblems\nelse if YetAnotherErrorThatNoOneThoughtOf then\n DoMoreErrorHandling\nelse\n DoMyNormalStuff\n"
},
{
"answer_id": 166730,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 1,
"selected": false,
"text": " if (!widget.enabled()) {\n // more common \n } else {\n // less common \n }\n if (widget.disabled()) {\n // more common \n } else {\n // less common\n }\n"
},
{
"answer_id": 166873,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 1,
"selected": false,
"text": "if (expected)\n{\n //expected path\n}\nelse\n{\n //fallback other odd case\n} \n"
},
{
"answer_id": 166913,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 0,
"selected": false,
"text": "unless (alive) {\n go_to_heaven;\n} else {\n say \"MEDIC\";\n}\n"
},
{
"answer_id": 167044,
"author": "Chris B-C",
"author_id": 1517,
"author_profile": "https://Stackoverflow.com/users/1517",
"pm_score": 1,
"selected": false,
"text": "unless ($foo) {\n $bar;\n}\n"
},
{
"answer_id": 11505844,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "if(condition)\n{\ndoSomething();\n}\nelse\n{\nSystem.out.println(\"condition not true\")\n}\n if(!condition)\n{\ndoSomething();\n}\nelse\n{\nSystem.out.println(\"condition true\");\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14663/"
] |
166,600
|
<p>In java, when using SimpleDateFormat with the pattern:</p>
<pre><code>yyyy-MM-dd'T'HH:mm:ss.SSSZ
</code></pre>
<p>the date is outputted as:</p>
<pre><code>"2002-02-01T18:18:42.703-0700"
</code></pre>
<p>In xquery, when using the xs:dateTime function, it gives the error:</p>
<pre><code>"Invalid lexical value [err:FORG0001]"
</code></pre>
<p>with the above date. In order for xquery to parse properly, the date needs to look like:</p>
<pre><code>"2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string
</code></pre>
<p>which is based on the ISO 8601, whereas Java date is based on the RFC 822 standard.</p>
<p>I would like to be able to easily specify the timezone in Java so that it will output the way that xquery wants.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 166725,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": 0,
"selected": false,
"text": "static public String formatISO8601(Calendar cal) {\nMessageFormat format = new MessageFormat(\"{0,time}{1,number,+00;-00}:{2,number,00}\");\n\nDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\");\ndf.setTimeZone(cal.getTimeZone());\nformat.setFormat(0, df);\n\nlong zoneOff = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) / 60000L;\nint zoneHrs = (int) (zoneOff / 60L);\nint zoneMins = (int) (zoneOff % 60L);\nif (zoneMins < 0)\n zoneMins = -zoneMins;\n\nreturn (format.format(new Object[] { cal.getTime(), new Integer(zoneHrs), new Integer(zoneMins) }));\n}\n"
},
{
"answer_id": 167183,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "//NOTE: ZZ on end is not compatible with jdk, but allows for formatting \n//dates like so (note the : 3rd from last spot, which is iso8601 standard): \n//date=2008-10-03T10:29:40.046-04:00 \nprivate static final String DATE_FORMAT_8601 = \"yyyy-MM-dd'T'HH:mm:ss.SSSZZ\"; \nDateFormatUtils.format(new Date(), DATE_FORMAT_8601) \n"
},
{
"answer_id": 191865,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) {\n Date date = new Date(); \n DateTime dateTime = new DateTime(date); \n DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); \n String dateString = fmt.print(dateTime); \n System.out.println(\"dateString=\" + dateString); \n DateTime dt = fmt.parseDateTime(dateString); \n System.out.println(\"converted date=\" + dt.toDate()); \n} \n"
},
{
"answer_id": 1060276,
"author": "doodaddy",
"author_id": 24973,
"author_profile": "https://Stackoverflow.com/users/24973",
"pm_score": 1,
"selected": false,
"text": "DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date());\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
166,607
|
<p>I need to either find a file in which the version is encoded or a way of polling it across the web so it reveals its version. The server is running at a host who will not provide me command line access, although I can browse the install location via FTP.</p>
<p>I have tried HEAD and do not get a version number reported.</p>
<p>If I try a missing page to get a 404 it is intercepted, and a stock page is returned which has no server information on it. I guess that points to the server being hardened.</p>
<p>Still no closer...</p>
<p>I put a PHP file up as suggested, but I can't browse to it and can't quite figure out the URL path that would load it. In any case I am getting plenty of access denied messages and the same stock 404 page. I am taking some comfort from knowing that the server is quite robustly protected.</p>
|
[
{
"answer_id": 166619,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 8,
"selected": true,
"text": "HEAD / HTTP/1.0\n HTTP/1.1 200 OK\nDate: Fri, 03 Oct 2008 12:39:43 GMT\nServer: Apache/2.2.9 (Ubuntu) DAV/2 SVN/1.5.0 PHP/5.2.6-1ubuntu4 with Suhosin-Patch mod_perl/2.0.4 Perl/v5.10.0\nLast-Modified: Thu, 02 Aug 2007 20:50:09 GMT\nETag: \"438118-197-436bd96872240\"\nAccept-Ranges: bytes\nContent-Length: 407\nConnection: close\nContent-Type: text/html; charset=UTF-8\n HEAD http://your.webserver.com/\n curl --head http://your.webserver.com/\n telnet your.webserver.com 80\n HEAD / HTTP/1.0\n <?php phpinfo() ?>\n /usr/sbin/apache2 -V\n"
},
{
"answer_id": 166625,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 1,
"selected": false,
"text": "get / http1.1\n::enter::\n::enter::\n"
},
{
"answer_id": 166648,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 3,
"selected": false,
"text": "<?php phpinfo(); ?>\n _SERVER[\"SERVER_SOFTWARE\"]\n"
},
{
"answer_id": 166769,
"author": "Veynom",
"author_id": 11670,
"author_profile": "https://Stackoverflow.com/users/11670",
"pm_score": 3,
"selected": false,
"text": "HTTP/1.1 200 OK\nDate: Fri, 03 Oct 2008 13:09:45 GMT\nServer: Apache\nX-Powered-By: PHP/5.2.6RC4-pl0-gentoo\nSet-Cookie: PHPSESSID=a97a60f86539b5502ad1109f6759585c; path=/\nExpires: Thu, 19 Nov 1981 08:52:00 GMT\nCache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\nPragma: no-cache\nConnection: close\nContent-Type: text/html\n\n\n\nConnection to host lost.\n <?php phpinfo(); ?>\n"
},
{
"answer_id": 12110433,
"author": "crmpicco",
"author_id": 691505,
"author_profile": "https://Stackoverflow.com/users/691505",
"pm_score": 5,
"selected": false,
"text": "httpd -v Server version: Apache/2.2.3\nServer built: Oct 20 2011 17:00:12\n apachectl -v"
},
{
"answer_id": 23841194,
"author": "Martin Zeitler",
"author_id": 549372,
"author_profile": "https://Stackoverflow.com/users/549372",
"pm_score": 0,
"selected": false,
"text": "<?php\n if(isset($_SERVER['SERVER_SOFTWARE'])){\n echo $_SERVER['SERVER_SOFTWARE'];\n }\n?>\n"
},
{
"answer_id": 32045766,
"author": "matinict",
"author_id": 2239022,
"author_profile": "https://Stackoverflow.com/users/2239022",
"pm_score": -1,
"selected": false,
"text": " $version = apache_get_version();\n echo \"$version\\n\";\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24039/"
] |
166,615
|
<p>I am currently plowing my way through <a href="http://www-128.ibm.com/developerworks/edu/os-dw-os-php-cake1.html" rel="nofollow noreferrer">IBM's tutorial on CakePHP</a></p>
<p>At one point I run into this snippet of code:</p>
<pre><code><?php
class Dealer extends AppModel {
var $name = 'Dealer';
var $hasMany = array (
'Product' => array(
'className' => 'Product',
'conditions'=>, // is this allowed?
'order'=>, // same thing here
'foreignKey'=>'dealer_id'
)
);
}
?>
</code></pre>
<p>When I run it I get the following error-message: "Parse error: syntax error, unexpected ',' in /Applications/MAMP/htdocs/cakephp/app/models/product.php on line 7"</p>
<p>I'm a n00b at PHP so my question is: is it allowed to make an array with keys without assigned values? Has anybody played around with this tut and know what is up?</p>
|
[
{
"answer_id": 166627,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "$hasMany = array ('Product' => array(\n'className' => 'Product',\n'conditions'=> null, // is this allowed?\n'order'=> null, // same thing here\n'foreignKey'=>'dealer_id'));\n"
},
{
"answer_id": 166629,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 4,
"selected": true,
"text": "<?php\nclass Dealer extends AppModel\n{\nvar $name = 'Dealer';\nvar $hasMany = array ('Product' => array(\n'className' => 'Product',\n'conditions'=> null,\n'order'=> null,\n'foreignKey'=>'dealer_id')\n);\n}\n?>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24218/"
] |
166,617
|
<p>I am attempting to write an application that uses libCurl to post soap requests to a secure web service. This Windows application is built against libCurl version 7.19.0 which, in turn, is built against openssl-0.9.8i. The pertinent curl related code follows:</p>
<blockquote>
<pre>
FILE *input_file = fopen(current->post_file_name.c_str(), "rb");
FILE *output_file = fopen(current->results_file_name.c_str(), "wb");
if(input_file && output_file)
{
struct curl_slist *header_opts = 0;
CURLcode rcd;
header_opts = curl_slist_append(header_opts, "Content-Type: application/soap+xml; charset=utf8");
curl_easy_reset(curl_handle);
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, output_file);
curl_easy_setopt(curl_handle, CURLOPT_READDATA, input_file);
curl_easy_setopt(curl_handle, CURLOPT_URL, fs_service_url);
curl_easy_setopt(curl_handle, CURLOPT_POST, 1);
curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, header_opts);
rcd = curl_easy_perform(curl_handle);
if(rcd != 0)
{
current->curl_result = rcd;
current->curl_error = curl_easy_strerror(rcd);
}
curl_slist_free_all(header_opts);
}
</pre>
</blockquote>
<p>When I attempt to execute the URL, curl returns an CURLE_OUT_OF_MEMORY error which appears to be related to a failure to allocate an SSL context. Has anyone else encountered this problem before?</p>
|
[
{
"answer_id": 37317423,
"author": "vidstige",
"author_id": 363437,
"author_profile": "https://Stackoverflow.com/users/363437",
"pm_score": 0,
"selected": false,
"text": "curl_easy_setopt(curl_, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2));\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19674/"
] |
166,623
|
<p>I have some problems comparing an array with Norwegian characters with a utf8 character.</p>
<p>All characters except the special Norwegian characters(æ, ø, å) works fine.</p>
<pre><code>function isNorwegianChar($Char)
{
$aNorwegianChars = array('a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', 'æ', 'Æ', 'ø', 'Ø', 'å', 'Å', '=', '(', ')', ' ', '-');
$iArrayLength = count($aNorwegianChars);
for($iCount = 0; $iCount < $iArrayLength; $iCount++)
{
if($aNorwegianChars[$iCount] == $Char)
{
return true;
}
}
return false;
}
</code></pre>
<p>If anyone has any idea about what I can do pleas let me know.</p>
<p><strong>Update:</strong></p>
<p>The reason for needing this is that I'm trying to parse a text file that contains lines with Norwegian and Chinese words, like a dictionary. I want to split the line in to strings, one containing the Norwegian word and one containing the Chinese. This will later be inserted in a database. Example lines:</p>
<p>impulsiv 形 衝動的</p>
<p>imøtegå 動 反對,反駁</p>
<p>imøtekomme 動 符合</p>
<p>alkoholmisbruk(er) 名 濫用酒精 (名 濫用酒精的人)</p>
<p>alkoholpåvirket 形 受酒精影響的</p>
<p>alkotest 名 呼吸性酒精測試</p>
<p>alkymi(st) 名 煉金術 (名 煉金術士)</p>
<p>all, alt, alle, 形 全部, 所有 </p>
<p>As you can see there might be spaces between the words so I can not use something easy like explode to split between the Chinese and Norwegian words. What I do is use the isNorwegianChar and loop through the line until I find a char that is not in the array.</p>
<p>The problem is that it æ, ø and å is not returned as a Norwegian character and it think the Chinese word has started.</p>
<p>Here is the code:</p>
<pre><code> //Open file.
$rFile = fopen("norsk-kinesisk.txt", "r");
// Loop through the file.
$Count = 0;
while(!feof($rFile))
{
if(40== $Count)
{
break;
}
$sLine = fgets($rFile);
if(0 == $Count)
{
$sLine = mb_substr($sLine, 3);
}
$iLineLength = strlen($sLine);
$bChineseHasStarted = false;
$sNorwegianWord = '';
$sChineseWord = '';
for($iCount2 = 0; $iCount2 < $iLineLength; $iCount2++)
{
$char = mb_substr($sLine, $iCount2, 1);
if(($bChineseHasStarted === false) && (false == isNorwegianChar($char)))
{
$bChineseHasStarted = true;
}
if(false === $bChineseHasStarted)
{
$sNorwegianWord .= $char;
}
else
{
$sChineseWord .= $char;
}
//echo $char;
}
$sNorwegianWord = trim($sNorwegianWord);
$sChineseWord = trim($sChineseWord);
$Count++;
}
fclose($rFile);
</code></pre>
|
[
{
"answer_id": 166640,
"author": "Gilles",
"author_id": 10024,
"author_profile": "https://Stackoverflow.com/users/10024",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n<html>\n<head><title>norvegian utf-8 test</title>\n<meta http-equiv=\"Content-type\" value=\"text/html; charset=UTF-8\" />\n</head>\n\n<body>\n\n<?php\n\nfunction isSpecial($char) {\n $special_chars = array(\"æ\", \"ø\", \"å\", \"か\");\n return (array_search($char, $special_chars) !== false);\n}\n\nif (isset($_REQUEST[\"char\"])) {\n echo $_REQUEST[\"char\"].(isSpecial($_REQUEST[\"char\"])?\" (true)\":\" (false)\");\n}\n\n\n?>\n\n<form method=\"POST\" accept-charset=\"UTF-8\">\n<input type=\"text\" name=\"char\">\n<input type=\"submit\" value=\"submit\">\n</form>\n\n\n</body>\n</html>\n"
},
{
"answer_id": 167494,
"author": "Christoffer",
"author_id": 24811,
"author_profile": "https://Stackoverflow.com/users/24811",
"pm_score": 1,
"selected": false,
"text": "function isNorwegianChar($Char)\n{\n $sNorwegianChars = \"'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZæÆøØåÅ=() -,\";\n\n if(mb_strpos($sNorwegianChars, $Char))\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24811/"
] |
166,630
|
<p>I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there a direct way to do this using either std::strings or char* strings?</p>
<p>E.g., in Python you could simply do</p>
<pre><code>>>> "." * 5 + "lolcat"
'.....lolcat'
</code></pre>
|
[
{
"answer_id": 166646,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 8,
"selected": false,
"text": "std::string(size_type count, CharT ch) std::string(5, '.') + \"lolcat\"\n"
},
{
"answer_id": 166668,
"author": "Roskoto",
"author_id": 13635,
"author_profile": "https://Stackoverflow.com/users/13635",
"pm_score": 3,
"selected": false,
"text": "cout << multi(5) << \"whatever\" << \"lolcat\";\n"
},
{
"answer_id": 166924,
"author": "camh",
"author_id": 23744,
"author_profile": "https://Stackoverflow.com/users/23744",
"pm_score": 5,
"selected": false,
"text": "std::string str(\"lolcat\");\nstr.insert(0, 5, '.');\n"
},
{
"answer_id": 167810,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 6,
"selected": false,
"text": "std::string(5, '.')\n #include <sstream>\n\nstd::string repeat(int n) {\n std::ostringstream os;\n for(int i = 0; i < n; i++)\n os << \"repeat\";\n return os.str();\n}\n"
},
{
"answer_id": 3193642,
"author": "Ian",
"author_id": 385391,
"author_profile": "https://Stackoverflow.com/users/385391",
"pm_score": 4,
"selected": false,
"text": "cout.width(11);\ncout.fill('.');\ncout << \"lolcat\" << endl;\n .....lolcat\n"
},
{
"answer_id": 34321702,
"author": "Daniel",
"author_id": 2970186,
"author_profile": "https://Stackoverflow.com/users/2970186",
"pm_score": 4,
"selected": false,
"text": "#include <string>\n#include <cstddef>\n\nstd::string repeat(std::string str, const std::size_t n)\n{\n if (n == 0) {\n str.clear();\n str.shrink_to_fit();\n return str;\n } else if (n == 1 || str.empty()) {\n return str;\n }\n const auto period = str.size();\n if (period == 1) {\n str.append(n - 1, str.front());\n return str;\n }\n str.reserve(period * n);\n std::size_t m {2};\n for (; m < n; m *= 2) str += str;\n str.append(str.c_str(), (n - (m / 2)) * period);\n return str;\n}\n operator* #include <utility>\n\nstd::string operator*(std::string str, std::size_t n)\n{\n return repeat(std::move(str), n);\n}\n"
},
{
"answer_id": 49613515,
"author": "sorosh_sabz",
"author_id": 1539100,
"author_profile": "https://Stackoverflow.com/users/1539100",
"pm_score": 3,
"selected": false,
"text": " std::string repeat(const std::string& input, size_t num)\n {\n std::ostringstream os;\n std::fill_n(std::ostream_iterator<std::string>(os), num, input);\n return os.str();\n }\n"
},
{
"answer_id": 49743791,
"author": "Pavel P",
"author_id": 468725,
"author_profile": "https://Stackoverflow.com/users/468725",
"pm_score": 4,
"selected": false,
"text": "std::string(5, '.') std::string repeat(const std::string& input, unsigned num)\n{\n std::string ret;\n ret.reserve(input.size() * num);\n while (num--)\n ret += input;\n return ret;\n}\n"
},
{
"answer_id": 64919825,
"author": "claytonjwong",
"author_id": 8334739,
"author_profile": "https://Stackoverflow.com/users/8334739",
"pm_score": 2,
"selected": false,
"text": "repeated #include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n\nusing namespace std;\n\nint main() {\n ostringstream repeated;\n fill_n(ostream_iterator<string>(repeated), 3, string(\"abc\"));\n cout << \"repeated: \" << repeated.str() << endl; // repeated: abcabcabc\n return 0;\n}\n"
},
{
"answer_id": 71564035,
"author": "Matthew M.",
"author_id": 7410473,
"author_profile": "https://Stackoverflow.com/users/7410473",
"pm_score": 1,
"selected": false,
"text": "#include <string>\n#include <cstddef>\n\nstd::string repeat(size_t n, const std::string& str) {\n if (n == 0 || str.empty()) return {};\n if (n == 1) return str;\n const auto period = str.size();\n if (period == 1) return std::string(n, str.front());\n\n std::string ret(str);\n ret.reserve(period * n);\n std::size_t m {2};\n for (; m < n; m *= 2) ret += ret;\n ret.append(ret.c_str(), (n - (m / 2)) * period);\n return ret;\n}\n str str repeat"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
166,641
|
<p>In the following example should I expect that <code>values.size()</code> will be called every time around the loop? In which case it might make sense to introduce a temporary <code>vectorSize</code> variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change.</p>
<pre><code>double sumVector(const std::vector<double>& values) {
double sum = 0.0;
for (size_t ii = 0; ii < values.size(); ++ii) {
sum += values.at(ii);
}
}
</code></pre>
<p>Note that I don't care if there are more efficient methods to sum the contents of a vector, this question is just about the use of size() in a for construct.</p>
|
[
{
"answer_id": 166704,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 2,
"selected": false,
"text": "for (int i=v.size()-1; i>=0 ;i--)\n{\n ...\n}\n"
},
{
"answer_id": 166774,
"author": "Curro",
"author_id": 10688,
"author_profile": "https://Stackoverflow.com/users/10688",
"pm_score": 1,
"selected": false,
"text": "std::vector<double>::const_iterator iter = values.begin();\nfor(; iter != values.end(); ++iter)\n{\n // use the iterator here to access the value.\n}\n"
},
{
"answer_id": 166885,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 1,
"selected": false,
"text": "for while"
},
{
"answer_id": 166903,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": true,
"text": "for (size_t ii = 0, count = values.size(); ii < count; ++ii)\n"
},
{
"answer_id": 167022,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "at [] at at try at double sum = 0.0;\nforeach (double d, values)\n sum += d;\n"
},
{
"answer_id": 167825,
"author": "Kaz Dragon",
"author_id": 24913,
"author_profile": "https://Stackoverflow.com/users/24913",
"pm_score": 3,
"selected": false,
"text": "size_t size = values.size();\nfor (size_t ii = 0; ii < size; ++ii) {\n sum += values.at(ii)\n}\n for (size_t ii = 0; ii < values.size(); ++ii) {\n sum += values.at(ii);\n}\n double sum = std::accumulate(values.begin(), values.end(), 0);\n"
},
{
"answer_id": 169645,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "size() std::list std::vector std::vector::size() std::vector::size()"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3229/"
] |
166,658
|
<p>I am using <a href="http://nant.sourceforge.net/release/0.85-rc2/help/fundamentals/listeners.html#MailLogger" rel="nofollow noreferrer">MailLogger</a> to send a message about a failed/successful release. I would like to make the mail body simple and easy to read. How can I suppress output for some particular tasks?</p>
|
[
{
"answer_id": 166704,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 2,
"selected": false,
"text": "for (int i=v.size()-1; i>=0 ;i--)\n{\n ...\n}\n"
},
{
"answer_id": 166774,
"author": "Curro",
"author_id": 10688,
"author_profile": "https://Stackoverflow.com/users/10688",
"pm_score": 1,
"selected": false,
"text": "std::vector<double>::const_iterator iter = values.begin();\nfor(; iter != values.end(); ++iter)\n{\n // use the iterator here to access the value.\n}\n"
},
{
"answer_id": 166885,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 1,
"selected": false,
"text": "for while"
},
{
"answer_id": 166903,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": true,
"text": "for (size_t ii = 0, count = values.size(); ii < count; ++ii)\n"
},
{
"answer_id": 167022,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "at [] at at try at double sum = 0.0;\nforeach (double d, values)\n sum += d;\n"
},
{
"answer_id": 167825,
"author": "Kaz Dragon",
"author_id": 24913,
"author_profile": "https://Stackoverflow.com/users/24913",
"pm_score": 3,
"selected": false,
"text": "size_t size = values.size();\nfor (size_t ii = 0; ii < size; ++ii) {\n sum += values.at(ii)\n}\n for (size_t ii = 0; ii < values.size(); ++ii) {\n sum += values.at(ii);\n}\n double sum = std::accumulate(values.begin(), values.end(), 0);\n"
},
{
"answer_id": 169645,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "size() std::list std::vector std::vector::size() std::vector::size()"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] |
166,695
|
<p>I know I can cycle through my tabs using cmd+{ or cmd+}, but is it possible to select a specific tab (i.e. cmd+3 for the third tab in iTerm) in Leopards' Terminal.app? </p>
|
[
{
"answer_id": 953105,
"author": "Topher Fangio",
"author_id": 85309,
"author_profile": "https://Stackoverflow.com/users/85309",
"pm_score": -1,
"selected": false,
"text": ".screenrc defscrollback 1024\nhardstatus on\nhardstatus alwayslastline\nhardstatus string \"%{.bW}%-w%{.rW}%n %t%{-}%+w %=%{..G} %H %{..Y} %m/%d %C%a \"\n screen -c ~/.screenrc.programming source $HOME/.screenrc\n\nscreen -t World\nscreen -t Server\nscreen -t Console\nscreen -t Command\nscreen -t Editor\nscreen -t MySQL\n Ctrl-A,n Ctrl-A,p Ctrl-A"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16685/"
] |
166,712
|
<p>I have noticed that some apps like Safari and Mail show a loading indicator in the status bar (the bar at the very top of the phone) when they are accessing the network. Is there a way to do the same thing in SDK apps, or is this an Apple only thing?</p>
|
[
{
"answer_id": 166734,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 9,
"selected": true,
"text": "[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;\n [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;\n UIApplication.shared.isNetworkActivityIndicatorVisible = true\n UIApplication.shared.isNetworkActivityIndicatorVisible = false\n"
},
{
"answer_id": 1750967,
"author": "Michael Waterfall",
"author_id": 106244,
"author_profile": "https://Stackoverflow.com/users/106244",
"pm_score": 5,
"selected": false,
"text": "#define ShowNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = YES\n#define HideNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = NO\n ShowNetworkActivityIndicator(); HideNetworkActivityIndicator();"
},
{
"answer_id": 13412791,
"author": "Resh32",
"author_id": 1611950,
"author_profile": "https://Stackoverflow.com/users/1611950",
"pm_score": 5,
"selected": false,
"text": "#import <Foundation/Foundation.h>\n\n@interface RMActivityIndicator : NSObject\n\n-(void)increaseActivity;\n-(void)decreaseActivity;\n-(void)noActivity;\n\n+(RMActivityIndicator *)sharedManager;\n\n@end\n #import \"RMActivityIndicator.h\"\n\n@interface RMActivityIndicator ()\n\n@property(nonatomic,assign) unsigned int activityCounter;\n\n@end\n\n@implementation RMActivityIndicator\n\n- (id)init\n{\n self = [super init];\n if (self) {\n self.activityCounter = 0;\n }\n return self;\n}\n\n -(void)increaseActivity{\n @synchronized(self) {\n self.activityCounter++;\n }\n [self updateActivity];\n }\n-(void)decreaseActivity{\n @synchronized(self) {\n if (self.activityCounter>0) self.activityCounter--;\n }\n [self updateActivity];\n}\n-(void)noActivity{\n self.activityCounter = 0;\n [self updateActivity];\n}\n\n-(void)updateActivity{\n UIApplication* app = [UIApplication sharedApplication];\n app.networkActivityIndicatorVisible = (self.activityCounter>0);\n}\n\n#pragma mark -\n#pragma mark Singleton instance\n\n+(RMActivityIndicator *)sharedManager {\n static dispatch_once_t pred;\n static RMActivityIndicator *shared = nil;\n\n dispatch_once(&pred, ^{\n shared = [[RMActivityIndicator alloc] init];\n });\n return shared;\n}\n\n@end\n [[RMActivityIndicator sharedManager]increaseActivity];\n [NSURLConnection sendAsynchronousRequest:urlRequest queue:self.networkReceiveProcessQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)\n {\n [[RMActivityIndicator sharedManager]decreaseActivity];\n }\n"
},
{
"answer_id": 13623764,
"author": "asish",
"author_id": 1175051,
"author_profile": "https://Stackoverflow.com/users/1175051",
"pm_score": 4,
"selected": false,
"text": "[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;\n"
},
{
"answer_id": 29040799,
"author": "Sev",
"author_id": 2640458,
"author_profile": "https://Stackoverflow.com/users/2640458",
"pm_score": 2,
"selected": false,
"text": "dispatch_async(dispatch_get_main_queue(), ^{\n [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];\n});\n"
},
{
"answer_id": 35449012,
"author": "Babu Lal",
"author_id": 4309479,
"author_profile": "https://Stackoverflow.com/users/4309479",
"pm_score": 3,
"selected": false,
"text": "AFNetworking AppDelegate AFNetworking/AFNetworkActivityIndicatorManager.h didFinishLaunchingWithOptions: [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]"
},
{
"answer_id": 56697071,
"author": "M Reza",
"author_id": 3815069,
"author_profile": "https://Stackoverflow.com/users/3815069",
"pm_score": 3,
"selected": false,
"text": "UIApplication.shared.isNetworkActivityIndicatorVisible = true"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] |
166,718
|
<p><strong>Background</strong></p>
<p>I am trying to create a copy of a business object I have created in VB.NET. I have implemented the ICloneable interface and in the Clone function, I create a copy of the object by serializing it with a BinaryFormatter and then de-serializing straight back out into another object which I return from the function.</p>
<p>The class I am trying to serialize is marked as "Serializable" along with the child objects that are contained within the class.</p>
<p>I have tested that the clone method works by writing code similar to the following:</p>
<pre><code>Dim obj as New Sheep()
Dim dolly as Sheep = obj.Clone()
</code></pre>
<p>All works fine at this point.</p>
<p><strong>Problem</strong></p>
<p>I have a custom windows forms control which inherits from a 3rd party control. This custom control basically contains the object which I want to clone (as this object ultimatly feeds the 3rd party control).</p>
<p>I want to create a clone of the object within the windows form control so that I can allow the user to manipulate the properties whilst having the option of cancelling the changes and reverting the object back to how it was before they made the changes. I would like to take the copy of the object before the user starts making changes and hold onto it so I have it ready if they press cancel.</p>
<p>My thought would be to write code along the lines of the following:</p>
<pre><code>Dim copy as Sheep = MyControl.Sheep.Clone()
</code></pre>
<p>Then allow the user to manipulate the properties on <code>MyControl.Sheep</code>. When I attempt to do this however, the clone method throws an exception stating:</p>
<p><em>Type 'MyControl' in Assembly 'My_Assembly_Info_Here' is not marked as serializable</em></p>
<p>This error is thrown at the point where I call <code>BinaryFormatter.Serialize(stream,Me)</code>.</p>
<p>I have tried creating a method on <code>MyControl</code> that returns a copy of the object and also first assigning <code>MyControl.Sheep</code> to another variable and then cloning the variable but nothing seems to work. However, creating a new instance of the object directly and cloning it works fine!</p>
<p>Any idea's where I am going wrong?</p>
<p><strong>Solution</strong></p>
<p>Marc's answer helped point me in the right direction on this one. <a href="http://www.lhotka.net/WeBlog/CommentView.aspx?guid=776f44e8-aaec-4845-b649-e0d840e6de2c" rel="nofollow noreferrer">This</a> blog post from Rocky Lhotka explains the problem and how to solve it. </p>
|
[
{
"answer_id": 166883,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleApplication1\n{\n public class NonSerializableSheep\n {\n public NonSerializableSheep() { }\n\n public string Name { get; set; }\n public int Id { get; set; }\n // public read only properties can create a problem\n // with this approach if another property or (worse)\n // a group of properties sets it\n public int Legs { get; private set; }\n\n public override string ToString()\n {\n return String.Format(\"{0} ({1})\", Name, Id);\n }\n }\n\n public static class GhettoSerializer\n {\n // you could make this a factory method if your type\n // has a constructor that appeals to you (i.e. default \n // parameterless constructor)\n public static void Initialize<T>(T instance, IDictionary<string, object> values)\n {\n var props = typeof(T).GetProperties();\n\n // my approach does nothing to handle rare properties with array indexers\n var matches = props.Join(\n values,\n pi => pi.Name,\n kvp => kvp.Key,\n (property, kvp) =>\n new {\n Set = new Action<object,object,object[]>(property.SetValue), \n kvp.Value\n }\n );\n\n foreach (var match in matches)\n match.Set(instance, match.Value, null);\n }\n public static IDictionary<string, object> Serialize<T>(T instance)\n {\n var props = typeof(T).GetProperties();\n\n var ret = new Dictionary<string, object>();\n\n foreach (var property in props)\n {\n if (!property.CanWrite || !property.CanRead)\n continue;\n ret.Add(property.Name, property.GetValue(instance, null));\n }\n\n return ret;\n }\n }\n\n public class Program\n {\n public static void Main()\n {\n var nss = new NonSerializableSheep\n {\n Name = \"Dolly\",\n Id = 12\n };\n\n Console.WriteLine(nss);\n\n var bag = GhettoSerializer.Serialize(nss);\n\n // a factory deserializer eliminates the additional\n // declarative step\n var nssCopy = new NonSerializableSheep();\n GhettoSerializer.Initialize(nssCopy, bag);\n\n Console.WriteLine(nssCopy);\n\n Console.ReadLine();\n\n }\n }\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6165/"
] |
166,722
|
<p>I know the name of the table I want to find. I'm using Microsoft SQL Server Management Studio 2005, and I want to search all databases in the database server that I'm attached to in the studio. Is this possible? Do I need to query the system tables?</p>
|
[
{
"answer_id": 166866,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 1,
"selected": false,
"text": "SELECT name, DbID \nFROM master..sysdatabases\nWHERE name NOT IN ('northwind', 'pubs')\nAND (status & 32) <> 32 --loading.\nAND (status & 64) <> 64 --pre recovery.\nAND (status & 128) <> 128 --recovering.\nAND (status & 256) <> 256 --not recovered.\nAND (status & 512) <> 512 --Offline\nAND (status & 32768) <> 32768 --emergency mode.\nAND DbID > 4\n set @sql_string = ''\n+' Insert into #tblDatabaseName '\n+' select ''' + @db_name + ''' as ''DbName'', '\n+' o.name as ''TableName'' '\n+' from [' + @db_name + ']..sysobjects o with(nolock) '\n+' where o.name like ''' + @TableName + ''' ' \n\nexecute sp_executesql @sql_string\n\nfetch next from db_cursor into @db_name, @DbID\n"
},
{
"answer_id": 166932,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": 1,
"selected": false,
"text": "EXEC sp_MSForEachDB 'USE [?] IF EXISTS(SELECT * FROM Sys.Objects WHERE Type = ''U'' AND Name = ''Product'') PRINT ''?'''\n"
},
{
"answer_id": 202354,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 3,
"selected": true,
"text": "EXEC sp_MSForEachDB 'USE [?] IF OBJECT_ID(''dbo.mytable'') IS NOT NULL PRINT ''?'''\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5716/"
] |
166,739
|
<p>I've got a byte() array returned as result of directx sound capture, but for other parts of my program I want to treat the results as single(). Is trundling down the array item by item the fastest way of doing it or is there a clever way to do it ? </p>
<p>The code that gets it is</p>
<pre><code>CType(Me._applicationBuffer.Read(Me._nextCaptureOffset, GetType(Byte), LockFlag.None, LockSize), Byte())
</code></pre>
<p>which creates the byte array, can Ctype handle single ? (note, I can't figure out a way to do it!)</p>
|
[
{
"answer_id": 166755,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": -1,
"selected": false,
"text": "float f = BitConverter.ToSingle(bytearray, 0);\n Dim single s;\ns = BitConverter.ToSingle(bytearray, 0);\n"
},
{
"answer_id": 171829,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "public float[] ByteArrayToFloatArray(byte[] byteArray)\n{\n float[] floatArray = new float[byteArray.Length / 4];\n for (int i = 0; i < floatArray.Length; i++)\n {\n floatArray[i] = BitConverter.ToSingle(byteArray, i * 4);\n }\n return floatArray;\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2135219/"
] |
166,742
|
<p>I would like to make a list of remarkable robot simulation environments including advantages and disadvantages of them. Some examples I know of are <a href="http://www.cyberbotics.com/" rel="noreferrer">Webots</a> and <a href="http://playerstage.sourceforge.net/" rel="noreferrer">Player/Stage</a>.</p>
|
[
{
"answer_id": 1685675,
"author": "Barrett Ames",
"author_id": 204392,
"author_profile": "https://Stackoverflow.com/users/204392",
"pm_score": 3,
"selected": false,
"text": "rviz nav_view"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21047/"
] |
166,752
|
<p>Does anyone know the full list of C# compiler number literal modifiers?</p>
<p>By default declaring '0' makes it an Int32 and '0.0' makes it a 'Double'. I can use the literal modifier 'f' at the end to ensure something is treated as a 'Single' instead. For example like this...</p>
<pre><code>var x = 0; // x is Int32
var y = 0f; // y is Single
</code></pre>
<p>What are the other modifiers I can use? Is there one for forcing to Double, Decimal, UInt32? I tried googling for this but could not find anything. Maybe my terminology is wrong and so that explains why I am coming up blank. Any help much appreciated.</p>
|
[
{
"answer_id": 166762,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 7,
"selected": true,
"text": "var y = 0f; // y is single\nvar z = 0d; // z is double\nvar r = 0m; // r is decimal\nvar i = 0U; // i is unsigned int\nvar j = 0L; // j is long (note capital L for clarity)\nvar k = 0UL; // k is unsigned long (note capital L for clarity)\n"
},
{
"answer_id": 166787,
"author": "Nic Wise",
"author_id": 2947,
"author_profile": "https://Stackoverflow.com/users/2947",
"pm_score": 3,
"selected": false,
"text": "var x = 0; //whats x?\nfloat x = 0; //oh, it's a float\nbyte x = 0; // or not!\n"
},
{
"answer_id": 166809,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": " var y = (float)0; // y is single\n var z = (double)0; // z is double\n var r = (decimal)0; // r is decimal\n var i = (uint)0; // i is unsigned int\n var j = (long)0; // j is long\n var k = (ulong)0; // k is unsigned long\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6276/"
] |
166,802
|
<p>Has anyone ever had the issue where trying to "View Designer" on a windows form in Visual Studio .NET causes the error: <strong>"Could not load file or assembly…"</strong> ?</p>
<p>In this case, the assembly in question was <code>XYZ.dll</code>. I managed to fix this by adding <code>XYZ.dll</code> and all its references to my project's references (even though my project doesn't directly depend on them) and rebuilding the whole solution. However, after that, I removed all those references from my project, rebuilt, and it still worked. </p>
<p>One other piece of information is that I use <strong>Resharper 2.5</strong>. Someone else pointed out that it might be Resharper doing some shadow copying. I'll look into this next time this happens.
Does anyone have a understanding of why this error happens in the first place, and possibly the 'correct' way to fix it?</p>
|
[
{
"answer_id": 166867,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 5,
"selected": false,
"text": "TypeLoadException devenv.exe"
},
{
"answer_id": 7854643,
"author": "J Collins",
"author_id": 576262,
"author_profile": "https://Stackoverflow.com/users/576262",
"pm_score": 5,
"selected": false,
"text": "=== Pre-bind state information ===\nLOG: User = **************\nLOG: DisplayName = ***********, Version=1.0.4275.22699, Culture=neutral, PublicKeyToken=null\n (Fully-specified)\nLOG: Appbase = file:///C:/Program Files/Microsoft Visual Studio 10.0/Common7/IDE/\nLOG: Initial PrivatePath = NULL\nCalling assembly : ***********, Version=1.0.4275.22699, Culture=neutral, PublicKeyToken=null.\n===\nLOG: This bind starts in default load context.\nLOG: Using application configuration file: C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\IDE\\devenv.exe.Config\nLOG: Using host configuration file: \nLOG: Using machine configuration file from C:\\WINDOWS\\Microsoft.NET\\Framework\\v4.0.30319\\config\\machine.config.\nLOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).\nLOG: The same bind was seen before, and was failed with hr = 0x80070002.\n"
},
{
"answer_id": 35914799,
"author": "Brij",
"author_id": 846380,
"author_profile": "https://Stackoverflow.com/users/846380",
"pm_score": 0,
"selected": false,
"text": "clean+rebuild clean+rebuild userContorl1 was in myapp.mynamespace1, and \nuserControl2 was in myapp.myNamespace1\n clean+rebuild myUserControl1.SomeType = somenamespace.SomeGenericClass(of Date).SomeEnum\n myUserControl1.SomeType = somenamespace.SomeEnum\n"
},
{
"answer_id": 36340939,
"author": "John Kroetch",
"author_id": 1539223,
"author_profile": "https://Stackoverflow.com/users/1539223",
"pm_score": 0,
"selected": false,
"text": "try\n{\n _InitializeStuff();\n}\ncatch (Exception ex)\n{\n Logger.Instance.Log(\"Couldn't instantiate: \" + ex.Messsage);\n}"
},
{
"answer_id": 39264574,
"author": "c-iii-O",
"author_id": 3292559,
"author_profile": "https://Stackoverflow.com/users/3292559",
"pm_score": 1,
"selected": false,
"text": "...\nusing System.Windows.Forms; // UserControl\n\nnamespace MyNamespace\n{\n public class MyForm : Form\n {\n public MyForm()\n {\n InitializeComponent();\n ...\n }\n\n private void InitializeComponent()\n {\n //this.ctrl = new MyNamespace.MyCtrl(); // Inherited class\n this.ctrl = new System.Windows.Forms.UserControl();\n ...\n }\n\n //private MyNamespace.MyCtrl myCtrl; // Inherited class\n private UserControl ctrl;\n }\n\n public class MyCtrl : UserControl\n {\n ...\n }\n}\n MyCtrl MyForm UserControl"
},
{
"answer_id": 45876244,
"author": "user8515392",
"author_id": 8515392,
"author_profile": "https://Stackoverflow.com/users/8515392",
"pm_score": 0,
"selected": false,
"text": "devenv /resetsettings devenv /resetSkippkgs"
},
{
"answer_id": 56837488,
"author": "Ross Crooks",
"author_id": 10570144,
"author_profile": "https://Stackoverflow.com/users/10570144",
"pm_score": 0,
"selected": false,
"text": "<data name=\"EventBar1.EventCheckedSubscriptions\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n <value>\n AAEAAAD/////AQAAAAAAAAAMAgAAAJoBbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1u\n ZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIG1zY29ybGliLCBWZXJzaW9u\n PTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUB\n AAAANlN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkV2ZW50SGFuZGxlcgMA\n AAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uAwAAFVN5c3RlbS5FdmVudEhhbmRsZXJbXQgIAgAAAAkDAAAA\n AAAAAAAAAAAHAwAAAAABAAAAAAAAAAMTU3lzdGVtLkV2ZW50SGFuZGxlcgs=\n</value>\n </data>\n <data name=\"EventBar1.EventLengthSubscriptions\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n <value>\n AAEAAAD/////AQAAAAAAAAAMAgAAAJoBbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1u\n ZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIG1zY29ybGliLCBWZXJzaW9u\n PTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUB\n AAAANlN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkV2ZW50SGFuZGxlcgMA\n AAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uAwAAFVN5c3RlbS5FdmVudEhhbmRsZXJbXQgIAgAAAAkDAAAA\n AAAAAAAAAAAHAwAAAAABAAAAAAAAAAMTU3lzdGVtLkV2ZW50SGFuZGxlcgs=\n</value>\n </data>\n <data name=\"EventBar1.EventLengthTypes\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n <value>\n AAEAAAD/////AQAAAAAAAAAMAgAAAKABY3RybENhbGVuZGFyU2lkZUJhciwgVmVyc2lvbj0xLjAuNzEy\n MS4yMTIzNCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsXV0sIG1zY29ybGliLCBW\n ZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0\n ZTA4OQwDAAAAUWN0cmxDYWxlbmRhclNpZGVCYXIsIFZlcnNpb249MS4wLjcxMjEuMjEyMzQsIEN1bHR1\n cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUBAAAAT1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5l\n cmljLkxpc3RgMVtbY3RybENhbGVuZGFyU2lkZUJhci5FdmVudEJhcitFdmVudExlbmd0aFR5cGUDAAAA\n Bl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgQAAC5jdHJsQ2FsZW5kYXJTaWRlQmFyLkV2ZW50QmFyK0V2ZW50\n TGVuZ3RoVHlwZVtdAwAAAAgIAgAAAAkEAAAAAAAAAAAAAAAHBAAAAAABAAAAAAAAAAQsY3RybENhbGVu\n ZGFyU2lkZUJhci5FdmVudEJhcitFdmVudExlbmd0aFR5cGUDAAAACw==\n</value>\n </data>\n <data name=\"EventBar1.EventSettingsSubscriptions\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n <value>\n AAEAAAD/////AQAAAAAAAAAMAgAAAJoBbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1u\n ZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIG1zY29ybGliLCBWZXJzaW9u\n PTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUB\n AAAANlN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkV2ZW50SGFuZGxlcgMA\n AAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uAwAAFVN5c3RlbS5FdmVudEhhbmRsZXJbXQgIAgAAAAkDAAAA\n AAAAAAAAAAAHAwAAAAABAAAAAAAAAAMTU3lzdGVtLkV2ZW50SGFuZGxlcgs=\n</value>\n </data>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
166,823
|
<p>Suppose I have a base class B, and a derived class D. I wish to have a method foo() within my base class that returns a new object of whatever type the instance is. So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation resides solely in the base class B.</p>
<p>Is this possible?</p>
|
[
{
"answer_id": 166849,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 2,
"selected": false,
"text": " public B instance() throws Exception {\n return getClass().newInstance();\n }\n"
},
{
"answer_id": 166861,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "public ClassName getFoo() throws InstantiationException, IllegalAccessException\n{\n return getClass().newInstance();\n}\n"
},
{
"answer_id": 166877,
"author": "MattC",
"author_id": 21126,
"author_profile": "https://Stackoverflow.com/users/21126",
"pm_score": 1,
"selected": false,
"text": "public B foo() {\n return this.getClass().newInstance();\n}\n"
},
{
"answer_id": 166934,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 0,
"selected": false,
"text": "public class B <X extends B>{\n\npublic X foo() throws InstantiationException, IllegalAccessException{\n return (X)this.getClass().newInstance();\n}\n} \npublic class C extends B<C>{ \n\n}\n"
},
{
"answer_id": 166949,
"author": "Bruno Ranschaert",
"author_id": 4900,
"author_profile": "https://Stackoverflow.com/users/4900",
"pm_score": 1,
"selected": false,
"text": "public class B {\n public B foo()\n throws IllegalAccessException, InstantiationException {\n return this.getClass().newInstance();\n }\n}\n\npublic class D extends B{ \n}\n\npublic class Test {\n public static final void main(String[] args)\n {\n try {\n System.out.println((new B()).foo());\n System.out.println((new D()).foo());\n } catch (IllegalAccessException e) {\n e.printStackTrace(); \n } catch (InstantiationException e) {\n e.printStackTrace(); \n }\n }\n}\n"
},
{
"answer_id": 166959,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 1,
"selected": false,
"text": "Thing foo() {\n Thing th = getNewInstance();\n // do some stuff with th\n return th;\n}\n\nThing getNewInstance() {\n return getClass().newInstance();\n}\n Thing getNewInstance() {\n return new BigThing(10, ThingSize.METRES);\n}\n"
},
{
"answer_id": 167163,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 3,
"selected": true,
"text": "abstract class B {\n public abstract B foo();\n}\n abstract class B {\n private final BFactory factory;\n protected B(BFactory factory) {\n this.factory = factory;\n }\n public B foo() {\n return factory.create();\n }\n}\ninterface BFactory {\n B create();\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
] |
166,836
|
<p>If we put aside the rights and wrongs of putting demo data into a live system for a minute (that's a whole separate discussion!), we are being asked to store some demo data in our live system so that it can be credibly demonstrated without the appearance of smoke + mirrors (we want to use the same login page for example)</p>
<p>Since I'm sure this is a challenge many other people must have - I'd be interested to know what approaches have people have devised to separating this data so that it doesn't get in the way of day to day operations on their systems?</p>
<p>As I alluded to above, I'm aware that this probably isn't best practice. :-)</p>
|
[
{
"answer_id": 291101,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM tableA \n SELECT * FROM (SELECT * FROM tableA WHERE Data_quality = 'PROD' <or however you do it>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19629/"
] |
166,841
|
<p>I have a xml blob that's checked against a schema in sql 2005. My website uses xsl to transform and display the blob. How do I add a hyperlink to the xml (in any node) without the sql 2005 schema complaining a node was found in the wrong place? Or the xsl thinking that the hyperlink is a valid xml node?</p>
<p>thank you</p>
|
[
{
"answer_id": 291101,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM tableA \n SELECT * FROM (SELECT * FROM tableA WHERE Data_quality = 'PROD' <or however you do it>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433/"
] |
166,844
|
<p>I'm working on an integration testing project in .NET. The testing framework executable starts a service and then needs to wait for the service to complete an operation.</p>
<p>What is the best approach for the exe to wait on the service to complete its task (the service itself will not exit upon task completion)?</p>
<p>Both processes have access to the same database, so my first thought was a simple table that records the service's status. Once it's signaled that it's done, the exe can stop waiting and complete its task. Other approaches?</p>
<p>Let me reiterate that the service, once it has completed its task, will remain in a running/in-memory state, so waiting for it to exit won't work. ;-)</p>
<p>Also, this is purely for integration testing purposes, and will never go into production, so "simple" is the operative word.</p>
|
[
{
"answer_id": 166951,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 4,
"selected": true,
"text": "Semaphore Release() WaitOne() Semaphore s = new Semaphore(1, 1, \"MyNamedSemaphore\");\n// start service, passing the string \"MyNamedSemaphore\"\ns.WaitOne(); // will wait for Release() in service\n // perform the initial task\n// find semaphore name (i.e. from Environment.CommandLine)\nSemaphore s = new Semaphore(1, 1, semaphoreName); // will use existing kernel object\ns.Release(); // WaitOne in exe will complete\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] |
166,855
|
<p>What is the PHP preg_replace in C#?</p>
<p>I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do something like that in C# without using .Replace("old","new").</p>
<pre><code>$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';
$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);
</code></pre>
|
[
{
"answer_id": 166889,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "System.Text.RegularExpressions using System.Text.RegularExpressions;\n\nRegex r = new Regex(\"=C0\");\nstring output = r.Replace(text);\n"
},
{
"answer_id": 166939,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "public static class ExtensionMethods\n{\n public static String PregReplace(this String input, string[] pattern, string[] replacements)\n {\n if (replacements.Length != pattern.Length)\n throw new ArgumentException(\"Replacement and Pattern Arrays must be balanced\");\n\n for (var i = 0; i < pattern.Length; i++)\n {\n input = Regex.Replace(input, pattern[i], replacements[i]); \n }\n\n return input;\n }\n}\n class Program\n {\n static void Main(string[] args)\n {\n String[] pattern = new String[4];\n String[] replacement = new String[4];\n\n pattern[0] = \"Quick\";\n pattern[1] = \"Fox\";\n pattern[2] = \"Jumped\";\n pattern[3] = \"Lazy\";\n\n replacement[0] = \"Slow\"; \n replacement[1] = \"Turtle\";\n replacement[2] = \"Crawled\";\n replacement[3] = \"Dead\";\n\n String DemoText = \"The Quick Brown Fox Jumped Over the Lazy Dog\";\n\n Console.WriteLine(DemoText.PregReplace(pattern, replacement));\n } \n }\n"
},
{
"answer_id": 166940,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "stringsList.Select( s => replacementsList.Select( r => s.Replace(s,r) ) );\n"
},
{
"answer_id": 167296,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": true,
"text": "public static class StringManipulation\n{\n public static string PregReplace(string input, string[] pattern, string[] replacements)\n {\n if (replacements.Length != pattern.Length)\n throw new ArgumentException(\"Replacement and Pattern Arrays must be balanced\");\n\n for (int i = 0; i < pattern.Length; i++)\n {\n input = Regex.Replace(input, pattern[i], replacements[i]); \n }\n\n return input;\n }\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
166,876
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/76760/vs2008-setup-project-shared-by-all-users-application-data-files">VS2008 Setup Project: Shared (By All Users) Application Data Files?</a> </p>
</blockquote>
<p>Please can someone advice what is the best place (path) to put some application data which should be accessible and editable by all users.</p>
<p>This is considering both Windows XP and Windows Vista and i expect that change in any file of above path does NOT trigger UAC!</p>
|
[
{
"answer_id": 166881,
"author": "JC.",
"author_id": 3615,
"author_profile": "https://Stackoverflow.com/users/3615",
"pm_score": 2,
"selected": false,
"text": "Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)\n"
},
{
"answer_id": 166906,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 3,
"selected": false,
"text": "CSIDL_COMMON_APPDATA"
},
{
"answer_id": 191316,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 1,
"selected": false,
"text": "// assumes\n// company is a pointer to a character sting containing company name\n// appname is a pointer to a character string containing application name\n// fname is a pointer to a character string cintaining name of file to be created\n\n#include <shlobj.h> // for SHGetFolderPath\n#include <direct.h> // for _mkdir\n\nchar path[MAX_PATH];\nSHGetFolderPath(NULL,CSIDL_COMMON_APPDATA,NULL,NULL,path);\nstrcat(path,\"/\");\nstrcat(path,company);\n_mkdir(path);\nstrcat(path,\"/\");\nstrcat(path,appname);\n_mkdir(path);\nstrcat(path,\"/\");\nstrcat(path,fname);\n\n// path is now a character string which can passed to fopen\n"
},
{
"answer_id": 7489017,
"author": "Doug Kavendek",
"author_id": 9330,
"author_profile": "https://Stackoverflow.com/users/9330",
"pm_score": 0,
"selected": false,
"text": "FOLDERID_ProgramData"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
166,884
|
<p>Why would someone want to use a linked-list over an array?</p>
<p>Coding a linked-list is, no doubt, a bit more work than using an array and one may wonder what would justify the additional effort.</p>
<p>I think insertion of new elements is trivial in a linked-list but it's a major chore in an array. Are there other advantages to using a linked list to store a set of data versus storing it in an array?</p>
<p>This question is not a duplicate of <a href="https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist">this question</a> because the other question is asking specifically about a particular Java class while this question is concerned with the general data structures. </p>
|
[
{
"answer_id": 166978,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "#include <vector>"
},
{
"answer_id": 167448,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 6,
"selected": false,
"text": "a = (1 2 3 4, ....)\nb = (4 3 2 1 1 2 3 4 ...)\nc = (3 4 ...)\n b = 4 -> 3 -> 2 -> 1 -> a\nc = a.next.next \n a b c prepend tail"
},
{
"answer_id": 1656533,
"author": "mhaller",
"author_id": 75126,
"author_profile": "https://Stackoverflow.com/users/75126",
"pm_score": 4,
"selected": false,
"text": "arrayList ArrayList<String>\n elementData Object[]\n [0] Object \"Foo\"\n [1] Object \"Foo\"\n [2] Object \"Foo\"\n [3] Object \"Foo\"\n [4] Object \"Foo\"\n ...\n linkedList LinkedList<String>\n header LinkedList$Entry<E>\n element E\n next LinkedList$Entry<E>\n element E \"Foo\"\n next LinkedList$Entry<E>\n element E \"Foo\"\n next LinkedList$Entry<E>\n element E \"Foo\"\n next LinkedList$Entry<E>\n previous LinkedList$Entry<E>\n ...\n previous LinkedList$Entry<E>\n previous LinkedList$Entry<E>\n previous LinkedList$Entry<E>\n"
},
{
"answer_id": 39738783,
"author": "Vikalp Veer",
"author_id": 6684431,
"author_profile": "https://Stackoverflow.com/users/6684431",
"pm_score": 1,
"selected": false,
"text": "A -> B -> C -> ...Z\n| | |\n| | [Cat, Cave]\n| [Banana, Blob]\n[Adam, Apple]\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820/"
] |
166,895
|
<p>Is it possible to have a different set of dependencies in a maven pom.xml file for different profiles?</p>
<p>e.g.</p>
<pre><code>mvn -P debug
mvn -P release
</code></pre>
<p>I'd like to pick up a different dependency jar file in one profile that has the same class names and different implementations of the same interfaces.</p>
|
[
{
"answer_id": 167284,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 9,
"selected": true,
"text": "release debug"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
] |
166,897
|
<p>I have a problem similar to the one found here : <a href="https://stackoverflow.com/questions/86531/jsf-selectitem-label-formatting">JSF selectItem label formatting</a>. </p>
<p>What I want to do is to accept a double as a value for my and display it with two decimals. Can this be done in an easy way? </p>
<p>I've tried using but that seems to be applied on the value from the inputText that is sent to the server and not on the initial value in the input field.</p>
<p>My code so far:</p>
<pre><code><h:inputText id="december" value="#{budgetMB.december}" onchange="setDirty()" styleClass="StandardBlack">
<f:convertNumber maxFractionDigits="2" groupingUsed="false" />
</h:inputText>
</code></pre>
<p>EDIT: The above code actually works. I was fooled by JDeveloper that didn't update the jsp page even when I did a explicit rebuild of my project and restarted the embedded OC4J server. However, after a reboot of my computer everything was fine. </p>
|
[
{
"answer_id": 168092,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 5,
"selected": true,
"text": "<h:inputText id=\"text1\" value=\"#{...}\">\n <f:convertNumber pattern=\"#,###,##0.00\"/>\n</h:inputText>\n pattern"
},
{
"answer_id": 168434,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 1,
"selected": false,
"text": "<h:inputText id=\"december\" value=\"#{budgetMB.december}\" styleClass=\"StandardBlack\">\n <f:convertNumber maxFractionDigits=\"2\" groupingUsed=\"false\" />\n <a4j:support event=\"onblur\" reRender=\"december\" />\n</h:inputText>\n"
},
{
"answer_id": 19330604,
"author": "Mosty Mostacho",
"author_id": 268273,
"author_profile": "https://Stackoverflow.com/users/268273",
"pm_score": 0,
"selected": false,
"text": "<f:convertNumber type=\"currency\" />\n locale currencyCode integerOnly currencySymbol pattern"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24828/"
] |
166,941
|
<p>I am trying to get <a href="http://selenium-rc.openqa.org/tutorial.html" rel="nofollow noreferrer">Selenium RC</a> working with Firefox 3 on Linux with PHP/Apache but am experiencing problems. Here's what I've done:</p>
<ul>
<li>I have installed the Firefox Selenium-IDE extension.</li>
<li>On the web server (which in my case is actually the same machine running Firefox), I've started the Selenium server with: java -jar selenium-server.jar -interactive</li>
<li>I have a PHP script as follows:</li>
</ul>
<p>PHP:</p>
<pre><code>require_once 'Testing/Selenium.php';
$browser = new Testing_Selenium("*custom /usr/lib/firefox-3.0.3/firefox", "https://www.example.com");
$browser->start();
</code></pre>
<p>When I run the PHP script, it does launch a new Firefox tab, but <b>I get this error message</b>:</p>
<pre><code>The requested URL /selenium-server/core/RemoteRunner.html was not found on this server.
</code></pre>
<p>I have had more success with Firefox 2 (by using <code>"*firefox"</code> instead of <code>"*custom"</code> but don't want to use that for my current project.</p>
|
[
{
"answer_id": 168964,
"author": "Peter Howe",
"author_id": 24106,
"author_profile": "https://Stackoverflow.com/users/24106",
"pm_score": 5,
"selected": true,
"text": "java -jar selenium-server.jar php -d include_path=\".:/usr/share/php:/usr/share/php/Selenium/PEAR\" test.php require_once 'Testing/Selenium.php';\n\n$oSelenium = new Testing_Selenium(\n \"*custom /usr/lib/firefox-3.0.3/firefox -P Selenium\",\n \"https://www.example.com\");\n$oSelenium->start();\n\n$oSelenium->open(\"/\");\n\nif (!$oSelenium->isElementPresent(\"id=login_button\")) {\n $oSelenium->click(\"logout\");\n $oSelenium->waitForPageToLoad(10000);\n if (!$oSelenium->isElementPresent(\"id=login_button\")) {\n echo \"Failed to log out\\n\\n\";\n exit;\n }\n}\n\n$oSelenium->type(\"login\", \"my_username\");\n$oSelenium->type(\"password\", \"my_password\");\n$oSelenium->click(\"login_button\");\n$oSelenium->waitForPageToLoad(10000);\n\n$oSelenium->click(\"top_nav_campaigns\");\n\n$oSelenium->stop();\n"
},
{
"answer_id": 3192944,
"author": "Deepan Chakravarthy",
"author_id": 271764,
"author_profile": "https://Stackoverflow.com/users/271764",
"pm_score": 1,
"selected": false,
"text": "\n\n1235$Deepan@Newton~/selenium/ide_scripts$\ncat mytest.php\n 'FF on linux',\n 'browser' => '*firefox',\n 'host' => '10.211.55.8',\n 'port' => 4444,\n 'timeout' => 30000,\n ),\n array(\n 'name' => 'FF on windows',\n 'browser' => '*firefox',\n 'host' => '10.211.55.5',\n 'port' => 4444,\n 'timeout' => 30000,\n ),\n */\n array(\n 'name' => 'Google Chrome on windows',\n 'browser' => '*googlechrome',\n 'host' => '10.211.55.5',\n 'port' => 4444,\n 'timeout' => 30000,\n ),\n /*\n array(\n 'name' => 'IE on windows',\n 'browser' => '*iexplore',\n 'host' => '10.211.55.5',\n 'port' => 4444,\n 'timeout' => 30000,\n ),\n array(\n 'name' => 'Safari on MacOS X',\n 'browser' => '*safari',\n 'host' => 'localhost',\n 'port' => 4444,\n 'timeout' => 30000,\n ),\n array(\n 'name' => 'Firefox on MacOS X',\n 'browser' => '*chrome',\n 'host' => 'localhost',\n 'port' => 4444,\n 'timeout' => 30000,\n ),\n */\n array(\n 'name' => 'Google Chrome on MacOS X',\n 'browser' => '*googlechrome',\n 'host' => 'localhost',\n 'port' => 4444,\n 'timeout' => 30000,\n )\n );\n\n protected function setUp()\n {\n //$this->setBrowser(\"*chrome\");\n $this->setBrowserUrl(\"http://www.facebook.com/\");\n }\n\n public function testMyTestCase()\n {\n $this->open(\"/index.php?lh=94730c649368393b6954cb9fc0802e0a&eu=iKjrC7Q2aC-8tcU7PVLilg\");\n $this->type(\"email\", \"myemail@domain.com\");\n $this->type(\"pass\", \"mypassword\");\n $this->click(\"persistent\");\n $this->click(\"//input[@type='submit']\");\n $this->waitForPageToLoad(\"30000\");\n sleep(10);\n $this->open(\"http://apps.facebook.com/myapp/\");\n sleep(4);\n $this->click(\"link=Play\");\n $this->waitForPageToLoad(\"30000\");\n sleep(4);\n $this->click(\"navAccountLink\");\n sleep(4);\n $this->click(\"link=Logout\");\n $this->waitForPageToLoad(\"30000\");\n sleep(4);\n }\n}\n?>\n1332$Deepan@Newton~/selenium/ide_scripts$\nphpunit mytest.php\n\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24106/"
] |
166,944
|
<p>I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.</p>
<p>I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.</p>
<p>Any better ideas? Thanks in advance!</p>
|
[
{
"answer_id": 167200,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 8,
"selected": true,
"text": "preg_replace('/[^a-zA-Z0-9]/', '', $str)\n"
},
{
"answer_id": 11601572,
"author": "Idealmind",
"author_id": 1527663,
"author_profile": "https://Stackoverflow.com/users/1527663",
"pm_score": 4,
"selected": false,
"text": "$command = \"python /path/to/python_script.py 2>&1\";\n$pid = popen( $command,\"r\");\nwhile( !feof( $pid ) )\n{\n echo fread($pid, 256);\n flush();\n ob_flush();\n usleep(100000);\n}\npclose($pid);\n"
},
{
"answer_id": 18921091,
"author": "user",
"author_id": 1892742,
"author_profile": "https://Stackoverflow.com/users/1892742",
"pm_score": 5,
"selected": false,
"text": "hello = \"hello\"\nworld = \"world\"\nprint hello + \" \" + world\n $python = shell_exec(python python.py);\necho $python;\n"
},
{
"answer_id": 37870761,
"author": "Gouled Med",
"author_id": 6108635,
"author_profile": "https://Stackoverflow.com/users/6108635",
"pm_score": -1,
"selected": false,
"text": "exec('your script python.py')\n"
},
{
"answer_id": 40356103,
"author": "Aze",
"author_id": 7098644,
"author_profile": "https://Stackoverflow.com/users/7098644",
"pm_score": 2,
"selected": false,
"text": "<?php\n $item='Everything is awesome!!';\n $tmp = exec(\"py.py $item\");\n echo $tmp;\n?>\n import sys\n\nlist1 = ' '.join(sys.argv[1:])\n\ndef main():\n print list1\n\nif __name__ == '__main__':\n main()\n"
},
{
"answer_id": 45592623,
"author": "Bob3411",
"author_id": 7086083,
"author_profile": "https://Stackoverflow.com/users/7086083",
"pm_score": 0,
"selected": false,
"text": "/home/user/mypython/bin/python ./cgi-bin/test.py"
},
{
"answer_id": 53071179,
"author": "SMshrimant",
"author_id": 8355510,
"author_profile": "https://Stackoverflow.com/users/8355510",
"pm_score": 1,
"selected": false,
"text": "<html>\n <body>\n <head>\n <title>\n run\n </title>\n </head>\n\n <form method=\"post\">\n\n <input type=\"submit\" value=\"GO\" name=\"GO\">\n </form>\n </body>\n</html>\n\n<?php\n if(isset($_POST['GO']))\n {\n shell_exec(\"python /var/www/html/lab/mkdir.py\");\n echo\"success\";\n }\n?>\n #!/usr/bin/env python \nimport os \nos.makedirs(\"thisfolder\");\n"
},
{
"answer_id": 65859369,
"author": "Raeen",
"author_id": 15025468,
"author_profile": "https://Stackoverflow.com/users/15025468",
"pm_score": 0,
"selected": false,
"text": "<?php\n require_once \"vendor/autoload.php\";\n\n use app\\core\\App;\n\n $app = new App();\n $python = $app->python;\n $output = $python->set(your python path)->send(data..)->gen();\n var_dump($ouput);\n import include.library.phpy as phpy\nprint(phpy.get_data(number of data , first = 1 , two =2 ...))\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2999/"
] |
166,996
|
<p>I have a table class that creates modifies a table of items. I want to display those items in a JTable using a table model. To me table model belongs to my GUI package but table needs table model in order to fire changes and table model needs table class in order to display it so I can not separate the two. if you need to do this what would be the class structure you use? or do I have a flow in my thinking and they belong in the same package?</p>
|
[
{
"answer_id": 167945,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 2,
"selected": false,
"text": "TableModel AbstractTableModel getRowCount getColumnCount getValueAt AbstractTableModel.fireTableDataChanged DefaultTableModel JTable"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
167,003
|
<p>I generally stay away from <code>regular expressions</code> because I seldom find a good use for them. But in this case, I don't think I have choice. </p>
<p>I need a regex for the following situation. I will be looking at three character strings. It will be a match if the first character is <code>1-9 or the letters o,n,d (lower or upper)</code> AND the second character is <code>1,2 or 3</code> and the third character is <code>0-9</code>.</p>
<p>Can anybody help me out?</p>
|
[
{
"answer_id": 167005,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": false,
"text": "[1-9ondOND][123][0-9]\n ^ $ o n d O N D re.match('[1-9ond][123][0-9]', inputstring, re.IGNORECASE)\n re.match ^"
},
{
"answer_id": 167010,
"author": "codebunny",
"author_id": 13667,
"author_profile": "https://Stackoverflow.com/users/13667",
"pm_score": 2,
"selected": false,
"text": "/^[1-9ondOND][1-3][0-9]$/ ^ $"
},
{
"answer_id": 167023,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": -1,
"selected": false,
"text": "^(?:[1-9]|[ond])[1-3][0-9]$\n /^(?:[1-9]|[ond])[1-3][0-9]$/\n"
},
{
"answer_id": 167047,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 4,
"selected": true,
"text": "\n^[1-9ondOND][123][0-9]$\n"
},
{
"answer_id": 167051,
"author": "Greg",
"author_id": 13009,
"author_profile": "https://Stackoverflow.com/users/13009",
"pm_score": 2,
"selected": false,
"text": "[1-9ond][123][0-9]\n"
},
{
"answer_id": 26636470,
"author": "Suganthan Madhavan Pillai",
"author_id": 2534236,
"author_profile": "https://Stackoverflow.com/users/2534236",
"pm_score": 0,
"selected": false,
"text": "([1-9]|(?i)(o|n|d))[123][\\d]\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] |
167,004
|
<p>I am attempting to set up an nmake makefile to export our balsamiq mockup files to png files automatically, but I'm afraid I can't make heads nor tails of how to make a generic rule for doing so, without explicitly listing all the files I want exported.</p>
<p><a href="http://www.balsamiq.com/blog/?p=231" rel="nofollow noreferrer">This page</a> details the command line syntax for exporting the files, and <a href="http://msdn.microsoft.com/en-us/library/ms925728.aspx" rel="nofollow noreferrer">this page</a> contains an example which looks like it contains a generic rule for .obj files to .exe files.</p>
<p>The makefile I have tried so far looks like this:</p>
<pre><code>.bmml.png:
"C:\Program Files\Balsamiq Mockups\Balsamiq Mockups.exe" export $< $@
</code></pre>
<p>But this doesn't work.</p>
<p>If I simply run nmake (with some outdated png files), nmake just does this:</p>
<pre><code>[C:\Temp] :nmake
Microsoft (R) Program Maintenance Utility Version 9.00.30729.01
Copyright (C) Microsoft Corporation. All rights reserved.
[C:\Temp] :
</code></pre>
<p>If I ask it to build one specific file, it does this:</p>
<pre><code>[C:\Temp] :nmake "TestFile.png"
Microsoft (R) Program Maintenance Utility Version 9.00.30729.01
Copyright (C) Microsoft Corporation. All rights reserved.
NMAKE : fatal error U1073: don't know how to make '"TestFile.png"'
Stop.
[C:\Temp] :
</code></pre>
<p>Any nmake gurus out there that can set me straight?</p>
<p>An example makefile which simply makes .dat files from .txt files by copying them, to experiment with, looks like this:</p>
<pre><code>.txt.dat:
copy $< $@
</code></pre>
<p>this does nothing as well, so clearly I'm not understanding how such generic rules work. Do I need to specify a goal above that somehow lists the files I want?</p>
|
[
{
"answer_id": 631724,
"author": "David Pokluda",
"author_id": 223,
"author_profile": "https://Stackoverflow.com/users/223",
"pm_score": 0,
"selected": false,
"text": "export : *.bmml\n \"C:\\Program Files\\Balsamiq Mockups\\Balsamiq Mockups.exe\" export $** $(**B).png\n nmake /A\n export : *.txt\n copy $** $(**B).dat\n nmake /A"
},
{
"answer_id": 640880,
"author": "Eric Melski",
"author_id": 77345,
"author_profile": "https://Stackoverflow.com/users/77345",
"pm_score": 5,
"selected": true,
"text": ".SUFFIXES: .bmml .png\n.bmml.png:\n @echo Building $@ from $<\n all: *.bmml\n $(MAKE) $(**:.bmml=.png)\n *.bmml all .bmml .png .SUFFIXES: .bmml .png\nall: *.bmml\n @echo Converting $(**) to .png...\n @$(MAKE) $(**:.bmml=.png)\n\n.bmml.png:\n @echo Building $@ from $<\n Converting Test1.bmml Test2.bmml to .png...\nBuilding Test1.png from Test1.bmml\nBuilding Test2.png from Test2.bmml\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
167,007
|
<p>As a new Eclipse user, I am constantly annoyed by how long it takes compiler error messages to display. This is mostly only a problem for long errors that don't fit in the status bar or the "Problems" tab. But I get enough long errors in Java—especially with generics—that this is a nagging issue. (Note: The correct answer to this question is not "get better at using generics." ;-) </p>
<p>The ways I have found to display an error are:</p>
<ol>
<li>Press <code>Ctrl+.</code> or execute the command "Next Annotation". The next error is highlighted and its associated message appears in the status bar (if it is short enough). The error is also highlighted in the "Problems" tab, if it is open, but the tab is not automatically brought to the top.</li>
<li>Hover the mouse over the error. After a noticeable lag, the error message appears as a "tool tip", along with any associated "Quick Fixes."</li>
<li>Hover the mouse over the error icon on the left side of the editing pane. After a noticeable lag, all of the error messages for that line appear as a "tool tip." Clicking on the icon brings up "Quick Fixes."</li>
</ol>
<p>What I would like is for <code>Ctrl+.</code> to automatically and instantly bring up the complete error message (I don't care where). Is this a configurable option?</p>
<p>[UPDATE] @asterite's "<code>Ctrl+. F2</code>" is almost it. How do I make "Next Annotation, then Show Tooltip Description" a macro bound to a single keystroke?</p>
|
[
{
"answer_id": 167571,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 0,
"selected": false,
"text": "Ctrl+1"
},
{
"answer_id": 168913,
"author": "Craig Angus",
"author_id": 15352,
"author_profile": "https://Stackoverflow.com/users/15352",
"pm_score": 0,
"selected": false,
"text": "Window>Preferences>Java>>Editor>ContentAssist\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
167,014
|
<p>Our team (5-10 developers) plans to <strong>adopt Subversion</strong> for our .NET (Visual Studio) projects/solutions (VisualSVN Server, TortoiseSVN / VisualSVN).</p>
<p>What is the best way to <strong>organize a new repository tree</strong>? Is it okay to use <em>one big repository</em> or is it better to create <em>different repositories</em> for every solution / product line etc.?</p>
<p>Our projects can be categorized this way (example):</p>
<ul>
<li>Main Product Line
<ul>
<li>Main Web App
<ul>
<li>Library 1</li>
<li>Library 2</li>
<li>...</li>
</ul></li>
<li>Windows Client</li>
<li>Another Windows Client </li>
<li>Windows Service </li>
</ul></li>
<li>Tools
<ul>
<li>Tool A</li>
<li>Tool B</li>
</ul></li>
<li>Product Line 2
<ul>
<li>Software 1</li>
<li>Software 2</li>
</ul></li>
<li>Product Line 3
<ul>
<li>App 1</li>
<li>App 2</li>
</ul></li>
</ul>
|
[
{
"answer_id": 174883,
"author": "Frew Schmidt",
"author_id": 12448,
"author_profile": "https://Stackoverflow.com/users/12448",
"pm_score": 1,
"selected": false,
"text": "[general]\nanon-access = none\nauth-access = write\npassword-db = ../../conf/passwd\nauthz-db = ../../conf/authz\n [groups]\nAOS = nathan,mark\n\n[AOS:/]\n@AOS = rw\nfrew = rw\n [users]\nfrew = password\nnathan = awesome\nmark = station\n"
},
{
"answer_id": 22235758,
"author": "user2784896",
"author_id": 2784896,
"author_profile": "https://Stackoverflow.com/users/2784896",
"pm_score": 0,
"selected": false,
"text": "Projects\n Project Name\n trunk\n branches\n tags\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6461/"
] |
167,027
|
<p>I have a need to display many numerical values in columns. These values need to be easily editable so I cannot just display them in a table. I am using textboxes to display them. Is there a way for me to right-justify the text displayed in a textbox? It would also be nice if when the user is entering data for it to start displaying what they type from the right.</p>
|
[
{
"answer_id": 167037,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 8,
"selected": true,
"text": "input {\n text-align:right;\n}\n <html>\n <head>\n <title>Blah</title>\n <style type=\"text/css\">\n input { text-align:right; }\n </style>\n </head>\n <body>\n <input type=\"text\" value=\"2\">\n </body>\n</html>\n"
},
{
"answer_id": 167038,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 4,
"selected": false,
"text": "<input type=\"text\" style=\"text-align: right\"/>\n <style>\n .rightJustified {\n text-align: right;\n }\n</style>\n <input type=\"text\" class=\"rightJustified\"/>\n"
},
{
"answer_id": 167043,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": false,
"text": "style=\"text-align: right\""
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] |
167,031
|
<p>Does anyone know the API call I can use to change the keyboard layout on a windows machine to Dvorak? Doing it through the UI is easy but I'd like to have a script that I can run on new VM's to automate the process. </p>
|
[
{
"answer_id": 167052,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 3,
"selected": false,
"text": "[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout]\n\"ScanCode Map\"=hex:00,00,00,00,00,00,00,00,22,00,00,00,2d,00,30,00,24,00,2e,00,\\\n11,00,33,00,33,00,11,00,12,00,20,00,34,00,12,00,1b,00,0d,00,0d,00,1b,00,16,\\\n00,21,00,17,00,22,00,20,00,23,00,1a,00,0c,00,2e,00,17,00,23,00,24,00,14,00,\\\n25,00,31,00,26,00,35,00,1a,00,30,00,31,00,13,00,18,00,26,00,19,00,2f,00,34,\\\n00,28,00,10,00,0c,00,28,00,19,00,13,00,18,00,1f,00,1f,00,27,00,2c,00,35,00,\\\n15,00,14,00,22,00,16,00,25,00,2f,00,10,00,2d,00,21,00,15,00,27,00,2c,00,00,\\\n00,00,00\n [HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout]\n\"ScanCode Map\"=hex:00,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00\n"
},
{
"answer_id": 11784116,
"author": "Bobulous",
"author_id": 1515834,
"author_profile": "https://Stackoverflow.com/users/1515834",
"pm_score": 5,
"selected": true,
"text": "intlcfg.exe -inputlocale:0409:00010409\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23283/"
] |
167,053
|
<p>I'm trying to understand the best way to get the connection to my databases.</p>
<p>At the moment I've got a method which parses the URL (depending on the URL called the application has to connect to a different database, like customer1.example.com will connect to the customer1 database) and calls </p>
<pre><code>ActiveRecord::Base.establish_connection(conn_string)
</code></pre>
<p>where conn_string contains the name of the database.</p>
<p>This method (set_db) is called with a</p>
<pre><code>before_filter :set_db
</code></pre>
<p>in my Application controller, so basically for each request I get, the URL is parsed and the application try to do an establish_connection. </p>
<p>I was wondering if I can have a connection pool somewhere....do you have any suggestion about that? Is it better to have a Singleton which keep all the connections made and gives back the right one?</p>
<p>Thanks!
Roberto</p>
|
[
{
"answer_id": 167265,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 1,
"selected": false,
"text": "class xx < ActiveRecord.base\n\ndef self.table_name\n \"otherdatabase.table\"\nend\n"
},
{
"answer_id": 170708,
"author": "Priit",
"author_id": 22964,
"author_profile": "https://Stackoverflow.com/users/22964",
"pm_score": 0,
"selected": false,
"text": "RewriteMap accounts prg:domain_mapper.rb\nRewriteMap lowercase int:tolower\n\nRewriteCond %{HTTP_HOST} ^(.*)$\nRewriteCond ${accounts:${lowercase:%1}} ^(.+)$\nRewriteRule . - [E=ACCOUNT:%1]\nRequestHeader set Customer-Key %{ACCOUNT}e\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22083/"
] |
167,067
|
<p>Given a SCHEMA for implementing tags</p>
<p>ITEM
ItemId, ItemContent</p>
<p>TAG
TagId, TagName</p>
<p>ITEM_TAG
ItemId, TagId</p>
<p>What is the best way to limit the number of ITEMS to return when selecting with tags?</p>
<pre><code>SELECT i.ItemContent, t.TagName FROM item i
INNER JOIN ItemTag it ON i.id = it.ItemId
INNER JOIN tag t ON t.id = it.TagId
</code></pre>
<p>is of course the easiest way to get them all back, but using a limit clause breaks down, because you get an duplicate of all the items for each tag, which counts toward the number of rows in LIMIT.</p>
|
[
{
"answer_id": 167156,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 1,
"selected": false,
"text": "select i.ItemContent, t.TagName from (SELECT ItemId, ItemContent FROM item limit 10) i\nINNER JOIN ItemTag it ON i.ItemId = it.ItemId --You will miss tagless items here!\nINNER JOIN tag t ON t.id = it.TagId\n"
},
{
"answer_id": 167573,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "SELECT i.ItemContent\nFROM item AS i\nWHERE i.id IN (\n SELECT it.ItemId\n FROM ItemTag AS it\n INNER JOIN tag AS t ON (t.id = it.TagId)\n WHERE t.TagName IN ('mysql', 'database', 'tags', 'tagging')\n);\n"
},
{
"answer_id": 167600,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "SELECT i.ItemContent, GROUP_CONCAT(t.TagName ORDER BY t.TagName) AS TagList\nFROM item AS i \n INNER JOIN ItemTag AS it ON i.id = it.ItemId \n INNER JOIN tag AS t ON t.id = it.TagId\nGROUP BY i.ItemId;\n"
},
{
"answer_id": 167653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\nSELECT DISTINCT TagID, TagName FROM ((TAG T\nINNER JOIN ITEM_TAG I_T ON T.TagID = I_T.TagID)\nINNER JOIN ITEM I ON I_T.ItemID = I.ItemID)\nGROUP BY TagID, TagName"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22277/"
] |
167,074
|
<p>I changed the MembershipProvider in my ASP.net MVC website, and now the stylesheet for the login page isn't referenced correctly. Below is a copy of the forms tag in my web.config if that could be the reason. It looks identical though to the one generated by a new project with the exception of the name and timeout attribute.</p>
<pre><code><authentication mode="Forms">
<forms loginUrl="~/Account/Login" name=".ADAuthCookie" timeout="10" />
</authentication>
</code></pre>
<p>When I visit the page now, the link tag for the CSS looks like this:</p>
<pre><code><link href="../Content/Site.css" rel="stylesheet" type="text/css" />
</code></pre>
<p>When it <em>should</em> look like this:</p>
<pre><code><link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</code></pre>
|
[
{
"answer_id": 167264,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 1,
"selected": false,
"text": "<link href=\"<%= ResolveClientUrl(\"../../content/Site.css\") %> rel=\"stylesheet\" type=\"text/css\" />\n"
},
{
"answer_id": 179678,
"author": "Jared",
"author_id": 24841,
"author_profile": "https://Stackoverflow.com/users/24841",
"pm_score": 1,
"selected": true,
"text": "<authorization>\n <deny users=\"?\" />\n <allow users=\"*\" />\n</authorization>\n <location path=\"Content\">\n <system.web>\n <authorization>\n <allow users=\"*\" />\n </authorization>\n </system.web>\n</location>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24841/"
] |
167,084
|
<p>What is the the best of detecting and later altering the screen resolution and multiple desktop within .net</p>
<p>I have a small app that while runs at work on my multiple monitor/high(ish) resolution however what I want to be able to detect is the users primary monitor and set the application to that (main objective) and adjust the resolution to ensure the application fits(more for my own curiosity) </p>
|
[
{
"answer_id": 167102,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 3,
"selected": true,
"text": " System.Windows.Forms.Screen.PrimaryScreen\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
167,088
|
<p>I'm creating a webservice, and I want to name it appropriately.</p>
<p>Right now my service is named Service as per the /App_Code/Service.cs</p>
<p>Should I rename it to something like: <em>com.example.MyWebService.cs</em>?</p>
<p>How do I get around the class file not excepting '.' in the file name?</p>
|
[
{
"answer_id": 167123,
"author": "Sir Code-A-Lot",
"author_id": 13148,
"author_profile": "https://Stackoverflow.com/users/13148",
"pm_score": 0,
"selected": false,
"text": "namespace Com.Example\n{\n public class MyWebService\n {\n // class contents\n }\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
167,096
|
<p>Is it safe to assume that two itterations over the same collection will return the objects in the same order? Obviously, it is assumed that the collection has not otherwise been changed.</p>
|
[
{
"answer_id": 167130,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "IEnumerable foreach (int i in new Shuffler(1, 2, 3, 4, 5, 6, 7, 8, 9))\n Console.WriteLine(i);\n"
},
{
"answer_id": 167145,
"author": "mancaus",
"author_id": 13797,
"author_profile": "https://Stackoverflow.com/users/13797",
"pm_score": 3,
"selected": false,
"text": "List<T> Dictionary<K,V>"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18978/"
] |
167,106
|
<p>In there an easy way to do this in PHP. I want to make sure that only web requests from certain countries are able to access my website.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 28089465,
"author": "P. Bos",
"author_id": 4482631,
"author_profile": "https://Stackoverflow.com/users/4482631",
"pm_score": 2,
"selected": false,
"text": "if (!in_array(substr($country, 0, 2), $allowed_countries)) {\n if(!in_array($country, $allowed_countries)) {\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
167,109
|
<p>Consider these two C++ header cases:</p>
<p>Case 1:</p>
<pre><code>class Test {
public:
static int TEST_DATA[];
};
int Test::TEST_DATA[] = { 1, 2, 3, 4 };
</code></pre>
<p>Case 2:</p>
<pre><code>class Test {
public:
static int const TEST_DATA[];
};
int const Test::TEST_DATA[] = { 1, 2, 3, 4 };
</code></pre>
<p>Is const in the latter case only for self-imposed compile-time checks or does it affect shared library layout on Mac/Linux/Windows?</p>
<p><em>Update:</em> According to the answers, the compiler <em>may</em> put the const stuff on a read-only page. <em>Does</em> Visual C++ on Windows or GCC
on Mac or Linux actually place const data on a read-only page? Perhaps I tested the wrong way but on Mac on Intel, the elements of the const version seemed writable.</p>
|
[
{
"answer_id": 167307,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 0,
"selected": false,
"text": "struct Test\n{\n static int const TEST;\n};\nint const Test::TEST = 7;\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18721/"
] |
167,120
|
<p>This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this:</p>
<pre><code>a = {1:'', 2:'', 3:'', 4:''}
exclusion = [3, 4, 5]
# have to build up a new list or the iteration breaks
toRemove = []
for var in a.iterkeys():
if var in exclusion:
toRemove.append(var)
for var in toRemove:
del a[var]
</code></pre>
<p>This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict.</p>
<p>This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.</p>
|
[
{
"answer_id": 167134,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": true,
"text": "for key in exclusion:\n a.pop(key, None)\n None key"
},
{
"answer_id": 167158,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 2,
"selected": false,
"text": "keys iterkeys"
},
{
"answer_id": 167167,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 2,
"selected": false,
"text": "a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion)\n"
},
{
"answer_id": 167335,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "exclusion = set([3, 4, 5])\n\nfor key in exclusion.intersection(a):\n del a[key]\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] |
167,129
|
<p>What is the functional programming approach to convert an <code>IEnumerable<string></code> to a delimited string? I know I can use a loop, but I'm trying to wrap my head around functional programming. </p>
<p>Here's my example: </p>
<pre><code>var selectedValues =
from ListItem item in checkboxList.Items
where item.Selected
select item.Value;
var delimitedString = ??
</code></pre>
<p>.. or could I do this in just the first var assignment (append each result to the previous)?</p>
|
[
{
"answer_id": 167141,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 5,
"selected": false,
"text": "string.Join(\", \", string[] enumerable)\n"
},
{
"answer_id": 167142,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 2,
"selected": false,
"text": "var delimitedString = string.Join(\",\", checkboxList.Items.Where(i => i.Selected).Select(i => i.Value).ToArray());\n"
},
{
"answer_id": 167175,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": " StringBuilder sb = new StringBuilder();\n foreach(ListViewItem item in checkboxList.SelectedItems) {\n if(sb.Length > 0) sb.Append(',');\n sb.Append(item.Text);\n }\n string s = sb.ToString();\n"
},
{
"answer_id": 167178,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 5,
"selected": true,
"text": "var delimitedString = selectedValues.Aggregate((x,y) => x + \", \" + y);\n"
},
{
"answer_id": 167188,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 1,
"selected": false,
"text": "\nstring[] toDelimit = CallSomeFunction();\nreturn toDelimit.Aggregate((x, y) => x + \",\" + y);\n"
},
{
"answer_id": 167191,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 2,
"selected": false,
"text": "items.Aggregate((accum, elem) => accum + \", \" + elem);\n"
},
{
"answer_id": 167299,
"author": "Danko Durbić",
"author_id": 19241,
"author_profile": "https://Stackoverflow.com/users/19241",
"pm_score": 5,
"selected": false,
"text": "StringBuilder Append() StringBuilder return list.Aggregate( new StringBuilder(), \n ( sb, s ) => \n ( sb.Length == 0 ? sb : sb.Append( ',' ) ).Append( s ) );\n"
},
{
"answer_id": 13726453,
"author": "UNeverNo",
"author_id": 1051614,
"author_profile": "https://Stackoverflow.com/users/1051614",
"pm_score": 0,
"selected": false,
"text": "var selectedValues = String.Join(\",\", (from ListItem item in checkboxList.Items where item.Selected select item.Value).ToArray());\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10693/"
] |
167,152
|
<p>How can you get MSSQL server to accept Unicode data by default into a VARCHAR or NVARCHAR column?</p>
<p>I know that you can do it by placing a N in front of the string to be placed in the field but to by quite honest this seems a bit archaic in 2008 and particuarily with using SQL Server 2005.</p>
|
[
{
"answer_id": 167290,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 3,
"selected": true,
"text": "N N'Unicode string'\n'ANSI string'\n N N"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6244/"
] |
167,165
|
<p>I've been asked to maintain a large C++ codebase full of memory leaks. While poking around, I found out that we have a lot of buffer overflows that lead to the leaks (how it got this bad, I don't ever want to know). </p>
<p>I've decided to removing the buffer overflows first, starting with the dangerous functions. What C/C++ functions that are most often used incorrectly and can lead to buffer overflow?</p>
<p>For compiler and/or tools used to help look for buffer overrun, I've <a href="https://stackoverflow.com/questions/167199/what-cc-tools-can-check-for-buffer-overflows">created another question that deals with this</a></p>
|
[
{
"answer_id": 167181,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "uint32_t foo[3];\nfoo[3] = WALKED_OFF_END_OF_ARRAY;\n"
},
{
"answer_id": 167182,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 4,
"selected": false,
"text": "int foo[3];\nfoo[3] = WALKED_OFF_END_OF_ARRAY;\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
] |
167,193
|
<p>I have 2 tables:</p>
<pre><code>A
s_id(key) name cli type
B
sa_id(key) s_id user pwd
</code></pre>
<p>So in Jpa
I have:</p>
<pre><code>@Entity
class A...{
@OneToMany(fetch=FetchType.EAGER)
@JoinTable( name="A_B",
joinColumns={@JoinColumn(name="a_id", table="a",unique=false)},
inverseJoinColumns={@JoinColumn(name="b_id", table="b", unique=true)} )
Collection<B> getB(){...}
}
</code></pre>
<p>class b is just a basic entity class with no reference to A.</p>
<p>Hopefully that is clear. My question is: Do I really need a join table to do such a simple join? Can't this be done with a simple joincolumn or something?</p>
|
[
{
"answer_id": 218612,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": true,
"text": "@Entity class A...{ \n@OneToMany(fetch=FetchType.EAGER) \nCollection getB(){...} }\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22763/"
] |
167,206
|
<p>Is there a PHP module that you can use to programmatically read a torrent to find out information about it, Seeders for instance?</p>
|
[
{
"answer_id": 601710,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 3,
"selected": false,
"text": "hash_info tracker_url"
},
{
"answer_id": 601765,
"author": "Svish",
"author_id": 39321,
"author_profile": "https://Stackoverflow.com/users/39321",
"pm_score": 4,
"selected": false,
"text": "function bdecode($str) {\n $pos = 0;\n return bdecode_r($str, $pos);\n}\n\nfunction bdecode_r($str, &$pos) {\n $strlen = strlen($str);\n if (($pos < 0) || ($pos >= $strlen)) {\n return null;\n }\n else if ($str{$pos} == 'i') {\n $pos++;\n $numlen = strspn($str, '-0123456789', $pos);\n $spos = $pos;\n $pos += $numlen;\n if (($pos >= $strlen) || ($str{$pos} != 'e')) {\n return null;\n }\n else {\n $pos++;\n return intval(substr($str, $spos, $numlen));\n }\n }\n else if ($str{$pos} == 'd') {\n $pos++;\n $ret = array();\n while ($pos < $strlen) {\n if ($str{$pos} == 'e') {\n $pos++;\n return $ret;\n }\n else {\n $key = bdecode_r($str, $pos);\n if ($key == null) {\n return null;\n }\n else {\n $val = bdecode_r($str, $pos);\n if ($val == null) {\n return null;\n }\n else if (!is_array($key)) {\n $ret[$key] = $val;\n }\n }\n }\n }\n return null;\n }\n else if ($str{$pos} == 'l') {\n $pos++;\n $ret = array();\n while ($pos < $strlen) {\n if ($str{$pos} == 'e') {\n $pos++;\n return $ret;\n }\n else {\n $val = bdecode_r($str, $pos);\n if ($val == null) {\n return null;\n }\n else {\n $ret[] = $val;\n }\n }\n }\n return null;\n }\n else {\n $numlen = strspn($str, '0123456789', $pos);\n $spos = $pos;\n $pos += $numlen;\n if (($pos >= $strlen) || ($str{$pos} != ':')) {\n return null;\n }\n else {\n $vallen = intval(substr($str, $spos, $numlen));\n $pos++;\n $val = substr($str, $pos, $vallen);\n if (strlen($val) != $vallen) {\n return null;\n }\n else {\n $pos += $vallen;\n return $val;\n }\n }\n }\n}\n\nfunction bencode($var) {\n if (is_int($var)) {\n return 'i' . $var . 'e';\n }\n else if (is_array($var)) {\n if (count($var) == 0) {\n return 'de';\n }\n else {\n $assoc = false;\n foreach ($var as $key => $val) {\n if (!is_int($key)) {\n $assoc = true;\n break;\n }\n }\n if ($assoc) {\n ksort($var, SORT_REGULAR);\n $ret = 'd';\n foreach ($var as $key => $val) {\n $ret .= bencode($key) . bencode($val);\n }\n return $ret . 'e';\n }\n else {\n $ret = 'l';\n foreach ($var as $val) {\n $ret .= bencode($val);\n }\n return $ret . 'e';\n }\n }\n }\n else {\n return strlen($var) . ':' . $var;\n }\n}\n # Read a file\n$content = file_get_contents(\"file.torrent\");\n$content_d = bdecode($content);\n\n# Check if bdecode succeeded\nif(empty($content_d)) exit('Something is wrong with the torrent. BDecode failed.');\n\n# Calculate info_hash\n$info_hash = sha1(bencode($content_d['info']), true);\n\n# Calculate length\n$length = 0;\nfunction add_length($value, $key)\n{\n global $length;\n if($key == 'length') $length += $value;\n}\narray_walk_recursive($content_d, 'add_length');\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
167,224
|
<p>I have a variable of type Number, and i like to obtain the sign (if is '-' i like to have -1 and if '+' i like to have 1). So, i made this:</p>
<pre><code>var sign = Math.abs(n) / n;
</code></pre>
<p>But, there is any other way? Better than this?</p>
|
[
{
"answer_id": 167255,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 5,
"selected": true,
"text": "var sign = n < 0 ? -1 : 1;\n"
},
{
"answer_id": 167258,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 2,
"selected": false,
"text": "var sign = (n>=0)?1:-1;\n"
},
{
"answer_id": 167270,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 3,
"selected": false,
"text": "function sign(num) {\n if(num > 0) {\n return 1;\n } else if(num < 0) {\n return -1;\n } else {\n return 0;\n }\n}\n function sign(num) {\n return (num > 0) ? 1 : ((num < 0) ? -1 : 0);\n}\n"
},
{
"answer_id": 591768,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "var sign = 1 + 2*(n >> 31);\n"
},
{
"answer_id": 591798,
"author": "Chetan S",
"author_id": 31284,
"author_profile": "https://Stackoverflow.com/users/31284",
"pm_score": 0,
"selected": false,
"text": "function getSign(number:int):int {\n var tmp:String = new String(number);\n if (tmp.indexOf(0) == '-') {\n return -1;\n }\n return 1;\n}\n"
},
{
"answer_id": 12235161,
"author": "Dimmduh",
"author_id": 601040,
"author_profile": "https://Stackoverflow.com/users/601040",
"pm_score": 1,
"selected": false,
"text": "return (number < 0 && -1) || 1;\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
] |
167,232
|
<p>Is there a way to configure a Visual Studio 2005 Web Deployment Project to install an application into a named Application Pool rather than the default app pool for a given web site?</p>
|
[
{
"answer_id": 168362,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 5,
"selected": true,
"text": "Private Sub assignApplicationPool(ByVal WebSite As String, ByVal Vdir As String, ByVal appPool As String)\n Try\n Dim IISVdir As New DirectoryEntry(String.Format(\"IIS://{0}/W3SVC/1/Root/{1}\", WebSite, Vdir))\n IISVdir.Properties.Item(\"AppPoolId\").Item(0) = appPool\n IISVdir.CommitChanges()\n Catch ex As Exception\n Throw ex\n End Try\n End Sub\n\n Private strServer As String = \"localhost\"\n Private strRootSubPath As String = \"/W3SVC/1/Root\"\n Private strSchema As String = \"IIsWebVirtualDir\"\n Public Overrides Sub Install(ByVal stateSaver As IDictionary)\n MyBase.Install(stateSaver)\n Try\n Dim webAppName As String = MyBase.Context.Parameters.Item(\"TARGETVDIR\").ToString\n Dim vdirName As String = MyBase.Context.Parameters.Item(\"COMMONVDIR\").ToString\n Me.assignApplicationPool(Me.strServer, MyBase.Context.Parameters.Item(\"TARGETVDIR\").ToString, MyBase.Context.Parameters.Item(\"APPPOOL\").ToString)\n Catch ex As Exception\n Throw ex\n End Try\n End Sub\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7872/"
] |
167,233
|
<pre><code>rsync -auve ssh --backup --suffix='2008-10-03-1514539' --backup-dir='/tmp/' module.pm root@web1:/path/to/module.pm
</code></pre>
<p>I run this command without the --backup-dir option and when it copies the file over, it creates a backup with a current timestamp. When I include the --backup-dir option, it makes the backup into the /tmp/ directory but never attaches my suffix. </p>
<p>There is nothing in the <a href="http://samba.anu.edu.au/ftp/rsync/rsync.html" rel="nofollow noreferrer">manual</a> to suggest that you can't use both these options together. I've played around with the order also and nothing seems to fix it.</p>
<p>Does anyone have a solution to this?</p>
|
[
{
"answer_id": 10918859,
"author": "Paperghost",
"author_id": 1330572,
"author_profile": "https://Stackoverflow.com/users/1330572",
"pm_score": 1,
"selected": false,
"text": "# Backup\nmkdir -p /tmp/`date +\\%Y-\\%m-\\%d`-`date +\\%A`/\nrsync -avz /tmp/`date --date=yesterday +\\%Y-\\%m-\\%d`-`date --date=yesterday +\\%A`/ /tmp/`date +\\%Y-\\%m-\\%d`-`date +\\%A`/\nrsync -avz -e ssh root@web1:/path/to/module.pm /tmp/`date +\\%Y-\\%m-\\%d`-`date +\\%A`/\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404/"
] |
167,238
|
<p>The question is not how to tell in a oneliner. If you're writing the code in a one-liner, <em>you know</em> you are. But how does a module, included by <code>-MMy::Module::Name</code> know that it all started from a oneliner. </p>
<p>This is mine. It's non-portable though and relies on UNIX standard commands (although, it can be made portable more or less.)</p>
<pre><code>my $process_info = `ps $$ | tail -1`;
my $is_oneliner
= $process_info =~ m/perl.*?\s+-[^\P{IsLower}e]*e[^\P{IsLower}e]*\s+/m
;
</code></pre>
<p>And if you have a snazzier regex, feel free to improve upon mine. </p>
<hr>
<p>A couple of people have asked why I would want to do this. brian correctly guessed that I wanted to change export behavior based on whether it's a script, which we can assume has had some amount of design, or whether it's a oneliner where the user is trying to do as much as possible in a single command line. </p>
<p>This sounds bad, because there's this credo that exporters should respect other packages--sometimes known as "<code>@EXPORT</code> is <em>EVIL</em>!" But it seems to me that it's a foolish consistency when applied to oneliners. After all perl itself goes out of it's way to violate the structure of its language and give you easy loops if you ask for them on the command line, I simply want to extend that idea for my operational/business domain. I even want to apply source filters (<em>gasp!</em>) if it helps. </p>
<p>But this question also suggests that I might want to be a good citizen of Perl as well, because I only to break the community guidelines in certain cases. It is quite awesome to be able to create major business-level actions just by changing the command line in a batch scheduler rather than writing a whole new module. The test cycle is much compressed. </p>
|
[
{
"answer_id": 167267,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 6,
"selected": true,
"text": "$0 \"-e\" -e"
},
{
"answer_id": 169726,
"author": "Eric Wilhelm",
"author_id": 11580,
"author_profile": "https://Stackoverflow.com/users/11580",
"pm_score": 1,
"selected": false,
"text": "import() caller() 0 -M 0"
},
{
"answer_id": 171482,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 1,
"selected": false,
"text": "package MMN;\nuse My::Module::Name '/./';\nuse Exporter ();\n@ISA = 'Exporter';\n@EXPORT = @My::Module::Name::EXPORT_OK;\n1;\n perl -MMy::Module::Name=/./ -e ...\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11289/"
] |
167,247
|
<p>How do I stop a function/procedure in a superclass from been overridden in a subclass in Delphi (2007)?</p>
<p>I want to mark it so it can not be altered, I believe there is a final keyword but can not for the life of me find the documentation for it, so I am not 100% sure that's what I need.</p>
|
[
{
"answer_id": 167295,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 5,
"selected": true,
"text": "final type\n TSomeClass = class\n protected\n procedure SomeVirtualMethod; virtual;\n end;\n\n TOtherClass = class(TSomeClass)\n protected\n procedure SomeVirtualMethod; override; final;\n end;\n"
},
{
"answer_id": 167328,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 3,
"selected": false,
"text": "type\n TDeriv1 = class (TBase)\n procedure A; override; final;\n end;\n\n TDeriv2 = class (TDeriv1)\n procedure A; override; // error: \"cannot override a final method\"\n end;\n [Pascal Error] Unit1.pas(11): E2352 Cannot override a final method\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
] |
167,254
|
<p>Is there a better way to watch for new entries in a table besides selecting from it every n ticks of time or something like that?</p>
<p>I have a table that an external program updates very often, and clients can watch for this new data as it arrive, how can I make that without having to set a fixed period of repeatable select statements?</p>
|
[
{
"answer_id": 167423,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 3,
"selected": false,
"text": "add column Last_Modified TIMESTAMP ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP \n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623/"
] |
167,262
|
<p>I suppose this is a strange question to the huge majority of programmers that work daily with Java. I don't. I know Java-the-language, because I worked on Java projects, but not Java-the-world. I never made a web app from scratch in Java. If I have to do it with Python, Ruby, I know where to go (Django or Rails), but if I want to make a web application in Clojure, not because I'm forced to live in a Java world, but because I like the language and I want to give it a try, what libraries and frameworks should I use?</p>
|
[
{
"answer_id": 610595,
"author": "Joe W.",
"author_id": 3459,
"author_profile": "https://Stackoverflow.com/users/3459",
"pm_score": 3,
"selected": false,
"text": "(GET \"/post/:id/:slug\"\n (some-function-that-returns-html :id :slug))\n"
},
{
"answer_id": 3272200,
"author": "Ross Goddard",
"author_id": 4779,
"author_profile": "https://Stackoverflow.com/users/4779",
"pm_score": 7,
"selected": false,
"text": "(def app [req]\n (if (= \"/home\" (:uri req))\n {:status 200\n :body \"<h3>Welcome Home</h3>\"}\n {:status 200 \n :body \"<a href='/home'>Go Home!</a>\"}))\n (defroutes my-routes\n (GET \"/\" [] \"<h1>Hello all!</h1>\")\n (GET \"/user/:id\" [id] (str \"<h1>Hello \" id \"</h1>\")))\n (defroutes my-routes\n (GET \"*\" {uri :uri} \n {:staus 200 :body (str \"The uri of the current page is: \" uri)}))\n \"<h2>A header</h2>\" [:h2 \"A Header\"] \"<a href='/login'>Log In Page</a>\" [:a {:href \"/login\"} \"Log In Page\"] (defn layout [title & body]\n (html\n [:head [:title title]]\n [:body [:h1.header title] body])) \n\n(defn say-hello [name]\n (layout \"Welcome Page\" [:h3 (str \"Hello \" name)]))\n\n(defn hiccup-routes\n (GET \"/user/:name\" [name] (say-hello name)))\n"
},
{
"answer_id": 32165654,
"author": "nha",
"author_id": 1327651,
"author_profile": "https://Stackoverflow.com/users/1327651",
"pm_score": 4,
"selected": false,
"text": "Compojure apache Luminus compojure-api Pedestal Cognitect Aleph"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
167,282
|
<p>If two users are accessing same database table, how do we prevent users from overwriting each other’s data?</p>
|
[
{
"answer_id": 167318,
"author": "DL Redden",
"author_id": 20610,
"author_profile": "https://Stackoverflow.com/users/20610",
"pm_score": 1,
"selected": false,
"text": "last_actv_dtm last_actv_dtm UPDATE tab1\nSET\n col1 = ?\n , col2 = ?\n , last_actv_dtm = GETDATE()\nWHERE\n pkcol = rec.pkcol\n AND last_actv_dtm = rec.last_actv_dtm;\n"
},
{
"answer_id": 167367,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "SELECT column FROM table WHERE something = 'whatever' FOR UPDATE;\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
167,294
|
<p>I have a https link that requires user login & password. If I run it in FX like this:
<a href="https://usernameassword@www.example.com/link/sublink" rel="nofollow noreferrer">https://usernameassword@www.example.com/link/sublink</a></p>
<p>it will return the xml data as expected.</p>
<p>However, what i'm trying to do, is to automate this process.
I try to use <a href="http://php.net/manual/en/function.file-get-contents.php" rel="nofollow noreferrer">file_get_contents()</a> in PHP.</p>
<p>I even tried to use AJAX, but still doesn't work.</p>
<p>I tried to get the content (XML) either in Server or in the front-end (ajax), but both don't work.</p>
<p>Does anyone know what I need to go in order to get the content? Do I need to obtain the SSL certificate? </p>
<p>Solution in any ohter languages will be welcome too.</p>
|
[
{
"answer_id": 167318,
"author": "DL Redden",
"author_id": 20610,
"author_profile": "https://Stackoverflow.com/users/20610",
"pm_score": 1,
"selected": false,
"text": "last_actv_dtm last_actv_dtm UPDATE tab1\nSET\n col1 = ?\n , col2 = ?\n , last_actv_dtm = GETDATE()\nWHERE\n pkcol = rec.pkcol\n AND last_actv_dtm = rec.last_actv_dtm;\n"
},
{
"answer_id": 167367,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "SELECT column FROM table WHERE something = 'whatever' FOR UPDATE;\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/196874/"
] |
167,302
|
<p>I have an application in which attr_accessor is being used to keep temporary data for a model which will be passed to a rake task. Seeing there is not a database field for these attributes and they are not being calculated from database data, will the attr_accessor data persist and be available to the rake task? What happens if I need to restart the server - does the data get lost then if it's not saved to database? Or to pull this off, do I need to either save to a temp file or a database field?</p>
|
[
{
"answer_id": 168246,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 4,
"selected": true,
"text": "class Thing < ActiveRecord::Base\n attr_accessor :data\nend\n\n#try this in script/console\nthing = Thing.find(:first)\nthing.data = \"Something\"\nthing = Thing.find(:first)\n\nputs thing.data\n-> nil\n"
},
{
"answer_id": 758984,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "rake myraketask thing_id=#{thing.id} data=#{thing.data}"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13710/"
] |
167,304
|
<p>I am wondering if it is possible to use LINQ to pivot data from the following layout:</p>
<pre><code>CustID | OrderDate | Qty
1 | 1/1/2008 | 100
2 | 1/2/2008 | 200
1 | 2/2/2008 | 350
2 | 2/28/2008 | 221
1 | 3/12/2008 | 250
2 | 3/15/2008 | 2150
</code></pre>
<p>into something like this:</p>
<pre><code>CustID | Jan- 2008 | Feb- 2008 | Mar - 2008 |
1 | 100 | 350 | 250
2 | 200 | 221 | 2150
</code></pre>
|
[
{
"answer_id": 167937,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 9,
"selected": true,
"text": "List<CustData> myList = GetCustData();\n\nvar query = myList\n .GroupBy(c => c.CustId)\n .Select(g => new {\n CustId = g.Key,\n Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty),\n Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty),\n March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty)\n });\n GroupBy"
},
{
"answer_id": 6282689,
"author": "Sanjaya.Tio",
"author_id": 683491,
"author_profile": "https://Stackoverflow.com/users/683491",
"pm_score": 4,
"selected": false,
"text": "// order s(ource) by OrderDate to have proper column ordering\nvar r = s.Pivot3(e => e.custID, e => e.OrderDate.ToString(\"MMM-yyyy\")\n , lst => lst.Sum(e => e.Qty));\n// order r(esult) by CustID\n"
},
{
"answer_id": 32167435,
"author": "Vitaliy Fedorchenko",
"author_id": 2756471,
"author_profile": "https://Stackoverflow.com/users/2756471",
"pm_score": 2,
"selected": false,
"text": "IEnumerable<CustData> s;\nvar groupedData = s.ToLookup( \n k => new ValueKey(\n k.CustID, // 1st dimension\n String.Format(\"{0}-{1}\", k.OrderDate.Month, k.OrderDate.Year // 2nd dimension\n ) ) );\nvar rowKeys = groupedData.Select(g => (int)g.Key.DimKeys[0]).Distinct().OrderBy(k=>k);\nvar columnKeys = groupedData.Select(g => (string)g.Key.DimKeys[1]).Distinct().OrderBy(k=>k);\nforeach (var row in rowKeys) {\n Console.Write(\"CustID {0}: \", row);\n foreach (var column in columnKeys) {\n Console.Write(\"{0:####} \", groupedData[new ValueKey(row,column)].Sum(r=>r.Qty) );\n }\n Console.WriteLine();\n}\n public sealed class ValueKey {\n public readonly object[] DimKeys;\n public ValueKey(params object[] dimKeys) {\n DimKeys = dimKeys;\n }\n public override int GetHashCode() {\n if (DimKeys==null) return 0;\n int hashCode = DimKeys.Length;\n for (int i = 0; i < DimKeys.Length; i++) { \n hashCode ^= DimKeys[i].GetHashCode();\n }\n return hashCode;\n }\n public override bool Equals(object obj) {\n if ( obj==null || !(obj is ValueKey))\n return false;\n var x = DimKeys;\n var y = ((ValueKey)obj).DimKeys;\n if (ReferenceEquals(x,y))\n return true;\n if (x.Length!=y.Length)\n return false;\n for (int i = 0; i < x.Length; i++) {\n if (!x[i].Equals(y[i]))\n return false;\n }\n return true; \n }\n}\n var pvtData = new PivotData(new []{\"CustID\",\"OrderDate\"}, new SumAggregatorFactory(\"Qty\"));\npvtData.ProcessData(s, (o, f) => {\n var custData = (TT)o;\n switch (f) {\n case \"CustID\": return custData.CustID;\n case \"OrderDate\": \n return String.Format(\"{0}-{1}\", custData.OrderDate.Month, custData.OrderDate.Year);\n case \"Qty\": return custData.Qty;\n }\n return null;\n} );\nConsole.WriteLine( pvtData[1, \"1-2008\"].Value ); \n"
},
{
"answer_id": 43091570,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 3,
"selected": false,
"text": "var query =\n from c in myList\n group c by c.CustId into gcs\n let lookup = gcs.ToLookup(y => y.OrderDate.Month, y => y.Qty)\n select new\n {\n CustId = gcs.Key,\n Jan = lookup[1].Sum(),\n Feb = lookup[2].Sum(),\n Mar = lookup[3].Sum(),\n };\n"
},
{
"answer_id": 52828775,
"author": "Ali Bayat",
"author_id": 3427324,
"author_profile": "https://Stackoverflow.com/users/3427324",
"pm_score": 0,
"selected": false,
"text": "var query = myList\n .GroupBy(c => c.CustId)\n .Select(g => {\n var results = new CustomerStatistics();\n foreach (var customer in g)\n {\n switch (customer.OrderDate.Month)\n {\n case 1:\n results.Jan += customer.Qty;\n break;\n case 2:\n results.Feb += customer.Qty;\n break;\n case 3:\n results.March += customer.Qty;\n break;\n default:\n break;\n }\n }\n return new\n {\n CustId = g.Key,\n results.Jan,\n results.Feb,\n results.March\n };\n });\n var query = myList\n .GroupBy(c => c.CustId)\n .Select(g => {\n var results = g.Aggregate(new CustomerStatistics(), (result, customer) => result.Accumulate(customer), customerStatistics => customerStatistics.Compute());\n return new\n {\n CustId = g.Key,\n results.Jan,\n results.Feb,\n results.March\n };\n });\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleApp\n{\n internal class Program\n {\n private static void Main(string[] args)\n {\n IEnumerable<CustData> myList = GetCustData().Take(100);\n\n var query = myList\n .GroupBy(c => c.CustId)\n .Select(g =>\n {\n CustomerStatistics results = g.Aggregate(new CustomerStatistics(), (result, customer) => result.Accumulate(customer), customerStatistics => customerStatistics.Compute());\n return new\n {\n CustId = g.Key,\n results.Jan,\n results.Feb,\n results.March\n };\n });\n Console.ReadKey();\n }\n\n private static IEnumerable<CustData> GetCustData()\n {\n Random random = new Random();\n int custId = 0;\n while (true)\n {\n custId++;\n yield return new CustData { CustId = custId, OrderDate = new DateTime(2018, random.Next(1, 4), 1), Qty = random.Next(1, 50) };\n }\n }\n\n }\n public class CustData\n {\n public int CustId { get; set; }\n public DateTime OrderDate { get; set; }\n public int Qty { get; set; }\n }\n public class CustomerStatistics\n {\n public int Jan { get; set; }\n public int Feb { get; set; }\n public int March { get; set; }\n internal CustomerStatistics Accumulate(CustData customer)\n {\n switch (customer.OrderDate.Month)\n {\n case 1:\n Jan += customer.Qty;\n break;\n case 2:\n Feb += customer.Qty;\n break;\n case 3:\n March += customer.Qty;\n break;\n default:\n break;\n }\n return this;\n }\n public CustomerStatistics Compute()\n {\n return this;\n }\n }\n}\n"
},
{
"answer_id": 70385919,
"author": "Grant Johnson",
"author_id": 2208461,
"author_profile": "https://Stackoverflow.com/users/2208461",
"pm_score": 0,
"selected": false,
"text": "// LINQPad Code for Amy B answer\nvoid Main()\n{\n List<CustData> myList = GetCustData();\n \n var query = myList\n .GroupBy(c => c.CustId)\n .Select(g => new\n {\n CustId = g.Key,\n Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty),\n Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty),\n March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty),\n //April = g.Where(c => c.OrderDate.Month == 4).Sum(c => c.Qty),\n //May = g.Where(c => c.OrderDate.Month == 5).Sum(c => c.Qty),\n //June = g.Where(c => c.OrderDate.Month == 6).Sum(c => c.Qty),\n //July = g.Where(c => c.OrderDate.Month == 7).Sum(c => c.Qty),\n //August = g.Where(c => c.OrderDate.Month == 8).Sum(c => c.Qty),\n //September = g.Where(c => c.OrderDate.Month == 9).Sum(c => c.Qty),\n //October = g.Where(c => c.OrderDate.Month == 10).Sum(c => c.Qty),\n //November = g.Where(c => c.OrderDate.Month == 11).Sum(c => c.Qty),\n //December = g.Where(c => c.OrderDate.Month == 12).Sum(c => c.Qty) \n });\n \n \n query.Dump();\n}\n\n/// <summary>\n/// --------------------------------\n/// CustID | OrderDate | Qty\n/// --------------------------------\n/// 1 | 1 / 1 / 2008 | 100\n/// 2 | 1 / 2 / 2008 | 200\n/// 1 | 2 / 2 / 2008 | 350\n/// 2 | 2 / 28 / 2008 | 221\n/// 1 | 3 / 12 / 2008 | 250\n/// 2 | 3 / 15 / 2008 | 2150 \n/// </ summary>\npublic List<CustData> GetCustData()\n{\n List<CustData> custData = new List<CustData>\n {\n new CustData\n {\n CustId = 1,\n OrderDate = new DateTime(2008, 1, 1),\n Qty = 100\n },\n\n new CustData\n {\n CustId = 2,\n OrderDate = new DateTime(2008, 1, 2),\n Qty = 200\n },\n\n new CustData\n {\n CustId = 1,\n OrderDate = new DateTime(2008, 2, 2),\n Qty = 350\n },\n\n new CustData\n {\n CustId = 2,\n OrderDate = new DateTime(2008, 2, 28),\n Qty = 221\n },\n\n new CustData\n {\n CustId = 1,\n OrderDate = new DateTime(2008, 3, 12),\n Qty = 250\n },\n\n new CustData\n {\n CustId = 2,\n OrderDate = new DateTime(2008, 3, 15),\n Qty = 2150\n }, \n };\n\n return custData;\n}\n\npublic class CustData\n{\n public int CustId;\n public DateTime OrderDate;\n public uint Qty;\n}\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2833/"
] |
167,316
|
<p>I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?</p>
|
[
{
"answer_id": 167338,
"author": "Shaun Bowe",
"author_id": 1514,
"author_profile": "https://Stackoverflow.com/users/1514",
"pm_score": 4,
"selected": false,
"text": "SELECT DATEADD(ms, -2, DATEADD(dd, 1, DATEDIFF(dd, 0, GetDate())))\n DateTime now = DateTime.Now;\nDateTime endofDay = now.Date.AddDays(1).AddMilliseconds(-1);\n"
},
{
"answer_id": 167350,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": false,
"text": "SELECT DATEADD(ms, -3, '2008-01-24') BETWEEN BETWEEN DATETIME SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0))\n BETWEEN SELECT [ID]\n FROM [dbo].[Orders]\n WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0)\n AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0))\n"
},
{
"answer_id": 167428,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "AND @CompareDate <= [LastTimeforThatday]\n @compareDate BETWEEN [StartDate] AND [LastTimeforThatday]\n AND @CompareDate < [BeginningOfNextDay]\n AND (@CompareDate >= [StartDate] AND @CompareDate < [BeginningOfNextDay])\n"
},
{
"answer_id": 31524964,
"author": "davef",
"author_id": 5136461,
"author_profile": "https://Stackoverflow.com/users/5136461",
"pm_score": 2,
"selected": false,
"text": "SELECT DATEADD(ms, 86399997, *yourDate*)\n"
},
{
"answer_id": 71165518,
"author": "Phil",
"author_id": 18237793,
"author_profile": "https://Stackoverflow.com/users/18237793",
"pm_score": 0,
"selected": false,
"text": "select {fn curdate()} + ' 23:59:59.000'\n select DATEADD(ss,-1,DATEADD(DAY,1,CAST({fn curdate()} as DATETIME)))\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21004/"
] |
167,323
|
<p>I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed <a href="https://stackoverflow.com/questions/164789/winforms-implementation-question-for-having-my-ui-run-independently-of-my-bll-l">here</a>.</p>
<p>In trying to figure this out I wrote the following simple test program. I simply want it to open a form on a separate thread named "UI thread" and keep the thread running as long as the form is open while allowing the user to interact with the form (spinning is cheating). I understand why the below fails and the thread closes immediately but am not sure of what I should do to fix it.</p>
<pre><code>using System;
using System.Windows.Forms;
using System.Threading;
namespace UIThreadMarshalling {
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var tt = new ThreadTest();
ThreadStart ts = new ThreadStart(tt.StartUiThread);
Thread t = new Thread(ts);
t.Name = "UI Thread";
t.Start();
Thread.Sleep(new TimeSpan(0, 0, 10));
}
}
public class ThreadTest {
Form _form;
public ThreadTest() {
}
public void StartUiThread() {
_form = new Form1();
_form.Show();
}
}
}
</code></pre>
|
[
{
"answer_id": 167377,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": true,
"text": "public void StartUiThread()\n{\n using (Form1 _form = new Form1())\n {\n Application.Run(_form);\n }\n}\n"
},
{
"answer_id": 167402,
"author": "CheeZe5",
"author_id": 22431,
"author_profile": "https://Stackoverflow.com/users/22431",
"pm_score": 2,
"selected": false,
"text": "private void button1_Click(object sender, EventArgs e)\n{\n var t = new Thread(RunNewForm);\n t.Start();\n}\npublic static void RunNewForm()\n{\n Application.Run(new Form2());\n}\n"
},
{
"answer_id": 34018093,
"author": "Oli4",
"author_id": 1799272,
"author_profile": "https://Stackoverflow.com/users/1799272",
"pm_score": 1,
"selected": false,
"text": "public void StartUiThread() {\n _form = new Form1();\n _form.ShowDialog(); //Change Show() to ShowDialog() to wait in thread\n }\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
167,330
|
<p>I have a 'Purchase Order' class. It contains information about a single purchase order. I have a DAO class for database methods.</p>
<p>Where should the responsibility reside for the methods that will load and update the purchase order?</p>
<p>Should the PurchaseOrder class have '.update', 'insert', 'delete', and '.load' methods that use the DAO class directly, or should the PurchaseOrder class be ignorant of the DAO methods and have a POController class that manages these interactions?</p>
<p>The user will only be working on a single PurchaseOrder at a time.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 167731,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 0,
"selected": false,
"text": "PurchaseOrder po;\nPurchaseOrderController poc;\npoc = PurchaseOrderControllerFactory.Instance.Create();\npo = poc.GetPurchaseOrder(42);\n// do stuff\npoc.SavePurchaseOrder(po);\n // It could be a factory if needed.\nPurchaseOrderSystem pos = new PurchaseOrderSystem(); \n\nList<PurchaseOrder> transacted;\ntransacted = pos.TransactPurchaseOrders(john, 23);\n\n// Show transacted purchase orders or whatever...\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6624/"
] |
167,343
|
<p>I have quickly read over the <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" rel="noreferrer">Microsoft Lambda Expression</a> documentation.</p>
<p>This kind of example has helped me to understand better, though: </p>
<pre><code>delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
</code></pre>
<p>Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method?</p>
|
[
{
"answer_id": 167363,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 7,
"selected": false,
"text": " List<string> people = new List<string> { \"name1\", \"name2\", \"joe\", \"another name\", \"etc\" };\n string person = people.Find(person => person.Contains(\"Joe\"));\n public string FindPerson(string nameContains, List<string> persons)\n {\n foreach (string person in persons)\n if (person.Contains(nameContains))\n return person;\n return null;\n }\n"
},
{
"answer_id": 167391,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 5,
"selected": false,
"text": "List<string> strings = new List<string>();\nstrings.Add(\"Good\");\nstrings.Add(\"Morning\")\nstrings.Add(\"Starshine\");\nstrings.Add(\"The\");\nstrings.Add(\"Earth\");\nstrings.Add(\"says\");\nstrings.Add(\"hello\");\n\nstrings.Find(s => s == \"hello\");\n List<string> strings = new List<string>();\nstrings.Add(\"Good\");\nstrings.Add(\"Morning\")\nstrings.Add(\"Starshine\");\nstrings.Add(\"The\");\nstrings.Add(\"Earth\");\nstrings.Add(\"says\");\nstrings.Add(\"hello\");\n\nprivate static bool FindHello(String s)\n{\n return s == \"hello\";\n}\n\nstrings.Find(FindHello);\n strings.Find(delegate(String s) { return s == \"hello\"; });\n"
},
{
"answer_id": 167392,
"author": "Neil Williams",
"author_id": 9617,
"author_profile": "https://Stackoverflow.com/users/9617",
"pm_score": 9,
"selected": true,
"text": "// anonymous delegate\nvar evens = Enumerable\n .Range(1, 100)\n .Where(delegate(int x) { return (x % 2) == 0; })\n .ToList();\n\n// lambda expression\nvar evens = Enumerable\n .Range(1, 100)\n .Where(x => (x % 2) == 0)\n .ToList();\n Expression<T> void Example(Predicate<int> aDelegate);\n Example(x => x > 5);\n void Example(Expression<Predicate<int>> expressionTree);\n x > 5"
},
{
"answer_id": 167425,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "Strings.Find(s => s == \"hello\");\n Strings.Find(delegate(String s) { return s == \"hello\"; });\n"
},
{
"answer_id": 187497,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Linq;\nusing System.Linq.Expressions;\n\n\nnamespace ExpressionTreeThingy\n{\n class Program\n {\n static void Main(string[] args)\n {\n Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object\n var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime\n Console.WriteLine(del(5)); //we are just invoking a delegate at this point\n Console.ReadKey();\n }\n }\n}\n"
},
{
"answer_id": 378726,
"author": "agnieszka",
"author_id": 40872,
"author_profile": "https://Stackoverflow.com/users/40872",
"pm_score": 6,
"selected": false,
"text": "private ComboBox combo;\nprivate Label label;\n\npublic CreateControls()\n{\n combo = new ComboBox();\n label = new Label();\n //some initializing code\n combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);\n}\n\nvoid combo_SelectedIndexChanged(object sender, EventArgs e)\n{\n label.Text = combo.SelectedValue;\n}\n public CreateControls()\n{\n ComboBox combo = new ComboBox();\n Label label = new Label();\n //some initializing code\n combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};\n}\n"
},
{
"answer_id": 20704196,
"author": "LCJ",
"author_id": 696627,
"author_profile": "https://Stackoverflow.com/users/696627",
"pm_score": 3,
"selected": false,
"text": "delegate int MyDelagate (int i);\nMyDelagate delSquareFunction = x => x * x;\n x => x * x; x => {return x * x;};\n Func Console.WriteLine(MyMethod(x => \"Hi \" + x));\n\n public static string MyMethod(Func<string, string> strategy)\n {\n return strategy(\"Lijo\").ToString();\n }\n"
},
{
"answer_id": 20969202,
"author": "Gunasekaran",
"author_id": 1377919,
"author_profile": "https://Stackoverflow.com/users/1377919",
"pm_score": 3,
"selected": false,
"text": "Action public static long Measure(Action action)\n{\n Stopwatch sw = new Stopwatch();\n sw.Start();\n action();\n sw.Stop();\n return sw.ElapsedMilliseconds;\n}\n var timeTaken = Measure(() => yourMethod(param));\n var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));\n"
},
{
"answer_id": 74125532,
"author": "neena",
"author_id": 20211089,
"author_profile": "https://Stackoverflow.com/users/20211089",
"pm_score": 0,
"selected": false,
"text": "var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n\nvar oddNumbers = numbers.Where(x => x % 2 != 0);\nvar sumOfEven = numbers.Where(x => x % 2 == 0).Sum();\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
167,371
|
<p>I just want to see what files were modded/added/deleted between 2 arbitrary revisions. How do I do this?</p>
<p>Can I do this in tortoise as well?</p>
|
[
{
"answer_id": 167378,
"author": "Max Cantor",
"author_id": 16034,
"author_profile": "https://Stackoverflow.com/users/16034",
"pm_score": 6,
"selected": true,
"text": "svn log -v -rX:Y .\n"
},
{
"answer_id": 5736542,
"author": "Elias Zamaria",
"author_id": 28324,
"author_profile": "https://Stackoverflow.com/users/28324",
"pm_score": 5,
"selected": false,
"text": "svn diff -r X:Y --summarize\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
167,397
|
<p>What are the popular (ok, popular is relative) web frameworks for the various flavours of LISP?</p>
|
[
{
"answer_id": 13457783,
"author": "battlemidget",
"author_id": 415485,
"author_profile": "https://Stackoverflow.com/users/415485",
"pm_score": 2,
"selected": false,
"text": "RESTAS is a Common Lisp web application framework. Its key features are:\n\nRESTAS was developed to simplify development of web applications following the REST architectural style.\n\nRESTAS is based on the Hunchentoot HTTP server. Web application development with RESTAS is in many ways simpler than with Hunchentoot, but some knowledge of Hunchentoot is required, at least about working with hunchentoot:*request* and hunchentoot:*reply*.\n\nRequest dispatch is based on a route system. The route system is the key concept of RESTAS and provides unique features not found in other web frameworks.\n\nThe other key RESTAS concept is its module system, which provides a simple and flexible mechanism for modularized code reuse.\n\nInteractive development support. Any RESTAS code (such as the definition of a route, a module or a submodule) can be recompiled at any time when you work in SLIME and any changes you made can be immediately seen in the browser. No web server restart or other complicated actions are needed.\n\nSLIME integration. The inner structure of a web application can be investigated with the standard \"SLIME Inspector.\" For example, there is a \"site map\" and a simple code navigation with this map.\n\nEasy to use, pure Lisp web application daemonization facility based on RESTAS and SBCL in Linux without the use of Screen or detachtty.\n\nRESTAS is not an MVC framework, although it is not incompatible with the concept. From the MVC point of view, RESTAS provides the controller level. Nevertheless, RESTAS provides an effective and flexible way for separation of logic and representation, because it does not put any constraints on the structure of applications. Separation of model and controller can be effectively performed with Common Lisp facilities, and, hence, doesn't need any special support from the framework.\n\nRESTAS does not come with a templating library. cl-closure-template and HTML-TEMPLATE are two good templating libraries that can be used with RESTAS.\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432/"
] |
167,406
|
<p>I have a "Date of Birth" field, and trying to use the <code>timespan()</code> method to get the age in years. But returns "28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes".</p>
<p>Any idea how I can just get the "28 Years" portion?</p>
|
[
{
"answer_id": 167463,
"author": "Kevin Chan",
"author_id": 1877,
"author_profile": "https://Stackoverflow.com/users/1877",
"pm_score": 0,
"selected": false,
"text": "$date = '28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes';\n $yearsPart = substr($date, 0, strpos($date, 'Years') + 5);\n $parts = split(', ', $date);\n$yearsPart = $parts[0];\n"
},
{
"answer_id": 312401,
"author": "Teej",
"author_id": 37532,
"author_profile": "https://Stackoverflow.com/users/37532",
"pm_score": 2,
"selected": false,
"text": "echo strftime('%Y', 1226239392);"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
167,414
|
<p>On POSIX systems rename(2) provides for an atomic rename operation, including overwriting of the destination file if it exists and if permissions allow.</p>
<p>Is there any way to get the same semantics on Windows? I know about MoveFileTransacted() on Vista and Server 2008, but I need this to support Win2k and up.</p>
<p>The key word here is <em>atomic</em>... the solution must not be able to fail in any way that leaves the operation in an inconsistent state.</p>
<p>I've seen a lot of people say this is impossible on win32, but I ask you, is it really? </p>
<p>Please provide reliable citations if possible.</p>
|
[
{
"answer_id": 2368286,
"author": "edg",
"author_id": 284924,
"author_profile": "https://Stackoverflow.com/users/284924",
"pm_score": 5,
"selected": false,
"text": "ReplaceFile()"
},
{
"answer_id": 51737582,
"author": "Craig Barkhouse",
"author_id": 10194831,
"author_profile": "https://Stackoverflow.com/users/10194831",
"pm_score": 4,
"selected": false,
"text": "NtSetInformationFile(..., FileRenameInformationEx, ...) FILE_RENAME_POSIX_SEMANTICS SetFileInformationByHandle(..., FileRenameInfoEx, ...) FILE_RENAME_FLAG_POSIX_SEMANTICS"
},
{
"answer_id": 57358387,
"author": "Violet Giraffe",
"author_id": 634821,
"author_profile": "https://Stackoverflow.com/users/634821",
"pm_score": 3,
"selected": false,
"text": "FILE_RENAME_INFO.ReplaceIfExists ReplaceFile"
},
{
"answer_id": 60963667,
"author": "Pavel P",
"author_id": 468725,
"author_profile": "https://Stackoverflow.com/users/468725",
"pm_score": 1,
"selected": false,
"text": "std::rename std::filesystem::rename std::filesystem::rename std::filesystem::rename"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14739/"
] |
167,416
|
<p>Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor?</p>
<p>Motivation: we're migrating from one schema to a another and have a web-page that reads both tables and shows the (int) ID, but I can't have the same ID used for both tables.</p>
<p>I'm using SQL Server 9.0.3068.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 167421,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 2,
"selected": false,
"text": "SELECT NEWID()\n"
},
{
"answer_id": 167532,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 0,
"selected": false,
"text": "--Create table with a seed of 1 billion and an increment of 1\nCREATE TABLE myTable\n(\nprimaryKey int IDENTITY (1000000000, 1),\ncolumnOne varchar(10) NOT NULL\n)\n"
},
{
"answer_id": 167870,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE AlwaysRollback (\n id IDENTITY(1,1)\n);\n\nBEGIN TRANSACTION;\nINSERT INTO AllwaysRollBack () VALUES ();\nROLLBACK TRANSACTION;\n\nINSERT INTO RealTable1 (id, ...) VALUES (SCOPE_IDENTITY(), ...);\n\nBEGIN TRANSACTION;\nINSERT INTO AllwaysRollBack () VALUES ();\nROLLBACK TRANSACTION;\n\nINSERT INTO RealTable2 (id, ...) VALUES (SCOPE_IDENTITY(), ...);\n"
},
{
"answer_id": 4734441,
"author": "Daniel Casserly",
"author_id": 437346,
"author_profile": "https://Stackoverflow.com/users/437346",
"pm_score": 0,
"selected": false,
"text": " id integer NOT NULL DEFAULT nextval('table_two_seq'::regclass),\n"
},
{
"answer_id": 38427260,
"author": "Darrel Lee",
"author_id": 307968,
"author_profile": "https://Stackoverflow.com/users/307968",
"pm_score": 0,
"selected": false,
"text": "CREATE PROCEDURE GetNextValue \nAS\nBEGIN\n DECLARE @value int = null;\n\n -- Insert statements for procedure here\n INSERT into MySequence (DummyValue) Values (null);\n\n SET @value = SCOPE_IDENTITY();\n\n DELETE from MySequence where SequenceValue <> @value\n\n SELECT @value as Sequence\n\n return @value\nEND\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24881/"
] |
167,426
|
<p>I wrote small Python+Ajax programs (listed at the end) with socket module to study the COMET concept of asynchronous communications.<br/></p>
<p>The idea is to allow browsers to send messages real time each others via my python program.<br/></p>
<p>The trick is to let the "GET messages/..." connection opened waiting for a message to answer back.<br/></p>
<p>My problem is mainly on the reliability of what I have via socket.recv...<br/></p>
<p>When I POST from Firefox, it is working well.<br/></p>
<p>When I POST from Chrome or IE, the "data" I get in Python is empty.</p>
<p>Does anybody know about this problem between browsers?<br/></p>
<p>Are some browsers injecting some EOF or else characters killing the receiving of "recv"?<br/></p>
<p>Is there any solution known to this problem?</p>
<p>The server.py in Python:</p>
<pre><code> import socket
connected={}
def inRequest(text):
content=''
if text[0:3]=='GET':
method='GET'
else:
method='POST'
k=len(text)-1
while k>0 and text[k]!='\n' and text[k]!='\r':
k=k-1
content=text[k+1:]
text=text[text.index(' ')+1:]
url=text[:text.index(' ')]
return {"method":method,"url":url,"content":content}
mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
mySocket.bind ( ( '', 80 ) )
mySocket.listen ( 10 )
while True:
channel, details = mySocket.accept()
data=channel.recv(4096)
req=inRequest(data)
url=req["url"]
if url=="/client.html" or url=="/clientIE.html":
f=open('C:\\async\\'+url)
channel.send ('HTTP/1.1 200 OK\n\n'+f.read())
f.close()
channel.close()
elif '/messages' in url:
if req["method"]=='POST':
target=url[10:]
if target in connected:
connected[target].send("HTTP/1.1 200 OK\n\n"+req["content"])
print req["content"]+" sent to "+target
connected[target].close()
channel.close()
elif req["method"]=='GET':
user=url[10:]
connected[user]=channel
print user+' is connected'
</code></pre>
<p>The client.html in HTML+Javascript:</p>
<pre><code><html>
<head>
<script>
var user=''
function post(el) {
if (window.XMLHttpRequest) {
var text=el.value;
var req=new XMLHttpRequest();
el.value='';
var target=document.getElementById('to').value
}
else if (window.ActiveXObject) {
var text=el.content;
var req=new ActiveXObject("Microsoft.XMLHTTP");
el.content='';
}
else
return;
req.open('POST','messages/'+target,true)
req.send(text);
}
function get(u) {
if (user=='')
user=u.value
var req=new XMLHttpRequest()
req.open('GET','messages/'+user,true)
req.onload=function() {
var message=document.createElement('p');
message.innerHTML=req.responseText;
document.getElementById('messages').appendChild(message);
get(user);
}
req.send(null)
}
</script>
</head>
<body>
<span>From</span>
<input id="user"/>
<input type="button" value="sign in" onclick="get(document.getElementById('user'))"/>
<span>To</span>
<input id="to"/>
<span>:</span>
<input id="message"/>
<input type="button" value="post" onclick="post(document.getElementById('message'))"/>
<div id="messages">
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 170005,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": false,
"text": "index = '''\n<html>\n <head>\n </head>\n <body>\n <form action=\"/\" method=\"POST\">\n <textarea name=\"foo\"></textarea>\n <button type=\"submit\">post</button>\n </form>\n <h3>data posted</h3>\n <div>\n %s\n </div>\n </body>\n</html>\n'''\n\nbufsize = 4048\nimport socket\nimport re\nfrom urlparse import urlparse\n\nclass Headers(object):\n def __init__(self, headers):\n self.__dict__.update(headers)\n\n def __getitem__(self, name):\n return getattr(self, name)\n\n def get(self, name, default=None):\n return getattr(self, name, default)\n\nclass Request(object):\n header_re = re.compile(r'([a-zA-Z-]+):? ([^\\r]+)', re.M)\n\n def __init__(self, sock):\n header_off = -1\n data = ''\n while header_off == -1:\n data += sock.recv(bufsize)\n header_off = data.find('\\r\\n\\r\\n')\n header_string = data[:header_off]\n self.content = data[header_off+4:]\n\n lines = self.header_re.findall(header_string)\n self.method, path = lines.pop(0)\n path, protocol = path.split(' ')\n self.headers = Headers(\n (name.lower().replace('-', '_'), value)\n for name, value in lines\n )\n\n if self.method in ['POST', 'PUT']:\n content_length = int(self.headers.get('content_length', 0))\n while len(self.content) < content_length:\n self.content += sock.recv(bufsize)\n\n self.query = urlparse(path)[4]\n\nacceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nacceptor.setsockopt(\n socket.SOL_SOCKET,\n socket.SO_REUSEADDR,\n 1,\n)\nacceptor.bind(('', 2501 ))\nacceptor.listen(10)\n\nif __name__ == '__main__':\n while True:\n sock, info = acceptor.accept()\n request = Request(sock)\n sock.send('HTTP/1.1 200 OK\\n\\n' + (index % request.content) )\n sock.close()\n"
},
{
"answer_id": 170354,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "bufsize = 4048\nimport socket\nimport re\nfrom urlparse import urlparse\nconnected={}\nclass Headers(object):\n def __init__(self, headers):\n self.__dict__.update(headers)\n\n def __getitem__(self, name):\n return getattr(self, name)\n\n def get(self, name, default=None):\n return getattr(self, name, default)\n\nclass Request(object):\n header_re = re.compile(r'([a-zA-Z-]+):? ([^\\r]+)', re.M)\n\n def __init__(self, sock):\n header_off = -1\n data = ''\n while header_off == -1:\n data += sock.recv(bufsize)\n header_off = data.find('\\r\\n\\r\\n')\n header_string = data[:header_off]\n self.content = data[header_off+4:]\n furl=header_string[header_string.index(' ')+1:]\n self.url=furl[:furl.index(' ')]\n lines = self.header_re.findall(header_string)\n self.method, path = lines.pop(0)\n path, protocol = path.split(' ')\n self.headers = Headers(\n (name.lower().replace('-', '_'), value)\n for name, value in lines\n )\n if self.method in ['POST', 'PUT']:\n content_length = int(self.headers.get('content_length', 0))\n while len(self.content) < content_length:\n self.content += sock.recv(bufsize)\n self.query = urlparse(path)[4]\n\nacceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nacceptor.setsockopt(\n socket.SOL_SOCKET,\n socket.SO_REUSEADDR,\n 1,\n)\nacceptor.bind(('', 8007 ))\nacceptor.listen(10)\n\nif __name__ == '__main__':\n while True:\n sock, info = acceptor.accept()\n request = Request(sock)\n m=request.method\n u=request.url[1:]\n if m=='GET' and (u=='client.html' or u=='jquery.js'):\n f=open('c:\\\\async\\\\'+u,'r')\n sock.send('HTTP/1.1 200 OK\\n\\n'+f.read())\n f.close()\n sock.close()\n elif 'messages' in u:\n if m=='POST':\n target=u[9:]\n if target in connected:\n connected[target].send(\"HTTP/1.1 200 OK\\n\\n\"+request.content)\n connected[target].close()\n sock.close()\n elif m=='GET':\n user=u[9:]\n connected[user]=sock\n print user+' is connected'\n <html>\n<head>\n <style>\n input {width:80px;}\n span {font-size:12px;}\n button {font-size:10px;}\n </style>\n <script type=\"text/javascript\" src='jquery.js'></script>\n <script>\n var user='';\n function post(el) {$.post('messages/'+$('#to').val(),$('#message').val());}\n function get(u) {\n if (user=='') user=u.value\n $.get('messages/'+user,function(data) { $(\"<p>\"+data+\"</p>\").appendTo($('#messages'));get(user);});\n }\n </script>\n</head>\n<body>\n<span>From</span><input id=\"user\"/><button onclick=\"get(document.getElementById('user'))\">log</button>\n<span>To</span><input id=\"to\"/>\n<span>:</span><input id=\"message\"/><button onclick=\"post()\">post</button>\n<div id=\"messages\"></div>\n</body>\n</html>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
167,427
|
<p>What's the best way to go about creating a vertical and horizontal ruler bars in an SDI app? Would you make it part of the frame or the view? Derive it from CControlBar, or is there a better method?</p>
<p>The vertical ruler must also be docked to a pane and not the frame.</p>
<p>To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized.</p>
|
[
{
"answer_id": 169261,
"author": "Alf Zimmerman",
"author_id": 24612,
"author_profile": "https://Stackoverflow.com/users/24612",
"pm_score": 0,
"selected": false,
"text": "m_wndSplitter.CreateStatic(this, 1, 3);\n\nm_wndLeftPane.Create(&m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 0));\nm_ruler.Create(&m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 1));\n\nm_wndSplitter.CreateView(0, 2, pContext->m_pNewViewClass, CSize(300, 0), pContext);\nSetActiveView((CScrollView*)m_wndSplitter.GetDlgItem(m_wndSplitter.IdFromRowCol(0, 2)));\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24612/"
] |
167,432
|
<p>Example</p>
<p>G76 I0.4779 J270 K7 C90</p>
<p>X20 Y30 </p>
<p>If a number begins with I J K C X Y and it doesn't have a decimal then add decimal.
Above example should look like:</p>
<p>G76 I0.4779 J270 K7. C90.</p>
<p>X20. Y30.</p>
<p>Purpose of this code is to convert CNC code for an older Fanuc OPC controller</p>
|
[
{
"answer_id": 167530,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 2,
"selected": false,
"text": "Set RegEx = New RegExp\nRegEx.Global = True\nRegEx.Pattern = \"([IJKCXY]\\d+)([^\\.]|$)\"\nnewVar = RegEx.Replace (oldString, \"$1.$2\")\n Set RegEx = New RegExp\nRegEx.Global = True\nRegEx.Pattern = \"([IJKCXY]\\d+)([^\\.]|$)\"\nnewVar = RegEx.Replace (oldString, \"$1.$2\")\n"
},
{
"answer_id": 167651,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 0,
"selected": false,
"text": "function convert(str)\n Set RegEx = New RegExp\n RegEx.Global = True\n RegEx.Pattern = \"([IJKCXY]\\d*\\.?\\d*)\"\n Set Matches = regEx.Execute(str)\n\n For Each Match in Matches\n if instr(Match.value, \".\") = 0 then\n str = Replace(str, Match.value, Match.value & \".\")\n end if\n Next\n convert = str\nend function\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
167,439
|
<p><strong>Update:</strong> Thanks for the suggestions guys. After further research, I’ve reformulated the question here: <a href="https://stackoverflow.com/questions/217020/pythoneditline-on-os-x-163-sign-seems-to-be-bound-to-ed-prev-word">Python/editline on OS X: £ sign seems to be bound to ed-prev-word</a></p>
<p>On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell.</p>
<ul>
<li>Mac OS X 10.5.5</li>
<li>Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)</li>
<li>European keyboard (£ is shift-3)</li>
</ul>
<p>When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears.</p>
<p>If I’ve already typed some characters, e.g.</p>
<pre><code>>>> 1234567890 1234567890 1234567890
</code></pre>
<p>... then pressing shift-3 will make the cursor position itself after the most recent space, or the start of the line if there are no spaces left between the cursor and the start of the line.</p>
<p>In a normal bash shell, pressing shift-3 types a “£” as expected.</p>
<p>Any idea how I can type a literal “£” in the Python interactive shell?</p>
|
[
{
"answer_id": 167515,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 3,
"selected": false,
"text": " pound = u'\\u00A3'\n"
},
{
"answer_id": 167998,
"author": "indentation",
"author_id": 7706,
"author_profile": "https://Stackoverflow.com/users/7706",
"pm_score": 2,
"selected": false,
"text": "u'\\N{pound sign}' execute pound = u'\\N{pound sign}'"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578/"
] |
167,453
|
<p>I'm exploring the XML -> XSLT -> HTML meme for producing web content. I have very little XSLT experience.</p>
<p>I'm curious what mechanisms are available in XSLT to handle abstractions or "refactoring".</p>
<p>For example, with generic HTML and a service side include, many pages can be templated and decomposed to where there are, say, common header, nav, and footer segments, and the page itself is basically the body.</p>
<p>The common markup languages, JSP, PHP, ASP, go as far as to allow all of those segments to have dynamic content (such as adding the user name to every header block).</p>
<p>JSP goes even farther by allowing you to create Tag files, which can accept arguments to be used when generating the content, and even surround and work on content within the tags themselves.</p>
<p>I'm curious similar functionality is done within XSLT. What facilities are there to make reusable block of XSLT for things like creating HTML pages?</p>
|
[
{
"answer_id": 167468,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 3,
"selected": false,
"text": "Its rule based."
},
{
"answer_id": 167545,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 5,
"selected": true,
"text": "<page title=\"Home\">\n <navigation>\n <!-- something here -->\n </navigation>\n <main>\n <!-- something here -->\n </main>\n</page>\n call-template <xsl:template match=\"/page\" name=\"page\"> \n <html>\n <head> \n <title><xsl:value-of select=\"(@title)\" /></title> \n <xsl:call-template name=\"css\" />\n <xsl:call-template name=\"script\" />\n </head>\n <body>\n <xsl:call-template name=\"container\" />\n </body>\n </html>\n</xsl:template>\n css-extended. call-template <xsl:template name=\"css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{$cssPath}reset.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{$cssPath}style.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{$cssPath}layout.css\" />\n <xsl:call-template name=\"css-extended\" />\n </xsl:template> \n\n <!-- This is meant to be blank. It gets overriden by implementing stylesheets -->\n <xsl:template name=\"css-extended\" />\n content <xsl:template name=\"container\">\n <div id=\"container\">\n <xsl:call-template name=\"header\" />\n <xsl:call-template name=\"content\" />\n <xsl:call-template name=\"footer\" />\n </div>\n </xsl:template> \n\n <xsl:template name=\"content\">\n <div id=\"content\">\n <div id=\"content-inner\">\n <xsl:call-template name=\"sideBar\" />\n <xsl:call-template name=\"main\" />\n </div>\n </div>\n </xsl:template> \n\n <xsl:template name=\"main\">\n <div id=\"main\">\n <xsl:apply-templates select=\"main\" />\n <xsl:call-template name=\"main-extended\" />\n </div>\n </xsl:template>\n\n <!-- This is meant to be blank. It gets overriden by implementing stylesheets -->\n <xsl:template name=\"main-extended\" />\n\n<xsl:template name=\"footer\">\n <div id=\"footer\">\n <div id=\"footer-inner\">\n <!-- Footer content here -->\n </div>\n </div>\n</xsl:template> \n"
},
{
"answer_id": 171923,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<xsl:for-each /> <xsl:for-each select=\"/xml/data/here\">\n ... do some stuff ...\n</xsl:for-each>\n<xsl:for-each select=\"/xml/data/here\">\n ... do some DIFFERENT stuff ...\n</xsl:for-each>\n <xsl:template match=\"/\">\n ... do some stuff ...\n</xsl:template>\n <xsl:template match=\"/\">\n <xsl:apply-templates select=\"xml/data/too\" />\n</xsl:template>\n\n<xsl:template match=\"xml/data/too\">\n ... do something ...\n</xsl:template>\n <xsl:template name=\"WriteOut\">\n ... data with NO Context Here ...\n</xsl:template>\n <xsl:template match=\"/\">\n <xsl:call-template name=\"WriteOut\" />\n<xsl:template>\n <xsl:include href=\"header.xsl\" />\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13663/"
] |
167,464
|
<p>I am currently investigating how to make a connection to a SQL Server database from my Java EE web application using Windows Authentication instead of SQL Server authentication. I am running this app off of Tomcat 6.0, and am utilizing the Microsoft JDBC driver. My connection properties file looks as follows:</p>
<pre><code>dbDriver = com.microsoft.sqlserver.jdbc.SQLServerDriver
dbUser = user
dbPass = password
dbServer = localhost:1433;databaseName=testDb
dbUrl = jdbc:sqlserver://localhost:1433
</code></pre>
<p>I have zero problems with connecting to a SQL Server database in this fashion when using SQL Server authentication.</p>
<p>Is there any way I can retrieve the credentials of the user's Windows Authentication and use <strong>that</strong> authentication for SQL Server?</p>
<p><strong>UPDATE</strong>: I know in ASP.net there is a way to set up Windows Authentication for access to the webapp, which is exactly what I am looking for, except I want to pass that token off to SQL Server for access to the database.</p>
|
[
{
"answer_id": 356456,
"author": "Jerome Delattre",
"author_id": 27762,
"author_profile": "https://Stackoverflow.com/users/27762",
"pm_score": 7,
"selected": true,
"text": "jdbc:sqlserver://localhost;integratedSecurity=true;\n"
},
{
"answer_id": 801113,
"author": "opensas",
"author_id": 47633,
"author_profile": "https://Stackoverflow.com/users/47633",
"pm_score": 5,
"selected": false,
"text": "jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]\n"
},
{
"answer_id": 8836885,
"author": "Andy",
"author_id": 1145683,
"author_profile": "https://Stackoverflow.com/users/1145683",
"pm_score": 3,
"selected": false,
"text": "ntlmauth.dll PATH jdbc.default.url=jdbc:jtds:sqlserver://192.168.0.147:2302/lportal;useNTLMv2=true;domain=mydomain.local\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318/"
] |
167,471
|
<p>In Oracle, given a simple data table:</p>
<pre><code>create table data (
id VARCHAR2(255),
key VARCHAR2(255),
value VARCHAR2(511));
</code></pre>
<p>suppose I want to "insert or update" a value. I have something like:</p>
<pre><code>merge into data using dual on
(id='someid' and key='testKey')
when matched then
update set value = 'someValue'
when not matched then
insert (id, key, value) values ('someid', 'testKey', 'someValue');
</code></pre>
<p>Is there a better way than this? This command seems to have the following drawbacks:</p>
<ul>
<li>Every literal needs to be typed twice (or added twice via parameter setting)</li>
<li>The "using dual" syntax seems hacky</li>
</ul>
<p>If this is the best way, is there any way around having to set each parameter twice in JDBC?</p>
|
[
{
"answer_id": 167518,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "data_pkg.merge_data ('someid', 'testKey', 'someValue');\n begin\n insert into data (...) values (...);\nexception\n when dup_val_on_index then\n update data\n set ...\n where ...;\nend;\n"
},
{
"answer_id": 167754,
"author": "Craig",
"author_id": 55922,
"author_profile": "https://Stackoverflow.com/users/55922",
"pm_score": 6,
"selected": true,
"text": "merge into data\nusing (\n select\n 'someid' id,\n 'testKey' key,\n 'someValue' value\n from\n dual\n) val on (\n data.id=val.id\n and data.key=val.key\n)\nwhen matched then \n update set data.value = val.value \nwhen not matched then \n insert (id, key, value) values (val.id, val.key, val.value);\n"
},
{
"answer_id": 168573,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 2,
"selected": false,
"text": "update data set ...=... where ...=...;\n\nif sql%notfound then\n\n insert into data (...) values (...);\n\nend if;\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309/"
] |
167,485
|
<p>Is it possible to have a HasMany relationship of a basic type such as String, on an ActiveRecord class, without the need for creating another entity such as (TodoListItem) to hold the value.</p>
<pre><code>[ActiveRecord]
public class TodoList
{
[PrimaryKey]
public int Id
{
get { return _id; }
set { _id = value; }
}
[HasMany(typeof(string)]
public IList<string> Items
{
get { return _items; }
set { _items= value; }
}
}
</code></pre>
<p>Can anyone help?</p>
|
[
{
"answer_id": 167591,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": -1,
"selected": false,
"text": "[ActiveRecord(Table = \"MyTable\")]\npublic class MyClass : ActiveRecordBase<MyClass>\n{\n [Property]\n public int Id { get; set; }\n\n [Property]\n public int MyClassId { get; set; }\n\n [Property]\n public string ListItem { get; set; }\n}\n public void LoadMyClasses()\n{\n MyClass[] results = MyClass.FindAll();\n}\n"
},
{
"answer_id": 176807,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 4,
"selected": true,
"text": "ColumnKey Table Element HasMany Element [HasMany(typeof(string), Table=\"ToDoList_Items\", \n ColumnKey = \"ListItemID\", Element = \"Item\")]\npublic IList<string> Items { get; set; }\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4642/"
] |
167,491
|
<p>How do I in SQL Server 2005 use the DateAdd function to add a day to a date</p>
|
[
{
"answer_id": 167501,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "DECLARE @MyDate datetime\n\n-- ... set your datetime's initial value ...'\n\nDATEADD(d, 1, @MyDate)\n"
},
{
"answer_id": 167507,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 2,
"selected": false,
"text": "DECLARE @date DateTime\nSET @date = GetDate()\nSET @date = DateAdd(day, 1, @date)\n\nSELECT @date\n"
},
{
"answer_id": 167539,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 7,
"selected": false,
"text": "DATEADD(type, value, date)\n SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day\n"
},
{
"answer_id": 2204720,
"author": "Lakshmanan From INDIA",
"author_id": 266740,
"author_profile": "https://Stackoverflow.com/users/266740",
"pm_score": 2,
"selected": false,
"text": "Select getdate() -- 2010-02-05 10:03:44.527\n\n-- To get all date format\nselect CONVERT(VARCHAR(12),getdate(),100) +' '+ 'Date -100- MMM DD YYYY' -- Feb 5 2010\nunion\nselect CONVERT(VARCHAR(10),getdate(),101) +' '+ 'Date -101- MM/DDYYYY'\nUnion\nselect CONVERT(VARCHAR(10),getdate(),102) +' '+ 'Date -102- YYYY.MM.DD'\nUnion\nselect CONVERT(VARCHAR(10),getdate(),103) +' '+ 'Date -103- DD/MM/YYYY'\nUnion\nselect CONVERT(VARCHAR(10),getdate(),104) +' '+ 'Date -104- DD.MM.YYYY'\nUnion\nselect CONVERT(VARCHAR(10),getdate(),105) +' '+ 'Date -105- DD-MM-YYYY'\nUnion\nselect CONVERT(VARCHAR(11),getdate(),106) +' '+ 'Date -106- DD MMM YYYY' --ex: 03 Jan 2007\nUnion\nselect CONVERT(VARCHAR(12),getdate(),107) +' '+ 'Date -107- MMM DD,YYYY' --ex: Jan 03, 2007\nunion\nselect CONVERT(VARCHAR(12),getdate(),109) +' '+ 'Date -108- MMM DD YYYY' -- Feb 5 2010\nunion\nselect CONVERT(VARCHAR(12),getdate(),110) +' '+ 'Date -110- MM-DD-YYYY' --02-05-2010\nunion\nselect CONVERT(VARCHAR(10),getdate(),111) +' '+ 'Date -111- YYYY/MM/DD'\nunion\nselect CONVERT(VARCHAR(12),getdate(),112) +' '+ 'Date -112- YYYYMMDD' -- 20100205\nunion\nselect CONVERT(VARCHAR(12),getdate(),113) +' '+ 'Date -113- DD MMM YYYY' -- 05 Feb 2010\n\n\nSELECT convert(varchar, getdate(), 20) -- 2010-02-05 10:25:14\nSELECT convert(varchar, getdate(), 23) -- 2010-02-05\nSELECT convert(varchar, getdate(), 24) -- 10:24:20\nSELECT convert(varchar, getdate(), 25) -- 2010-02-05 10:24:34.913\nSELECT convert(varchar, getdate(), 21) -- 2010-02-05 10:25:02.990\n\n\n---==================================\n-- To get the time\nselect CONVERT(VARCHAR(12),getdate(),108) +' '+ 'Date -108- HH:MM:SS' -- 10:05:53\n\nselect CONVERT(VARCHAR(12),getdate(),114) +' '+ 'Date -114- HH:MM:SS:MS' -- 10:09:46:223\nSELECT convert(varchar, getdate(), 22) -- 02/05/10 10:23:11 AM\n----=============================================\nSELECT getdate()+1\nSELECT month(getdate())+1\nSELECT year(getdate())+1\n"
},
{
"answer_id": 19590482,
"author": "Dilip Kr Singh",
"author_id": 1501276,
"author_profile": "https://Stackoverflow.com/users/1501276",
"pm_score": 3,
"selected": false,
"text": "DATEADD(DAY,20,GETDATE())\n"
},
{
"answer_id": 22148005,
"author": "BJ Patel",
"author_id": 2683759,
"author_profile": "https://Stackoverflow.com/users/2683759",
"pm_score": 4,
"selected": false,
"text": "select DateAdd(day, 1, GetDate())\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21004/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.