qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
166,239 |
<p>I am trying to remotely run a DTSX package from a bat file with this command:</p>
<pre><code>DTEXEC /DTS "\File System\MY_PACKAGE_NAME" /SERVER MY_SERVER_NAME /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING V
</code></pre>
<p>This is working fine locally but failing remotely (I do have admin rights on the machine I am pointing to and I have SQL permissions as well) I am getting a timeout error (Login timeout expired).</p>
|
[
{
"answer_id": 170849,
"author": "JohnIdol",
"author_id": 1311500,
"author_profile": "https://Stackoverflow.com/users/1311500",
"pm_score": 3,
"selected": true,
"text": "<p>After a bit of research it looks like it is impossible to run DTEXEC remotely (it needs to be run locally - remote execution is not supported).</p>\n\n<p>To overcome this limitation the following method seems to be broadly implemented:</p>\n\n<ol>\n<li>set up a SQL job to run the DTSX package</li>\n<li>set up a Stored Procedure to run the job</li>\n<li>use isql command line in a BAT file (remotely executed) to run the stored procedure on the relevant SQL instance (with SQL credentials and not machine credentials)</li>\n</ol>\n"
},
{
"answer_id": 418362,
"author": "Jobo",
"author_id": 51915,
"author_profile": "https://Stackoverflow.com/users/51915",
"pm_score": 1,
"selected": false,
"text": "<p>SSIS also exposes a web service on the hosting server. You could via code, query a machine for packages, run packages via database or file system and add / modify variables of the package programmatically via any programming platform you like.</p>\n\n<p>That being said you could also set up your webservice to call your local batch file which contains your 'DETEXEC' command.</p>\n"
},
{
"answer_id": 689799,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>It's very possible, and so easily. There is no need to have a store procedure, nor SQL agent, or Web, or .NET development. I am surprised the Microsoft never suggested this:</p>\n\n<ol>\n<li>Schedule a task on the SQL Server to run the DTSX package. Disable it, so it won't run until you manually execute it from a remote PC.</li>\n<li>Execute the task from the PC using the command:</li>\n</ol>\n\n<blockquote>\n <p>schtasks /run /tn MyTask [/s MySQLServer [/u [domain]user /p password]] /?</p>\n</blockquote>\n\n<p>Note: if you do not like exposing the password, use the 'PSEXEC' command to execute the 'schtasks' command(download the free and powerful tool from <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx</a></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311500/"
] |
I am trying to remotely run a DTSX package from a bat file with this command:
```
DTEXEC /DTS "\File System\MY_PACKAGE_NAME" /SERVER MY_SERVER_NAME /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING V
```
This is working fine locally but failing remotely (I do have admin rights on the machine I am pointing to and I have SQL permissions as well) I am getting a timeout error (Login timeout expired).
|
After a bit of research it looks like it is impossible to run DTEXEC remotely (it needs to be run locally - remote execution is not supported).
To overcome this limitation the following method seems to be broadly implemented:
1. set up a SQL job to run the DTSX package
2. set up a Stored Procedure to run the job
3. use isql command line in a BAT file (remotely executed) to run the stored procedure on the relevant SQL instance (with SQL credentials and not machine credentials)
|
166,295 |
<pre><code><Grid.Triggers>
<EventTrigger RoutedEvent="Border.Loaded">
<EventTrigger.Actions >
<BeginStoryboard>
<Storyboard x:Name="MyStoryboard" AutoReverse="True" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="border" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:01" Value="#FFFAFAFA"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Grid.Triggers>
</code></pre>
<p>How do I enable\disable this event trigger\animation dynamically. I was thinking I could bind to a IValueConverter and disable the storyboard, but there does not seem to be any suitable property to bind to?</p>
|
[
{
"answer_id": 166460,
"author": "Bill Reiss",
"author_id": 18967,
"author_profile": "https://Stackoverflow.com/users/18967",
"pm_score": 1,
"selected": false,
"text": "<p>The only trigger currently available in Silverlight is \"Loaded\", for all other events you'll have to write a bit of code. To use this technique, Storyboards should go in the Resources section instead of Triggers, and you'll call Begin() on the Storyboard from the code.</p>\n\n<p>If you're doing templating of a control, then there are what are called Transitions which let you kick off storyboards based on control events, like MouseOver. This is handled by the Visual State Manager:</p>\n\n<p><a href=\"http://timheuer.com/blog/archive/2008/06/04/silverlight-introduces-visual-state-manager-vsm.aspx\" rel=\"nofollow noreferrer\">http://timheuer.com/blog/archive/2008/06/04/silverlight-introduces-visual-state-manager-vsm.aspx</a></p>\n"
},
{
"answer_id": 166494,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 0,
"selected": false,
"text": "<p>I wasn't really looking for the animation to be turned off based on an event. I wanted to do it based on a property of my business object that Im binding too? I was hoping there was something like Storyboard.Enabled = False!?!?!</p>\n"
},
{
"answer_id": 215762,
"author": "Christopher Bennage",
"author_id": 6855,
"author_profile": "https://Stackoverflow.com/users/6855",
"pm_score": 0,
"selected": false,
"text": "<p>You can't do what you are asking for with triggers in Silverlight. There's not a way to have a conditional in the trigger.\nYou can wire up the Loaded event, check your condition there, and if it's met start the storyboard. However, there is not a XAML-only equivalent.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
```
<Grid.Triggers>
<EventTrigger RoutedEvent="Border.Loaded">
<EventTrigger.Actions >
<BeginStoryboard>
<Storyboard x:Name="MyStoryboard" AutoReverse="True" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="border" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:01" Value="#FFFAFAFA"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Grid.Triggers>
```
How do I enable\disable this event trigger\animation dynamically. I was thinking I could bind to a IValueConverter and disable the storyboard, but there does not seem to be any suitable property to bind to?
|
The only trigger currently available in Silverlight is "Loaded", for all other events you'll have to write a bit of code. To use this technique, Storyboards should go in the Resources section instead of Triggers, and you'll call Begin() on the Storyboard from the code.
If you're doing templating of a control, then there are what are called Transitions which let you kick off storyboards based on control events, like MouseOver. This is handled by the Visual State Manager:
<http://timheuer.com/blog/archive/2008/06/04/silverlight-introduces-visual-state-manager-vsm.aspx>
|
166,321 |
<p>Is it possible to create a SQL query which will return one column which contains the dates from a given date range (e.g. all dates from last year till today). E.g.</p>
<pre><code>dat
----
2007-10-01
2007-10-02
2007-10-03
2007-10-04
...
</code></pre>
<p>I am wondering if this is possible as an alternative to creating a table which holds all those dates precalculated.</p>
<p><strong>Updated:</strong> I need a solution for MYSQL. I am not interested in any other DBs in this case.</p>
|
[
{
"answer_id": 166345,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 2,
"selected": false,
"text": "<p>AFAIK you cannot do that with a single SQL query. However the following block of code will do the job.</p>\n\n<p>Currently in Transact-SQL (for SQL Server). I do not know how this translates to MySQL.</p>\n\n<pre><code>DECLARE @start datetime\nDECLARE @end datetime\nDECLARE @results TABLE\n(\n val datetime not null\n)\nset @start = '2008-10-01'\nset @end = getdate()\nwhile @start < @end\nbegin\n insert into @results values(@start)\n SELECT @start = DATEADD (d, 1, @start)\nend\nselect val from @results\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>2008-10-01 00:00:00.000\n2008-10-02 00:00:00.000\n2008-10-03 00:00:00.000\n</code></pre>\n"
},
{
"answer_id": 166652,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p>Prior to CTEs, one would use a standard pre-loaded table of integer numbers (usually a few thousand in a utility table see <a href=\"http://web.archive.org/web/20150411042510/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html\" rel=\"nofollow noreferrer\">this article</a>) and join to it as necessary. This would work for you in mysql:</p>\n\n<pre><code>CREATE TABLE dbo.Numbers \n( \n Number INT IDENTITY(1,1) PRIMARY KEY CLUSTERED \n) \n\nWHILE COALESCE(SCOPE_IDENTITY(), 0) <= 1024 \nBEGIN \n INSERT dbo.Numbers DEFAULT VALUES \nEND\n\nSELECT DATEADD(dd, Number, DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(yy, -1, GETDATE())))) AS Date\nFROM Numbers\nWHERE Number BETWEEN 0 AND 366\n</code></pre>\n\n<p>In SQL Server 2005, you can use common table expressions and recursion:</p>\n\n<pre><code>WITH DateRange(Date) AS\n(\n SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(yy, -1, GETDATE()))) AS Date\n UNION ALL\n SELECT DATEADD(day, 1, Date) AS Date\n FROM DateRange\n WHERE Date <= GETDATE()\n)\nSELECT Date \nFROM DateRange\nOPTION (MAXRECURSION 366)\n</code></pre>\n"
},
{
"answer_id": 167618,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 2,
"selected": false,
"text": "<p>I do not have a MySQL instance at hand just now, but see if this will do. Substitute parameters as appropriate. I hard-coded 2007-01-01 for the example.</p>\n\n<p>Regards.</p>\n\n<pre><code>SELECT\n ADDDATE('2007-01-01' INTERVAL SeqValue DAY) DateValue\nFROM\n(\nSELECT\n (HUNDREDS.SeqValue + TENS.SeqValue + ONES.SeqValue) SeqValue\nFROM\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 1 SeqValue\n UNION ALL\n SELECT 2 SeqValue\n UNION ALL\n SELECT 3 SeqValue\n UNION ALL\n SELECT 4 SeqValue\n UNION ALL\n SELECT 5 SeqValue\n UNION ALL\n SELECT 6 SeqValue\n UNION ALL\n SELECT 7 SeqValue\n UNION ALL\n SELECT 8 SeqValue\n UNION ALL\n SELECT 9 SeqValue\n ) ONES\nCROSS JOIN\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 10 SeqValue\n UNION ALL\n SELECT 20 SeqValue\n UNION ALL\n SELECT 30 SeqValue\n UNION ALL\n SELECT 40 SeqValue\n UNION ALL\n SELECT 50 SeqValue\n UNION ALL\n SELECT 60 SeqValue\n UNION ALL\n SELECT 70 SeqValue\n UNION ALL\n SELECT 80 SeqValue\n UNION ALL\n SELECT 90 SeqValue\n ) TENS\nCROSS JOIN\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 100 SeqValue\n UNION ALL\n SELECT 200 SeqValue\n UNION ALL\n SELECT 300 SeqValue\n UNION ALL\n SELECT 400 SeqValue\n UNION ALL\n SELECT 500 SeqValue\n UNION ALL\n SELECT 600 SeqValue\n UNION ALL\n SELECT 700 SeqValue\n UNION ALL\n SELECT 800 SeqValue\n UNION ALL\n SELECT 900 SeqValue\n ) HUNDREDS\n) SEQ\nWHERE\n SEQ.SeqValue < = 366 AND\n ADDDATE('2007-01-01' INTERVAL SeqValue DAY) < ADDDATE('2007-01-01' INTERVAL 1 YEAR)\nORDER BY\n ADDDATE('2007-01-01' INTERVAL SeqValue DAY) ASC\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21672/"
] |
Is it possible to create a SQL query which will return one column which contains the dates from a given date range (e.g. all dates from last year till today). E.g.
```
dat
----
2007-10-01
2007-10-02
2007-10-03
2007-10-04
...
```
I am wondering if this is possible as an alternative to creating a table which holds all those dates precalculated.
**Updated:** I need a solution for MYSQL. I am not interested in any other DBs in this case.
|
AFAIK you cannot do that with a single SQL query. However the following block of code will do the job.
Currently in Transact-SQL (for SQL Server). I do not know how this translates to MySQL.
```
DECLARE @start datetime
DECLARE @end datetime
DECLARE @results TABLE
(
val datetime not null
)
set @start = '2008-10-01'
set @end = getdate()
while @start < @end
begin
insert into @results values(@start)
SELECT @start = DATEADD (d, 1, @start)
end
select val from @results
```
This outputs:
```
2008-10-01 00:00:00.000
2008-10-02 00:00:00.000
2008-10-03 00:00:00.000
```
|
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": "<p>\"How do I write ruby\" is a little beyond the scope of SO.</p>\n\n<p>But to turn these ruby scripts into executable scripts, put this as the first line of your ruby script:</p>\n\n<pre><code>#!/path/to/ruby\n</code></pre>\n\n<p>Then make the file executable:</p>\n\n<pre><code>chmod a+x myscript.rb\n</code></pre>\n\n<p>and away you go.</p>\n"
},
{
"answer_id": 166373,
"author": "Vasil",
"author_id": 7883,
"author_profile": "https://Stackoverflow.com/users/7883",
"pm_score": 4,
"selected": false,
"text": "<p>let's say you write your <code>script.rb</code> script. put:</p>\n\n<pre><code>#!/usr/bin/env ruby\n</code></pre>\n\n<p>as the first line and do a <code>chmod +x script.rb</code></p>\n"
},
{
"answer_id": 166432,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 2,
"selected": false,
"text": "<p>Place this at the beginning of your script.rb</p>\n\n<pre><code>#!/usr/bin/env ruby\n</code></pre>\n\n<p>Then mark it as executable:</p>\n\n<pre><code>chmod +x script.rb\n</code></pre>\n"
},
{
"answer_id": 166445,
"author": "Georg Schölly",
"author_id": 24587,
"author_profile": "https://Stackoverflow.com/users/24587",
"pm_score": 7,
"selected": false,
"text": "<p>As the others have said already, your first line should be</p>\n\n<pre><code>#!/usr/bin/env ruby\n</code></pre>\n\n<p>And you also have to make it executable: (in the shell)</p>\n\n<pre><code>chmod +x test.rb\n</code></pre>\n\n<p>Then follows the ruby code. If you open a file</p>\n\n<pre><code>File.open(\"file\", \"r\") do |io|\n # do something with io\nend\n</code></pre>\n\n<p>the file is opened in the current directory you'd get with <code>pwd</code> in the shell.</p>\n\n<p>The path to your script is also simple to get. With <code>$0</code> you get the first argument of the shell, which is the relative path to your script. The absolute path can be determined like that:</p>\n\n<pre><code>#!/usr/bin/env ruby\nrequire 'pathname'\np Pathname.new($0).realpath()\n</code></pre>\n\n<p>For file system operations I almost always use Pathname. This is a wrapper for many of the other file system related classes. Also useful: Dir, File...</p>\n"
},
{
"answer_id": 166541,
"author": "bltxd",
"author_id": 11892,
"author_profile": "https://Stackoverflow.com/users/11892",
"pm_score": 2,
"selected": false,
"text": "<p>In ruby, the constant <code>__FILE__</code> will always give you the path of the script you're running.</p>\n\n<p>On Linux, <code>/usr/bin/env</code> is your friend:</p>\n\n<pre><code>#! /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</code></pre>\n\n<p>On Windows it depends whether or not .rb files are associated with ruby.\nIf they are:</p>\n\n<pre><code># This script filename must end with .rb\nputs File.expand_path(__FILE__)\n</code></pre>\n\n<p>If they are not, you have to explicitly invoke ruby on them, I use a intermediate .cmd file:</p>\n\n<p>my_script.cmd:</p>\n\n<pre><code>@ruby %~dp0\\my_script.rb\n</code></pre>\n\n<p>my_script.rb:</p>\n\n<pre><code>puts File.expand_path(__FILE__)\n</code></pre>\n"
},
{
"answer_id": 166624,
"author": "Aaron Hinni",
"author_id": 12086,
"author_profile": "https://Stackoverflow.com/users/12086",
"pm_score": 4,
"selected": false,
"text": "<p>Go get yourself a copy of <a href=\"http://www.pragprog.com/titles/bmsft/everyday-scripting-with-ruby\" rel=\"noreferrer\">Everyday Scripting with Ruby</a>. It has plenty of useful tips on how to do the types of things your are wanting to do.</p>\n"
},
{
"answer_id": 166854,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 8,
"selected": true,
"text": "<p>By default, you already have access to <a href=\"http://www.ruby-doc.org/core/classes/Dir.html\" rel=\"noreferrer\">Dir</a> and <a href=\"http://www.ruby-doc.org/core/classes/File.html\" rel=\"noreferrer\">File</a>, which are pretty useful by themselves.</p>\n\n<pre><code>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</code></pre>\n\n<p>Also useful from the stdlib is <a href=\"http://www.ruby-doc.org/stdlib/libdoc/fileutils/rdoc/index.html\" rel=\"noreferrer\">FileUtils</a></p>\n\n<pre><code>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</code></pre>\n\n<p>Which is pretty nice </p>\n"
},
{
"answer_id": 171752,
"author": "craigp",
"author_id": 1436792,
"author_profile": "https://Stackoverflow.com/users/1436792",
"pm_score": 4,
"selected": false,
"text": "<p>This might also be helpful: <a href=\"http://rush.heroku.com/\" rel=\"noreferrer\">http://rush.heroku.com/</a></p>\n\n<p>I haven't used it much, but looks pretty cool</p>\n\n<p>From the site:</p>\n\n<blockquote>\n <p>rush is a replacement for the unix shell (bash, zsh, etc) which uses pure Ruby syntax. Grep through files, find and kill processes, copy files - everything you do in the shell, now in Ruby</p>\n</blockquote>\n"
},
{
"answer_id": 1806991,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 6,
"selected": false,
"text": "<p>Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.</p>\n\n<p>So, if you had a script called my_shell_script:</p>\n\n<pre><code>#!/usr/bin/env ruby\nputs \"I was passed: \"\nARGV.each do |value|\n puts value\nend\n</code></pre>\n\n<p>...make it executable (as others have mentioned):</p>\n\n<pre><code>chmod u+x my_shell_script\n</code></pre>\n\n<p>And call it like so: </p>\n\n<pre><code>> ./my_shell_script one two three four five\n</code></pre>\n\n<p>You'd get this:</p>\n\n<pre><code>I was passed: \none\ntwo\nthree\nfour\nfive\n</code></pre>\n\n<p>The arguments work nicely with filename expansion:</p>\n\n<pre><code>./my_shell_script *\n\nI was passed: \na_file_in_the_current_directory\nanother_file \nmy_shell_script\nthe_last_file\n</code></pre>\n\n<p>Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.</p>\n"
},
{
"answer_id": 2392597,
"author": "Dan Rosenstark",
"author_id": 8047,
"author_profile": "https://Stackoverflow.com/users/8047",
"pm_score": 5,
"selected": false,
"text": "<p>There's a lot of good advice here, so I wanted to add a tiny bit more.</p>\n\n<ol>\n<li><p>Backticks (or back-ticks) let you do some scripting stuff a lot easier. Consider</p>\n\n<pre><code>puts `find . | grep -i lib`\n</code></pre></li>\n<li><p>If you run into problems with getting the output of backticks, the stuff is going to standard err instead of standard out. <a href=\"http://www.weheartcode.com/2007/09/14/capturing-stderr-with-ruby-backticks/comment-page-1/#comment-30518\" rel=\"nofollow noreferrer\">Use this advice</a></p>\n\n<pre><code>out = `git status 2>&1`\n</code></pre></li>\n<li><p>Backticks do string interpolation:</p>\n\n<pre><code>blah = 'lib'\n`touch #{blah}`\n</code></pre></li>\n<li><p><a href=\"http://compileyouidontevenknowyou.blogspot.com/2010/02/how-to-pipe-in-ruby.html\" rel=\"nofollow noreferrer\">You can pipe inside Ruby, too</a>. It's a link to my blog, but it links back here so it's okay :) There are probably more advanced things out there on this topic.</p></li>\n<li><p>As other people noted, if you want to get serious there is Rush: not just as a shell replacement (which is a bit too zany for me) but also <a href=\"http://rush.heroku.com/handbook/library\" rel=\"nofollow noreferrer\">as a library for your use in shell scripts and programs.</a></p></li>\n</ol>\n\n<hr>\n\n<p>On Mac, Use Applescript inside Ruby for more power. Here's my <code>shell_here</code> script:</p>\n\n<pre><code>#!/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</code></pre>\n"
},
{
"answer_id": 12203123,
"author": "awenkhh",
"author_id": 1032757,
"author_profile": "https://Stackoverflow.com/users/1032757",
"pm_score": 2,
"selected": false,
"text": "<p>The answer by <a href=\"https://stackoverflow.com/users/6349/webmat\">webmat</a> is perfect. I just want to point you to a addition. If you have to deal a lot with command line parameters for your scripts, you should use <a href=\"http://ruby-doc.org/stdlib-1.9.3/libdoc/optparse/rdoc/OptionParser.html\" rel=\"nofollow noreferrer\">optparse</a>. It is simple and helps you tremendously.</p>\n"
},
{
"answer_id": 15494213,
"author": "Bohr",
"author_id": 1297064,
"author_profile": "https://Stackoverflow.com/users/1297064",
"pm_score": 3,
"selected": false,
"text": "<p>When you want to write more complex ruby scripts, these tools may help:</p>\n\n<p>For example: </p>\n\n<ul>\n<li><p><a href=\"http://github.com/wycats/thor\" rel=\"noreferrer\">thor</a>(a scripting framework)</p></li>\n<li><p><a href=\"http://davetron5000.github.com/gli/\" rel=\"noreferrer\">gli</a>(git like interface)</p></li>\n<li><p><a href=\"https://github.com/davetron5000/methadone\" rel=\"noreferrer\">methadone</a>(for creating simple tools)</p></li>\n</ul>\n\n<p>They give you a quick start to write your own scripts, especially 'command line app'.</p>\n"
},
{
"answer_id": 40916488,
"author": "Houcheng",
"author_id": 1196716,
"author_profile": "https://Stackoverflow.com/users/1196716",
"pm_score": 3,
"selected": false,
"text": "<p>The above answer are interesting and very helpful when using Ruby as shell script. For me, I does not use Ruby as my daily language and I prefer to use ruby as flow control only and still use bash to do the tasks.</p>\n\n<p>Some helper function can be used for testing execution result</p>\n\n<pre><code>#!/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</code></pre>\n\n<p>With helper, the ruby script could be bash alike:</p>\n\n<pre><code>#!/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</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24773/"
] |
I have some simple shell scripting tasks that I want to do
For example: Selecting a file in the working directory from a list of the files matching some regular expression.
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.
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
So the question is what parts of the Ruby libraries do I need to know to write ruby shell scripts?
|
By default, you already have access to [Dir](http://www.ruby-doc.org/core/classes/Dir.html) and [File](http://www.ruby-doc.org/core/classes/File.html), which are pretty useful by themselves.
```
Dir['*.rb'] #basic globs
Dir['**/*.rb'] #** == any depth of directory, including current dir.
#=> array of relative names
File.expand_path('~/file.txt') #=> "/User/mat/file.txt"
File.dirname('dir/file.txt') #=> 'dir'
File.basename('dir/file.txt') #=> 'file.txt'
File.join('a', 'bunch', 'of', 'strings') #=> 'a/bunch/of/strings'
__FILE__ #=> the name of the current file
```
Also useful from the stdlib is [FileUtils](http://www.ruby-doc.org/stdlib/libdoc/fileutils/rdoc/index.html)
```
require 'fileutils' #I know, no underscore is not ruby-like
include FileUtils
# Gives you access (without prepending by 'FileUtils.') to
cd(dir, options)
cd(dir, options) {|dir| .... }
pwd()
mkdir(dir, options)
mkdir(list, options)
mkdir_p(dir, options)
mkdir_p(list, options)
rmdir(dir, options)
rmdir(list, options)
ln(old, new, options)
ln(list, destdir, options)
ln_s(old, new, options)
ln_s(list, destdir, options)
ln_sf(src, dest, options)
cp(src, dest, options)
cp(list, dir, options)
cp_r(src, dest, options)
cp_r(list, dir, options)
mv(src, dest, options)
mv(list, dir, options)
rm(list, options)
rm_r(list, options)
rm_rf(list, options)
install(src, dest, mode = <src's>, options)
chmod(mode, list, options)
chmod_R(mode, list, options)
chown(user, group, list, options)
chown_R(user, group, list, options)
touch(list, options)
```
Which is pretty nice
|
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": "<p>As far as I know, there's no way do do this within the Servlet API. However, you can parse web.xml directly and extract the values yourself. I used dom4j below, but you can use whatever XML processing stuff you like:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 36058398,
"author": "Foyta",
"author_id": 322240,
"author_profile": "https://Stackoverflow.com/users/322240",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the version of Ian's answer using newer DOM API:</p>\n\n<pre><code>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</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18702/"
] |
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?
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.
|
As far as I know, there's no way do do this within the Servlet API. However, you can parse web.xml directly and extract the values yourself. I used dom4j below, but you can use whatever XML processing stuff you like:
```
protected List<String> getSecurityRoles() {
List<String> roles = new ArrayList<String>();
ServletContext sc = this.getServletContext();
InputStream is = sc.getResourceAsStream("/WEB-INF/web.xml");
try {
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
Element webApp = doc.getRootElement();
// Type safety warning: dom4j doesn't use generics
List<Element> roleElements = webApp.elements("security-role");
for (Element roleEl : roleElements) {
roles.add(roleEl.element("role-name").getText());
}
} catch (DocumentException e) {
e.printStackTrace();
}
return roles;
}
```
|
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": "<p>My first reaction would be to <code>yum update apache</code> (or just a <code>yum update</code>). </p>\n\n<p>Then try the <code>yum install mod_python</code>.</p>\n"
},
{
"answer_id": 515131,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>also getting same issue</p>\n\n<p>--> Running transaction check\n---> Package mod_python.i386 0:3.2.8-3.1 set to be updated\n--> Processing Dependency: httpd >= 2.0.40 for package: mod_python\n--> Processing Dependency: httpd-mmn = 20051115 for package: mod_python\n--> Finished Dependency Resolution\nError: Missing Dependency: httpd >= 2.0.40 is needed by package mod_python\nError: Missing Dependency: httpd-mmn = 20051115 is needed by package mod_python</p>\n"
},
{
"answer_id": 953856,
"author": "GuiSim",
"author_id": 116301,
"author_profile": "https://Stackoverflow.com/users/116301",
"pm_score": 1,
"selected": false,
"text": "<p>We have mod_python 3.3 running on Apache 2.2 on a CentOS (forgot the version). All we did is download the tar.gz (from <a href=\"http://httpd.apache.org/modules/python-download.cgi\" rel=\"nofollow noreferrer\">http://httpd.apache.org/modules/python-download.cgi</a>) , extract it...</p>\n\n<pre><code>$ ./configure --with-apxs=/usr/local/apache2/bin/apxs\n$ ./make\n$ su\n$ make install\n</code></pre>\n\n<p>Everything works fine. We couldn't use yum so everything is built from source.\nMy suggestion would be to try to build from source.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24039/"
] |
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.
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
The error he is reporting is as follows:
```
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
```
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.
So my question is, what should I ask/tell the Administrator to do?
Is there something obviously wrong with the combination of components above?
|
We have mod\_python 3.3 running on Apache 2.2 on a CentOS (forgot the version). All we did is download the tar.gz (from <http://httpd.apache.org/modules/python-download.cgi>) , extract it...
```
$ ./configure --with-apxs=/usr/local/apache2/bin/apxs
$ ./make
$ su
$ make install
```
Everything works fine. We couldn't use yum so everything is built from source.
My suggestion would be to try to build from source.
|
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": "<p>You are looking for:</p>\n\n<pre><code>del L[:]\n</code></pre>\n"
},
{
"answer_id": 166462,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure why you're worried about the fact that you're referencing a new, empty list in memory instead of the same \"pointer\".</p>\n\n<p>Your other list is going to be collected sooner or later and one of the big perks about working in a high level, garbage-collected language is that you don't normally need to worry about stuff like this.</p>\n"
},
{
"answer_id": 57217653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><strong><em>this can help you::)</em></strong></p>\n\n<pre><code>L[:] = []\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] |
I find it annoying that I can't clear a list. In this example:
```
a = []
a.append(1)
a.append(2)
a = []
```
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.
The only way I can see of retaining the same pointer is doing something like the following:
```
for i in range(len(a)):
a.pop()
```
This seems pretty long-winded though, is there a better way of solving this?
|
You are looking for:
```
del L[:]
```
|
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": 166465,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 1,
"selected": false,
"text": "<p>My understanding is that a wrapper class for log4net would be a static class which takes care of initializing the logging object from app.config/web.config or by code (e.g. integration with NUnit).</p>\n"
},
{
"answer_id": 166466,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 0,
"selected": false,
"text": "<p>a possible use for a log4net wrapper could be a class that gets the calling class and method via reflection to get an idea of where your logging entry happened. at least i use this frequently.</p>\n"
},
{
"answer_id": 166477,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 6,
"selected": false,
"text": "<p>Essentially you create an interface and then a concrete implementation of that interface that wraps the classes and methods of Log4net directly. Additional logging systems can be wrapped by creating more concrete classes which wrap other classes and methods of those systems. Finally use a factory to create instances of your wrappers based on a configuration setting or line of code change. (Note: you can get more flexible - and complex - using an <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"noreferrer\">Inversion of Control</a> container such as <a href=\"http://structuremap.sourceforge.net/Default.htm\" rel=\"noreferrer\">StructureMap</a>.)</p>\n\n<pre><code>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</code></pre>\n\n<p>And an example of using this code in your classes (declared as a static readonly field):</p>\n\n<pre><code>private static readonly ILogger _logger =\n LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n</code></pre>\n\n<p>You can get the same slightly more performance friendly effect using:</p>\n\n<pre><code>private static readonly ILogger _logger = \n LogManager.GetLogger(typeof(YourTypeName));\n</code></pre>\n\n<p>The former example is considered more maintainable.</p>\n\n<p>You would not want to create a Singleton to handle all logging because Log4Net logs for the invoking type; its much cleaner and useful to have each type use its own logger rather than just seeing a single type in the log file reporting all messages.</p>\n\n<p>Because your implementation should be fairly reusable (other projects in your organization) you could make it its own assembly or ideally include it with your own personal/organization's framework/utility assembly. Do not re-declare the classes separately in each of your business/data/UI assemblies, that's not maintainable.</p>\n"
},
{
"answer_id": 166577,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>What benefits are you planning on getting out of writing a wrapper for log4net. I'd recommend getting comfortable with the log4net classes first before writing a wrapper around them. cfeduke is right in his answer on how to write said wrapper, but unless you need to add actual functionality to his example a wrapper would only succeed in slowing the logging process down and adding complexity for future maintainers. This especially true when refactoring tools available in .Net make such changes super easy.</p>\n"
},
{
"answer_id": 588912,
"author": "Alconja",
"author_id": 68727,
"author_profile": "https://Stackoverflow.com/users/68727",
"pm_score": 5,
"selected": false,
"text": "<p>Assuming you were going with something like <a href=\"https://stackoverflow.com/questions/166438/what-would-a-log4net-wrapper-class-look-like/166477#166477\">cfeduke's answer above</a>, you could also add an overload to your <code>LogManager</code> like this:</p>\n\n<pre><code>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</code></pre>\n\n<p>That way in your code you can now just use:</p>\n\n<pre><code>private static readonly ILogger _logger = LogManager.GetLogger();\n</code></pre>\n\n<p>instead of either of these:</p>\n\n<pre><code>private static readonly ILogger _logger =\n LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\nprivate static readonly ILogger _logger = \n LogManager.GetLogger(typeof(YourTypeName));\n</code></pre>\n\n<p>Which is effectively equivalent of the first alternative (i.e. the one that uses <code>MethodBase.GetCurrentMethod().DeclaringType</code>), only a little simpler.</p>\n"
},
{
"answer_id": 1286900,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Alconja, I like your idea of using the stacktrace to jump back to the calling method. I was thinking of further encapsulating the calls, to not just retrieve the logger object, but to perform actually perform the logging. What I want is a static class that handles the logging, by abstracting from the specific implementation used. I.e. </p>\n\n<pre><code>LoggingService.LogError(\"my error message\");\n</code></pre>\n\n<p>That way I only need to change the internals of the static class, if I later decide to user another logging system. </p>\n\n<p>So I used your idea to get the calling object using the stack trace : </p>\n\n<pre><code>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</code></pre>\n\n<p>Does anybody see a problem with this approach?</p>\n"
},
{
"answer_id": 4370244,
"author": "Michael",
"author_id": 532768,
"author_profile": "https://Stackoverflow.com/users/532768",
"pm_score": -1,
"selected": false,
"text": "<p>I know this answer is late, but it may help someone in the future.</p>\n\n<p>It sounds like you want a programmatic API that XQuiSoft Logging gives you. You don't have to specify which logger you want with XQuiSoft. it is as simple as this:</p>\n\n<p>Log.Write(Level.Verbose, \"source\", \"category\", \"your message here\");</p>\n\n<p>Then via configuration you direct messages by source, category, level, or any other custom filter to different locations (files, emails, etc...).</p>\n\n<p>See <a href=\"http://www.codeproject.com/KB/cs/XQuiSoftLoggingIntro.aspx\" rel=\"nofollow\">this article</a> for an introduction.</p>\n"
},
{
"answer_id": 35164947,
"author": "Jeson Martajaya",
"author_id": 868532,
"author_profile": "https://Stackoverflow.com/users/868532",
"pm_score": 1,
"selected": false,
"text": "<p>I have successfully isolated log4net dependency into a single project. If you intend to do the same, here is what my wrapper class look like:</p>\n\n<pre><code>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</code></pre>\n\n<p>And dont forget to add this in the <code>AssemblyInfo.cs</code> of the interfacing project (took me a good few hours to find this)</p>\n\n<pre><code>[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = \"log4net.config\")]\n</code></pre>\n\n<p>And put your log4net configuration xml in <code>log4net.config</code> file, set it as <code>Content</code>, <code>Copy Always</code></p>\n"
},
{
"answer_id": 38394820,
"author": "Leonardo",
"author_id": 497058,
"author_profile": "https://Stackoverflow.com/users/497058",
"pm_score": 1,
"selected": false,
"text": "<p>There are frameworks like the <a href=\"https://msdn.microsoft.com/en-us/library/ff648465.aspx\" rel=\"nofollow\">Prism Library for WPF</a> that promote the usage of a <a href=\"https://en.wikipedia.org/wiki/Facade_pattern\" rel=\"nofollow\">facade</a> for the logging framework of your choice.</p>\n\n<p>This is an example that uses <a href=\"https://logging.apache.org/log4net/\" rel=\"nofollow\">log4net</a>:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>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</code></pre>\n\n<p>Note that by specifying the <a href=\"https://logging.apache.org/log4net/release/sdk/html/M_log4net_Core_ILogger_Log_1.htm\" rel=\"nofollow\"><code>callerStackBoundaryDeclaringType</code></a> you can still get the class name of the caller issuing the logging request. All you need to do is to include <code>%C %M</code> in your conversion pattern:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date [%thread] %-5level %C.%M - %message%newline\" />\n</layout>\n</code></pre>\n\n<p>However, as the <a href=\"https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html\" rel=\"nofollow\">documentation</a> warns, generating the caller class information is slow, therefore it must be used wisely.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
] |
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.
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?
Should the wrapper be a singleton class?
|
Essentially you create an interface and then a concrete implementation of that interface that wraps the classes and methods of Log4net directly. Additional logging systems can be wrapped by creating more concrete classes which wrap other classes and methods of those systems. Finally use a factory to create instances of your wrappers based on a configuration setting or line of code change. (Note: you can get more flexible - and complex - using an [Inversion of Control](http://en.wikipedia.org/wiki/Inversion_of_control) container such as [StructureMap](http://structuremap.sourceforge.net/Default.htm).)
```
public interface ILogger
{
void Debug(object message);
bool IsDebugEnabled { get; }
// continue for all methods like Error, Fatal ...
}
public class Log4NetWrapper : ILogger
{
private readonly log4net.ILog _logger;
public Log4NetWrapper(Type type)
{
_logger = log4net.LogManager.GetLogger(type);
}
public void Debug(object message)
{
_logger.Debug(message);
}
public bool IsDebugEnabled
{
get { return _logger.IsDebugEnabled; }
}
// complete ILogger interface implementation
}
public static class LogManager
{
public static ILogger GetLogger(Type type)
{
// if configuration file says log4net...
return new Log4NetWrapper(type);
// if it says Joe's Logger...
// return new JoesLoggerWrapper(type);
}
}
```
And an example of using this code in your classes (declared as a static readonly field):
```
private static readonly ILogger _logger =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
```
You can get the same slightly more performance friendly effect using:
```
private static readonly ILogger _logger =
LogManager.GetLogger(typeof(YourTypeName));
```
The former example is considered more maintainable.
You would not want to create a Singleton to handle all logging because Log4Net logs for the invoking type; its much cleaner and useful to have each type use its own logger rather than just seeing a single type in the log file reporting all messages.
Because your implementation should be fairly reusable (other projects in your organization) you could make it its own assembly or ideally include it with your own personal/organization's framework/utility assembly. Do not re-declare the classes separately in each of your business/data/UI assemblies, that's not maintainable.
|
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>I think you want:</p>\n\n<pre><code>/p:DefineConstants=ACTIVATE\n</code></pre>\n"
},
{
"answer_id": 166524,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": -1,
"selected": false,
"text": "<p>It should probably be:</p>\n\n<pre><code>#ifdef ACTIVATE\n# pragma message( \"Activated\" )\n#else\n# pragma message( \"Not Activated\")\n#endif\n</code></pre>\n"
},
{
"answer_id": 166556,
"author": "Mac",
"author_id": 8696,
"author_profile": "https://Stackoverflow.com/users/8696",
"pm_score": 4,
"selected": false,
"text": "<p>C++ projects (and solutions) are not (yet ?) integrated in the MSBuild environment. As part of the build process, the <a href=\"http://msdn.microsoft.com/en-us/library/8xcy2245.aspx\" rel=\"noreferrer\">VCBuild task</a> is called, which is just a wrapper around <a href=\"http://msdn.microsoft.com/en-us/library/hw9dzw3c.aspx\" rel=\"noreferrer\">vcbuild.exe</a>.</p>\n\n<p>You could :</p>\n\n<ul>\n<li>create a specific configuration for your solution where <code>ACTIVATE=1</code> would be defined, and compile it with <a href=\"http://msdn.microsoft.com/en-us/library/xee0c8y7.aspx\" rel=\"noreferrer\">devenv.exe</a> (with the <a href=\"http://msdn.microsoft.com/en-us/library/abtk353z.aspx\" rel=\"noreferrer\">/ProjectConfig</a> switch).</li>\n<li>create your own target file to wrap your own call to the <a href=\"http://msdn.microsoft.com/en-us/library/8xcy2245.aspx\" rel=\"noreferrer\">VCBuild task</a> (see the Override parameter)...</li>\n<li><strike>use vcbuild.exe instead of msbuild.exe.</strike> (vcbuild.exe does not seem to have the equivalent of an Override parameter).</li>\n</ul>\n\n<p>Note that your solution would not work for C# projects either unless you tweaked your project files a bit. For reference, here is how I would do this :</p>\n\n<ul>\n<li>Add the following code before the call to <code><Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" /></code> :</li>\n</ul>\n\n<pre><PropertyGroup Condition=\" '$(MyConstants)' != '' \">\n <DefineConstants>$(DefineConstants);$(MyConstants)</DefineConstants>\n</PropertyGroup></pre>\n\n<ul>\n<li>Call MSBuild like this :</li>\n</ul>\n\n<pre>msbuild /p:MyConstants=\"ACTIVATE=1\"</pre>\n"
},
{
"answer_id": 177923,
"author": "acemtp",
"author_id": 6605,
"author_profile": "https://Stackoverflow.com/users/6605",
"pm_score": -1,
"selected": true,
"text": "<p>The answer is : YOU CANNOT</p>\n"
},
{
"answer_id": 567813,
"author": "Bruce Ikin",
"author_id": 10409,
"author_profile": "https://Stackoverflow.com/users/10409",
"pm_score": -1,
"selected": false,
"text": "<p>I needed to do this too - needed to be able to build two different versions of my app and wanted to be able to script the build using VCBUILD. VCBUILD does have the /override command line switch, but I am not sure it can be used to modify #define symbols that can then be tested using #if conditional compilation.</p>\n\n<p>The solution I cam up with was to write a simple utility to create a header file that #defined the symbol based on the state of an environment variable and run the utility from a pre-build step. Prior to each execution of the VCBUILD step the script sets the environment variable and \"touches\" a file in the app to ensure that the prebuild step is executed. </p>\n\n<p>Yes, it is an ugly hack, but it was the best I could come up with!</p>\n"
},
{
"answer_id": 14206134,
"author": "bigh_29",
"author_id": 163679,
"author_profile": "https://Stackoverflow.com/users/163679",
"pm_score": 5,
"selected": false,
"text": "<p>I'm a little late to the party (only 4 years or so), but I just had to workaround this problem on a project, and stumbled across this question while searching for a fix. Our solution was to use an environment variable with <code>/D</code> defines in it, combined with the Additional Options box in visual studio.</p>\n\n<ol>\n<li>In Visual Studio, add an environment variable macro, <code>$(ExternalCompilerOptions)</code>, to the Additional Options under project options->C/C++->Command Line (remember both Debug and Release configs)</li>\n<li>Set the environment variable prior to calling msbuild. Use the <code>/D</code> compiler option to define your macros</li>\n</ol>\n\n<pre class=\"lang-sh prettyprint-override\"><code> c:\\> set ExternalCompilerOptions=/DFOO /DBAR \n c:\\> msbuild\n</code></pre>\n\n<p>Item #1 ends up looking like this in the vcxproj file:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code> <ClCompile>\n <AdditionalOptions>$(ExternalCompilerOptions) ... </AdditionalOptions>\n </ClCompile>\n</code></pre>\n\n<p>This works for me with VS 2010. We drive msbuild from various build scripts, so the environment variable ugliness is hidden a bit. Note that I have not tested if this works when you need to set the define to specific value ( <code>/DACTIVATE=1</code> ). I think it would work, but I'm concerned about having multiple '='s in there.</p>\n\n<p>H^2</p>\n"
},
{
"answer_id": 15746207,
"author": "4LegsDrivenCat",
"author_id": 2006632,
"author_profile": "https://Stackoverflow.com/users/2006632",
"pm_score": 4,
"selected": false,
"text": "<p>If you need to define some constant (not just <code>true</code>/<code>false</code>), you can do it the following way:</p>\n\n<p>On command line:</p>\n\n<pre><code>MSBuild /p:MyDefine=MyValue\n</code></pre>\n\n<p>In vcxproj file (in section <code><ClCompile></code>; and/or <code><ResourceCompile></code>, depending on where you need it):</p>\n\n<pre><code><PreprocessorDefinitions>MY_DEFINE=$(MyDefine);$(PreprocessorDefinitions)</PreprocessorDefinitions>\n</code></pre>\n\n<p>Note that if you don't specify <code>/p:MyDefine=MyValue</code> in a call to <code>MSBuild</code> then empty string will be assigned to <code>MY_DEFINE</code> macro. If it's OK for you, that's it. If not, keep reading.</p>\n\n<p><strong>How to make a macro undefined if corresponding MSBuild parameter is not specified</strong></p>\n\n<p>To have <code>MY_DEFINE</code> macro undefined instead of empty string, you can use the following trick:</p>\n\n<pre><code><ClCompile>\n ....\n <PreprocessorDefinitions>_DEBUG;_CONSOLE;OTHER_UNCONDITIONAL_MACROS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n <PreprocessorDefinitions Condition=\"'$(MyDefine)'!=''\">MY_DEFINE=$(MyDefine);%(PreprocessorDefinitions)</PreprocessorDefinitions>\n ....\n</ClCompile>\n</code></pre>\n\n<p>First <code>PreprocessorDefinitions</code> defines unconditional macros. Second <code>PreprocessorDefinitions</code> additionally defines <code>MY_DEFINE</code> macro when <code>MyDefine</code> is not empty string. You can test this by placing the following piece of code into your cpp file:</p>\n\n<pre><code>#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</code></pre>\n\n<p>and running:</p>\n\n<pre><code>> 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</code></pre>\n"
},
{
"answer_id": 17446664,
"author": "stijn",
"author_id": 128384,
"author_profile": "https://Stackoverflow.com/users/128384",
"pm_score": -1,
"selected": false,
"text": "<p>For VS2010 and up, see my answer <a href=\"https://stackoverflow.com/a/17446623/128384\">here</a> for a solution that requires no modification of the original project file.</p>\n"
},
{
"answer_id": 45837089,
"author": "Anthony",
"author_id": 692438,
"author_profile": "https://Stackoverflow.com/users/692438",
"pm_score": -1,
"selected": false,
"text": "<p>As @bigh_29 has mentioned, using environment variables to define or undefine a preprocessor. </p>\n\n<p>What he suggested the way to undefine a preprocessor is actually <strong>/U</strong>ACTIVATE. </p>\n\n<p>This way, any preprocessor matching ACTIVATE will be negated and compiler wouldn't go through your #if ACTIVATE #endif enclosure.</p>\n"
},
{
"answer_id": 49115730,
"author": "Lex Sergeev",
"author_id": 5658348,
"author_profile": "https://Stackoverflow.com/users/5658348",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe it is a bad idea to answer such old question, but recently I googled a similar problem and found this topic. I wrote a cmd script for some build system and I was succeed to find a solution. I leave it here for future generations (:</p>\n\n<p>According to @acemtp's problem, my solution would look like this:</p>\n\n<pre><code>@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</code></pre>\n\n<p>UPD: I tried to use <code>set CL=/DACTIVATE=1</code> and it also worked, but the <a href=\"https://msdn.microsoft.com/en-us/library/hhzbb5c8(v=vs.120).aspx\" rel=\"nofollow noreferrer\">official documentation</a> recommends to use <strong>number sign</strong></p>\n"
},
{
"answer_id": 49630451,
"author": "Jay",
"author_id": 4213883,
"author_profile": "https://Stackoverflow.com/users/4213883",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Use the CL environment variable to define preprocessor macros</strong></p>\n\n<p>Before calling MSBUILD, simply set the environment variable 'CL' with '/D' options like so:</p>\n\n<p><code>set CL=/DACTIVATE</code> to define ACTIVATE</p>\n\n<p>You can use the '#' symbol to replace '=' sign</p>\n\n<p><code>set CL=/DACTIVATE#1</code> will define ACTIVATE=1</p>\n\n<p>Then make the call to MSBUILD </p>\n\n<p>More documentation on the CL Environment Variables can be found at:\n<a href=\"https://msdn.microsoft.com/en-us/library/kezkeayy(v=vs.140).aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/kezkeayy(v=vs.140).aspx</a></p>\n"
},
{
"answer_id": 72157847,
"author": "tschumann",
"author_id": 5158636,
"author_profile": "https://Stackoverflow.com/users/5158636",
"pm_score": -1,
"selected": false,
"text": "<p>I got pretty fed up with trying to do this without modifying solution or project files so I came up with the following:</p>\n<ul>\n<li>Create empty file as part of build e.g. <code>feature_flag.h</code></li>\n<li>Replace <code>#if FEATURE_FLAG</code> with <code>#if !__has_include("feature_flag.h")</code></li>\n<li>Remove <code>feature_flag.h</code> at the end of the build</li>\n</ul>\n<p>It's not using #define but it does use the preprocessor which was what I needed.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
] |
In a C++ file, I have a code like this:
```
#if ACTIVATE
# pragma message( "Activated" )
#else
# pragma message( "Not Activated")
#endif
```
I want to set this ACTIVE define to 1 with the msbuild command line.
It tried this but it doesn't work:
```
msbuild /p:DefineConstants="ACTIVATE=1"
```
Any idea?
|
The answer is : YOU CANNOT
|
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": "<p>There's no way other than using URL rewriting (mod_rewrite) or creating the missing pages. What's happening is that the client requests a page which doesn't exist. Apache is configured to serve a special page upon 404 errors, but it still sends the 404 status code, then AVG traps that.</p>\n\n<p>So, you could do something like:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{REQUEST_URI} !-f\nRewriteCond %{REQUEST_URI} !-d\nRewriteRule (.*) index.php?missing_content=$1\n</code></pre>\n\n<p>That will rewrite everything that doesn't exist (and would thus give a 404) to your index.php with the URL path in the missing_content query string parameter </p>\n"
},
{
"answer_id": 166498,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 2,
"selected": false,
"text": "<p>If what you get is a <em>Page Not Found</em> error, <strong>don't</strong> make it send Status 200 OK. Please.</p>\n\n<p>It's one of most annoying \"tricks\" people do for whatever reason. If the page user requests does not exist, tell this to him, as well as to his browser. And to search engines, that otherwise will crawl/cache your custom error-page thinking it's the actual response.</p>\n\n<p>If someone has some software installed that displays something else instead of your 404, it's his own problem and don't try to fight it making your service lie to the browser :)</p>\n"
},
{
"answer_id": 10245685,
"author": "TRiG",
"author_id": 209139,
"author_profile": "https://Stackoverflow.com/users/209139",
"pm_score": 0,
"selected": false,
"text": "<p>Some browsers don't display the content of 404 pages if that content is quite small. If there's larger page content they do display it. This rule varies per browser. Try adding more content to your 404 page and see whether that helps.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726/"
] |
I have a website which uses the custom 404 error handling in PHP/Apache to display specific pages.
e.g. <http://metachat.org/recent>
I've a feeling this is a bad way of doing this, but it's code I inherited...
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.
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...
```
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
```
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?
Thanks.
|
There's no way other than using URL rewriting (mod\_rewrite) or creating the missing pages. What's happening is that the client requests a page which doesn't exist. Apache is configured to serve a special page upon 404 errors, but it still sends the 404 status code, then AVG traps that.
So, you could do something like:
```
RewriteEngine On
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteRule (.*) index.php?missing_content=$1
```
That will rewrite everything that doesn't exist (and would thus give a 404) to your index.php with the URL path in the missing\_content query string parameter
|
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": "<p>Are you wanting this to be reactive? Or, on-demand?</p>\n\n<p>For reactive, see <a href=\"http://svnbook.red-bean.com/en/1.0/svn-book.html#svn-ch-5-sect-2.1\" rel=\"nofollow noreferrer\">hooks</a>. The script will have to be named according to it's purpose: <strong>pre-commit.bat</strong>, <strong>post-commit.bat</strong>. The scripts are called as: <strong>[script] [repos-path] [revision-number]</strong></p>\n\n<p>For, on-demand:</p>\n\n<ul>\n<li>Working Copy\n\n<ul>\n<li><strong>svn log</strong></li>\n<li><strong>svn st</strong></li>\n<li><strong>svn diff</strong></li>\n<li><strong>svn proplist</strong></li>\n</ul></li>\n<li>Repository\n\n<ul>\n<li><strong>svnlook author</strong></li>\n<li><strong>svnlook changed</strong></li>\n<li><strong>svnlook date</strong></li>\n<li><strong>svnlook diff</strong></li>\n<li><strong>svnlook history</strong></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Example:</p>\n\n<pre><code>svn st \"C:\\path\\to\\working\\directory\\\" >> C:\\path\\to\\working\\project.log\n</code></pre>\n\n<p>Every time you run the BAT, it'll add the <strong>st</strong> output to <strong>project.log</strong>. Adjust as needed.</p>\n"
},
{
"answer_id": 166662,
"author": "Tooony",
"author_id": 23864,
"author_profile": "https://Stackoverflow.com/users/23864",
"pm_score": 4,
"selected": true,
"text": "<p>For Win 2000 and later, this would assign the last output row from the svn status commmand to the svnOut variable and then test if the variable contains anything:</p>\n\n<pre><code>@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</code></pre>\n\n<p>Why there is a line like this</p>\n\n<pre><code>set svnOut=\n</code></pre>\n\n<p>you have to figure out yourself. ;-)</p>\n"
},
{
"answer_id": 167362,
"author": "acemtp",
"author_id": 6605,
"author_profile": "https://Stackoverflow.com/users/6605",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, the solution I found with the help of Tooony:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 171086,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 2,
"selected": false,
"text": "<p>Have your .bat execute <code>svnversion</code> (if you're using Subversion) or <code>SvnWCRev.exe</code> (if you're using TortoiseSVN) against the top-most level of your working copy.</p>\n\n<p>Both output if your working copy has been modified.</p>\n\n<p><code>svnversion</code> appends a \"M\" to its output.\n<code>SvnWCRev.exe</code> will print a line of text that the WC has been modified.</p>\n"
},
{
"answer_id": 40875217,
"author": "Bryan Legend",
"author_id": 52771,
"author_profile": "https://Stackoverflow.com/users/52771",
"pm_score": 0,
"selected": false,
"text": "<p>This version is based on @tooony's but checks the server for updates instead of the client.</p>\n\n<pre><code>@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</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
] |
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).
|
For Win 2000 and later, this would assign the last output row from the svn status commmand to the svnOut variable and then test if the variable contains anything:
```
@echo off
set svnOut=
set svnDir=C:Your\path\to\svn\dir\to\check
for /F "tokens=*" %%I in ('svn status %svnDir%') do set svnOut=%%I
if "%svnOut%"=="" (
echo No changes
) else (
echo Changed files!
)
```
Why there is a line like this
```
set svnOut=
```
you have to figure out yourself. ;-)
|
166,493 |
<p>I have a Windows executable (say <code>program.exe</code>) and I want to provide users with 2 launchers that will pass different arguments to it.</p>
<pre><code>program.exe -a
program.exe -b
</code></pre>
<p>I can easily do this with 2 batch files, but I would rather provide users with 2 .exe files as they are more likely to be used correctly without editing.</p>
<p>Is there an easy way to create such an executable?</p>
|
[
{
"answer_id": 166507,
"author": "stevechol",
"author_id": 2981,
"author_profile": "https://Stackoverflow.com/users/2981",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using .Net you can read the information presented as parameters from another application or batch file. It's part of the Framework. Here it is is VB.NET</p>\n\n<p>For Each Arg As String In Environment.GetCommandLineArgs()\n //Process the arguments\nNext Arg</p>\n"
},
{
"answer_id": 166510,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 0,
"selected": false,
"text": "<p>You might try this: <a href=\"http://www.abyssmedia.com/quickbfc/\" rel=\"nofollow noreferrer\">http://www.abyssmedia.com/quickbfc/</a></p>\n\n<p>If you want something really, really small, you'd probably need to make your own Pascal/C program. I suggest Pascal because there is a very <a href=\"http://www.freepascal.org/\" rel=\"nofollow noreferrer\">nice free compiler</a> that produces really small .EXEs without the need to used a tweaked library (that would be the <em>only</em> C shortcoming in this case).</p>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 166511,
"author": "RomanM",
"author_id": 14587,
"author_profile": "https://Stackoverflow.com/users/14587",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if its exactly what your trying to do but check <a href=\"https://stackoverflow.com/questions/130664/combining-two-executables\">this</a> for possible solutions.</p>\n\n<p>That answers the question in the title, as for what you write here, why dont you just parse the arguments and depending on them have the two functionalities inside one executable ?</p>\n"
},
{
"answer_id": 166528,
"author": "Matthew Dresser",
"author_id": 15613,
"author_profile": "https://Stackoverflow.com/users/15613",
"pm_score": 2,
"selected": false,
"text": "<p>Why create new executables?\nWhy not just create desktop shortcuts to launch the single exe.</p>\n"
},
{
"answer_id": 166601,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 0,
"selected": false,
"text": "<p>If you have the source code to your application, you can change its behavior based on the name of the executable. It's not hard - in main, look at argv[0] and change the options based on that.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18333/"
] |
I have a Windows executable (say `program.exe`) and I want to provide users with 2 launchers that will pass different arguments to it.
```
program.exe -a
program.exe -b
```
I can easily do this with 2 batch files, but I would rather provide users with 2 .exe files as they are more likely to be used correctly without editing.
Is there an easy way to create such an executable?
|
Why create new executables?
Why not just create desktop shortcuts to launch the single exe.
|
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": "<pre><code>import socket\nsocket.gethostbyname(socket.gethostname())\n</code></pre>\n\n<p>This won't work always (returns <code>127.0.0.1</code> on machines having the hostname in <code>/etc/hosts</code> as <code>127.0.0.1</code>), a paliative would be what gimel shows, use <code>socket.getfqdn()</code> instead. Of course your machine needs a resolvable hostname.</p>\n"
},
{
"answer_id": 166521,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<p>I'm afraid there aren't any good platform independent ways to do this other than connecting to another computer and having it send you your IP address. For example: <a href=\"http://www.findmyipaddress.info/locateipaddresses.html\" rel=\"noreferrer\">findmyipaddress</a>. Note that this won't work if you need an IP address that's behind NAT unless the computer you're connecting to is behind NAT as well.</p>\n\n<p>Here's one solution that works in Linux: <a href=\"http://code.activestate.com/recipes/439094/\" rel=\"noreferrer\">get the IP address associated with a network interface</a>.</p>\n"
},
{
"answer_id": 166589,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 9,
"selected": false,
"text": "<p>I just found this but it seems a bit hackish, however they say tried it on *nix and I did on windows and it worked.</p>\n\n<pre><code>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</code></pre>\n\n<p>This assumes you have an internet access, and that there is no local proxy.</p>\n"
},
{
"answer_id": 166591,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 7,
"selected": false,
"text": "<p>You can use the <a href=\"http://pypi.python.org/pypi/netifaces\" rel=\"noreferrer\">netifaces</a> module. Just type:</p>\n\n<pre><code>pip install netifaces\n</code></pre>\n\n<p>in your command shell and it will install itself on default Python installation.</p>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>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</code></pre>\n\n<p>On my computer it printed:</p>\n\n<pre>{45639BDC-1050-46E0-9BE9-075C30DE1FBC}: 192.168.0.100\n{D43A468B-F3AE-4BF9-9391-4863A4500583}: 10.5.9.207</pre>\n\n<p>Author of this module claims it should work on Windows, UNIX and Mac OS X.</p>\n"
},
{
"answer_id": 166992,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 5,
"selected": false,
"text": "<p><strong>[Windows only]</strong> If you don't want to use external packages and don't want to rely on outside Internet servers, this might help. It's a code sample that I found on <a href=\"http://www.google.com/codesearch?hl=en&lr=&q=getMACAddrWin&sbtn=Search\" rel=\"nofollow noreferrer\">Google Code Search</a> and modified to return required information:</p>\n<pre><code>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</code></pre>\n<p>Usage:</p>\n<pre><code>>>> for addr in getIPAddresses():\n>>> print addr\n192.168.0.100\n10.5.9.207\n</code></pre>\n<p>As it relies on <code>windll</code>, this will work only on Windows.</p>\n"
},
{
"answer_id": 1267524,
"author": "Alexander",
"author_id": 131264,
"author_profile": "https://Stackoverflow.com/users/131264",
"pm_score": 7,
"selected": false,
"text": "<p><strong>As an alias called <code>myip</code>:</strong></p>\n<pre><code>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</code></pre>\n<ul>\n<li>Works correctly with Python 2.x, Python 3.x, modern and old Linux distros, OSX/macOS and Windows for finding the current IPv4 address.</li>\n<li>Will not return the correct result for machines with multiple IP addresses, IPv6, no configured IP address or no internet access.</li>\n<li>Reportedly, this does not work on the latest releases of macOS.</li>\n</ul>\n<p><strong>NOTE</strong>: If you intend to use something like this within a Python program, the proper way is to make use of a Python module that has IPv6 support.</p>\n<hr />\n<p><strong>Same as above, but only the Python code:</strong></p>\n\n<pre><code>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</code></pre>\n<ul>\n<li>This will throw an exception if no IP address is configured.</li>\n</ul>\n<hr />\n<p><strong>Version that will also work on LANs without an internet connection:</strong></p>\n\n<pre><code>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</code></pre>\n<p>(thanks <a href=\"https://stackoverflow.com/users/191246/ccpizza\">@ccpizza</a>)</p>\n<hr />\n<p><strong>Background</strong>:</p>\n<p>Using <code>socket.gethostbyname(socket.gethostname())</code> did not work here, because one of the computers I was on had an <code>/etc/hosts</code> with duplicate entries and references to itself. <code>socket.gethostbyname()</code> only returns the last entry in <code>/etc/hosts</code>.</p>\n<p>This was my initial attempt, which weeds out all addresses starting with <code>"127."</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import socket\nprint([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])\n</code></pre>\n<p>This works with Python 2 and 3, on Linux and Windows, but does not deal with several network devices or IPv6. However, it stopped working on recent Linux distros, so I tried this alternative technique instead. It tries to connect to the Google DNS server at <code>8.8.8.8</code> at port <code>53</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>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</code></pre>\n<p>Then I combined the two above techniques into a one-liner that should work everywhere, and created the <code>myip</code> alias and Python snippet at the top of this answer.</p>\n<p>With the increasing popularity of IPv6, and for servers with multiple network interfaces, using a third-party Python module for finding the IP address is probably both more robust and reliable than any of the methods listed here.</p>\n"
},
{
"answer_id": 1947766,
"author": "smerlin",
"author_id": 231717,
"author_profile": "https://Stackoverflow.com/users/231717",
"pm_score": 5,
"selected": false,
"text": "<p>im using following module:</p>\n\n<pre><code>#!/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</code></pre>\n\n<p>Tested with windows and linux (and doesnt require additional modules for those)\nintended for use on systems which are in a single IPv4 based LAN.</p>\n\n<p>The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by <a href=\"https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib/1947766?noredirect=1#comment35654143_1947766\">Alexander</a>.\nIn such cases, you need to manually replace the list with the interface names on your system, or use another solution like <a href=\"http://alastairs-place.net/projects/netifaces/\" rel=\"noreferrer\">netifaces</a>.</p>\n"
},
{
"answer_id": 1980854,
"author": "gavaletz",
"author_id": 240954,
"author_profile": "https://Stackoverflow.com/users/240954",
"pm_score": 3,
"selected": false,
"text": "<p>FYI I can verify that the method:</p>\n\n<pre><code>import socket\naddr = socket.gethostbyname(socket.gethostname())\n</code></pre>\n\n<p>Works in OS X (10.6,10.5), Windows XP, and on a well administered RHEL department server. It did not work on a very minimal CentOS VM that I just do some kernel hacking on. So for that instance you can just check for a 127.0.0.1 address and in that case do the following:</p>\n\n<pre><code>if addr == \"127.0.0.1\":\n import commands\n output = commands.getoutput(\"/sbin/ifconfig\")\n addr = parseaddress(output)\n</code></pre>\n\n<p>And then parse the ip address from the output. It should be noted that ifconfig is not in a normal user's PATH by default and that is why I give the full path in the command. I hope this helps.</p>\n"
},
{
"answer_id": 3177266,
"author": "shino",
"author_id": 244843,
"author_profile": "https://Stackoverflow.com/users/244843",
"pm_score": 5,
"selected": false,
"text": "<p>I use this on my ubuntu machines:</p>\n\n<pre><code>import commands\ncommands.getoutput(\"/sbin/ifconfig\").split(\"\\n\")[1].split()[1][5:]\n</code></pre>\n\n<p>This doesn't work.</p>\n"
},
{
"answer_id": 5111878,
"author": "Kulbir Saini",
"author_id": 625510,
"author_profile": "https://Stackoverflow.com/users/625510",
"pm_score": 2,
"selected": false,
"text": "<p>For a list of IP addresses on *nix systems,</p>\n\n<pre><code>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</code></pre>\n\n<p>Though it's a bit late for this answer, I thought someone else may find it useful :-)</p>\n\n<p>PS : It'll return Broadcast addresses and Netmask as well.</p>\n"
},
{
"answer_id": 6327620,
"author": "viker",
"author_id": 795536,
"author_profile": "https://Stackoverflow.com/users/795536",
"pm_score": 3,
"selected": false,
"text": "<p>One simple way to produce \"clean\" output via command line utils:</p>\n\n<pre><code>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</code></pre>\n\n<p>It will show all IPv4 addresses on the system.</p>\n"
},
{
"answer_id": 6452999,
"author": "ddewaele",
"author_id": 492410,
"author_profile": "https://Stackoverflow.com/users/492410",
"pm_score": 0,
"selected": false,
"text": "<p>A machine can have multiple network interfaces (including the local loopback 127.0.0.1) you mentioned. As far as the OS is concerned, it's also a \"real IP address\". </p>\n\n<p>If you want to track all of interfaces, have a look at the following Puthon package : <a href=\"http://alastairs-place.net/netifaces/\" rel=\"nofollow\">http://alastairs-place.net/netifaces/</a></p>\n\n<p>I think you can avoid having gethostbyname return 127.0.0.1 if you ommit the loopback entry from your hosts file. (to be verified).</p>\n"
},
{
"answer_id": 6453024,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 2,
"selected": false,
"text": "<p><code>127.0.1.1</code> <em>is</em> your real IP address. More generally speaking, a computer can have any number of IP addresses. You can filter them for private networks - 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.</p>\n\n<p>However, there is no cross-platform way to get all IP addresses. On Linux, you can use the <a href=\"http://linux.die.net/man/7/netdevice\" rel=\"nofollow\"><code>SIOCGIFCONF</code></a> ioctl.</p>\n"
},
{
"answer_id": 6453053,
"author": "ninjagecko",
"author_id": 711085,
"author_profile": "https://Stackoverflow.com/users/711085",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Socket API method</strong></p>\n\n<p>see <a href=\"https://stackoverflow.com/a/28950776/711085\">https://stackoverflow.com/a/28950776/711085</a></p>\n\n<p>Downsides:</p>\n\n<ul>\n<li><em>Not cross-platform.</em></li>\n<li>Requires more fallback code, tied to existence of particular addresses on the internet</li>\n<li>This will also not work if you're behind a NAT</li>\n<li>Probably creates a UDP connection, not independent of (usually ISP's) DNS availability (see other answers for ideas like using 8.8.8.8: Google's (coincidentally also DNS) server)</li>\n<li>Make sure you make the destination address UNREACHABLE, like a numeric IP address that is spec-guaranteed to be unused. Do NOT use some domain like fakesubdomain.google.com or somefakewebsite.com; you'll still be spamming that party (now or in the future), and spamming your own network boxes as well in the process.</li>\n</ul>\n\n<hr>\n\n<p><strong>Reflector method</strong></p>\n\n<p>(Do note that this does not answer the OP's question of the local IP address, e.g. 192.168...; it gives you your public IP address, which might be more desirable depending on use case.)</p>\n\n<p>You can query some site like whatismyip.com (but with an API), such as:</p>\n\n<pre><code>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</code></pre>\n\n<p>or if using python2:</p>\n\n<pre><code>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</code></pre>\n\n<p>Advantages:</p>\n\n<ul>\n<li>One upside of this method is it's cross-platform</li>\n<li>It works from behind ugly NATs (e.g. your home router).</li>\n</ul>\n\n<p>Disadvantages (and workarounds):</p>\n\n<ul>\n<li>Requires this website to be up, the format to not change (almost certainly won't), and your DNS servers to be working. One can mitigate this issue by also querying other third-party IP address reflectors in case of failure.</li>\n<li>Possible attack vector if you don't query multiple reflectors (to prevent a compromised reflector from telling you that your address is something it's not), or if you don't use HTTPS (to prevent a man-in-the-middle attack pretending to be the server)</li>\n</ul>\n\n<hr>\n\n<p><em>edit</em>: Though initially I thought these methods were really bad (unless you use many fallbacks, the code may be irrelevant many years from now), it does pose the question \"what is the internet?\". A computer may have many interfaces pointing to many different networks. For a more thorough description of the topic, google for <code>gateways and routes</code>. A computer may be able to access an internal network via an internal gateway, or access the world-wide web via a gateway on for example a router (usually the case). The local IP address that the OP asks about is only well-defined with respect to a single link layer, so you have to specify that (\"is it the network card, or the ethernet cable, which we're talking about?\"). There may be multiple non-unique answers to this question as posed. However the global IP address on the world-wide web is probably well-defined (in the absence of massive network fragmentation): probably the return path via the gateway which can access the TLDs.</p>\n"
},
{
"answer_id": 9267833,
"author": "tMC",
"author_id": 592851,
"author_profile": "https://Stackoverflow.com/users/592851",
"pm_score": 5,
"selected": false,
"text": "<p>On Linux:</p>\n\n<pre><code>>>> 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</code></pre>\n"
},
{
"answer_id": 10192097,
"author": "snakebarber",
"author_id": 688589,
"author_profile": "https://Stackoverflow.com/users/688589",
"pm_score": 1,
"selected": false,
"text": "<p>Ok so this is Windows specific, and requires the installation of the <a href=\"http://timgolden.me.uk/python/wmi/index.html\" rel=\"nofollow\">python WMI module</a>, but it seems much less hackish than constantly trying to call an external server. It's just another option, as there are already many good ones, but it might be a good fit for your project.</p>\n\n<pre><code>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</code></pre>\n\n<p>By the way, WMI is very powerful... if you are doing any remote admin of window machines you should definitely check out what it can do.</p>\n"
},
{
"answer_id": 10325724,
"author": "Etienne Perot",
"author_id": 109696,
"author_profile": "https://Stackoverflow.com/users/109696",
"pm_score": 2,
"selected": false,
"text": "<p>I had to solve the problem \"Figure out if an IP address is local or not\", and my first thought was to build a list of IPs that were local and then match against it. This is what led me to this question. However, I later realized there is a more straightfoward way to do it: Try to bind on that IP and see if it works.</p>\n\n<pre><code>_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</code></pre>\n\n<p>I know this doesn't answer the question directly, but this should be helpful to anyone trying to solve the related question and who was following the same train of thought. This has the advantage of being a cross-platform solution (I think).</p>\n"
},
{
"answer_id": 10350424,
"author": "fccoelho",
"author_id": 34747,
"author_profile": "https://Stackoverflow.com/users/34747",
"pm_score": 3,
"selected": false,
"text": "<p>This will work on most linux boxes:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 10377262,
"author": "Ben Last",
"author_id": 661571,
"author_profile": "https://Stackoverflow.com/users/661571",
"pm_score": 2,
"selected": false,
"text": "<p>A slight refinement of the commands version that uses the IP command, and returns IPv4 and IPv6 addresses:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 10946468,
"author": "Oink",
"author_id": 422242,
"author_profile": "https://Stackoverflow.com/users/422242",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import socket\nsocket.gethostbyname(socket.getfqdn())\n</code></pre>\n"
},
{
"answer_id": 10992813,
"author": "WolfRage",
"author_id": 1450678,
"author_profile": "https://Stackoverflow.com/users/1450678",
"pm_score": 3,
"selected": false,
"text": "<p>This answer is my personal attempt to solve the problem of getting the LAN IP, since <code>socket.gethostbyname(socket.gethostname())</code> also returned 127.0.0.1. This method does not require Internet just a LAN connection. Code is for Python 3.x but could easily be converted for 2.x. Using UDP Broadcast:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 16412954,
"author": "Nakilon",
"author_id": 322020,
"author_profile": "https://Stackoverflow.com/users/322020",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import socket\n[i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)]\n</code></pre>\n"
},
{
"answer_id": 18542718,
"author": "Artur Barseghyan",
"author_id": 2318839,
"author_profile": "https://Stackoverflow.com/users/2318839",
"pm_score": 2,
"selected": false,
"text": "<p>Note: This is not using the standard library, but quite simple.</p>\n\n<p>$ pip install pif</p>\n\n<pre><code>from pif import get_public_ip\nget_public_ip()\n</code></pre>\n"
},
{
"answer_id": 20275076,
"author": "DarkXDroid",
"author_id": 2179483,
"author_profile": "https://Stackoverflow.com/users/2179483",
"pm_score": 2,
"selected": false,
"text": "<p>Well you can use the command \"ip route\" on GNU/Linux to know your current IP address.</p>\n\n<p>This shows the IP given to the interface by the DHCP server running on the router/modem. Usually \"192.168.1.1/24\" is the IP for local network where \"24\" means the range of posible IP addresses given by the DHCP server within the mask range.</p>\n\n<p>Here's an example: Note that PyNotify is just an addition to get my point straight and is not required at all</p>\n\n<pre><code>#! /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</code></pre>\n\n<p>The advantage of this is that you don't need to specify the network interface. That's pretty useful when running a socket server</p>\n\n<p>You can install PyNotify using easy_install or even Pip:</p>\n\n<pre><code>easy_install py-notify\n</code></pre>\n\n<p>or</p>\n\n<pre><code>pip install py-notify\n</code></pre>\n\n<p>or within python script/interpreter</p>\n\n<pre><code>from pip import main\n\nmain(['install', 'py-notify'])\n</code></pre>\n"
},
{
"answer_id": 20312936,
"author": "Matt",
"author_id": 3054551,
"author_profile": "https://Stackoverflow.com/users/3054551",
"pm_score": -1,
"selected": false,
"text": "<p>Simple yet sweet!</p>\n\n<pre><code>def getip():\n\n import socket\n hostname= socket.gethostname()\n ip=socket.gethostbyname(hostname)\n\n return(ip)\n</code></pre>\n"
},
{
"answer_id": 20710035,
"author": "Eli Collins",
"author_id": 681277,
"author_profile": "https://Stackoverflow.com/users/681277",
"pm_score": 3,
"selected": false,
"text": "<p>This is a variant of UnkwnTech's answer -- it provides a <code>get_local_addr()</code> function, which returns the primary LAN ip address of the host. I'm posting it because this adds a number of things: ipv6 support, error handling, ignoring localhost/linklocal addrs, and uses a TESTNET addr (rfc5737) to connect to.</p>\n\n<pre><code># 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</code></pre>\n"
},
{
"answer_id": 23822431,
"author": "dlm",
"author_id": 748925,
"author_profile": "https://Stackoverflow.com/users/748925",
"pm_score": 5,
"selected": false,
"text": "<p>Variation on ninjagecko's answer. This should work on any LAN that allows UDP broadcast and doesn't require access to an address on the LAN or internet.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 24171358,
"author": "user3712955",
"author_id": 3712955,
"author_profile": "https://Stackoverflow.com/users/3712955",
"pm_score": 2,
"selected": false,
"text": "<p>netifaces is available via pip and easy_install. (I know, it's not in base, but it could be worth the install.)</p>\n\n<p>netifaces does have some oddities across platforms:</p>\n\n<ul>\n<li>The localhost/loop-back interface may not always be included (Cygwin).</li>\n<li>Addresses are listed per-protocol (e.g., IPv4, IPv6) and protocols are listed per-interface. On some systems (Linux) each protocol-interface pair has its own associated interface (using the interface_name:n notation) while on other systems (Windows) a single interface will have a list of addresses for each protocol. In both cases there is a protocol list, but it may contain only a single element.</li>\n</ul>\n\n<p>Here's some netifaces code to play with:</p>\n\n<pre><code>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</code></pre>\n\n<p>The above code doesn't map an address back to its interface name (useful for generating ebtables/iptables rules on the fly). So here's a version that keeps the above information with the interface name in a tuple:</p>\n\n<pre><code>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</code></pre>\n\n<p>And, no, I'm not in love with list comprehensions. It's just the way my brain works these days.</p>\n\n<p>The following snippet will print it all out:</p>\n\n<pre><code>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</code></pre>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 24564613,
"author": "www-0av-Com",
"author_id": 1863152,
"author_profile": "https://Stackoverflow.com/users/1863152",
"pm_score": 4,
"selected": false,
"text": "<p>On Debian (tested) and I suspect most Linux's..</p>\n\n<pre><code>import commands\n\nRetMyIP = commands.getoutput(\"hostname -I\")\n</code></pre>\n\n<p>On MS Windows (tested) </p>\n\n<pre><code>import socket\n\nsocket.gethostbyname(socket.gethostname())\n</code></pre>\n"
},
{
"answer_id": 25850698,
"author": "Collin Anderson",
"author_id": 131881,
"author_profile": "https://Stackoverflow.com/users/131881",
"pm_score": 6,
"selected": false,
"text": "<p>If the computer has a route to the Internet, this will <em>always</em> work to get the preferred local ip address, even if /etc/hosts is not set correctly.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 27788672,
"author": "Graham Chap",
"author_id": 3842040,
"author_profile": "https://Stackoverflow.com/users/3842040",
"pm_score": 4,
"selected": false,
"text": "<p>A version I do not believe that has been posted yet. \nI tested with python 2.7 on Ubuntu 12.04.</p>\n\n<p>Found this solution at : <a href=\"http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/\" rel=\"noreferrer\">http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/</a></p>\n\n<pre><code>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</code></pre>\n\n<p>Example Result:</p>\n\n<pre><code>>>> get_ip_address('eth0')\n'38.113.228.130'\n</code></pre>\n"
},
{
"answer_id": 28950776,
"author": "fatal_error",
"author_id": 1301627,
"author_profile": "https://Stackoverflow.com/users/1301627",
"pm_score": 9,
"selected": false,
"text": "<p><strong>This method returns the "primary" IP on the local box (the one with a default route)</strong>.</p>\n<ul>\n<li>Does NOT need routable net access or any connection at all.</li>\n<li>Works even if all interfaces are unplugged from the network.</li>\n<li>Does NOT need or even try to get <em>anywhere else</em>.</li>\n<li>Works with NAT, public, private, external, and internal IP's</li>\n<li>Pure Python 2 (or 3) with no external dependencies.</li>\n<li>Works on Linux, Windows, and OSX.</li>\n</ul>\n<p>Python 3 or 2:</p>\n<pre class=\"lang-py prettyprint-override\"><code> 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</code></pre>\n<p>This returns a single IP which is the primary (the one with a default route). If you need instead all IP's attached to all interfaces (including localhost, etc), see something like <a href=\"https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib/24564613#24564613\">this answer</a>.</p>\n<p>If you are behind a NAT firewall like your wifi router at home, then this will not show your public NAT IP, but instead your private IP on the local network which has a default route to your local WIFI router. If you instead need your external IP:</p>\n<ul>\n<li><p>running this function on THAT external device (wifi router), or</p>\n</li>\n<li><p>connecting to an external service such as <a href=\"https://www.ipify.org/\" rel=\"noreferrer\">https://www.ipify.org/</a> that could reflect back the IP as it's seen from the outside world</p>\n</li>\n</ul>\n<p>... but those ideas are completely different from the original question. :)</p>\n"
},
{
"answer_id": 29931604,
"author": "LRund",
"author_id": 4713795,
"author_profile": "https://Stackoverflow.com/users/4713795",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't very Pythonic, but it works reliably on Windows.</p>\n\n<pre><code>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</code></pre>\n\n<p>Yeah, it's a hack, but at times I don't feel like second-guessing an operating system, and just go ahead and use what's built-in and works.</p>\n"
},
{
"answer_id": 36446068,
"author": "Frederik Aalund",
"author_id": 554283,
"author_profile": "https://Stackoverflow.com/users/554283",
"pm_score": 2,
"selected": false,
"text": "<p>A Python 3.4 version utilizing the newly introduced asyncio package.</p>\n<pre class=\"lang-py prettyprint-override\"><code>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</code></pre>\n<p>This is based on UnkwnTech's <a href=\"https://stackoverflow.com/a/166589/554283\">excellent answer</a>.</p>\n"
},
{
"answer_id": 37618645,
"author": "RiccardoCh",
"author_id": 2000573,
"author_profile": "https://Stackoverflow.com/users/2000573",
"pm_score": 2,
"selected": false,
"text": "<p>To get the ip address you can use a <em>shell command</em> directly in <strong>python</strong>:</p>\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 38814772,
"author": "Apalala",
"author_id": 545637,
"author_profile": "https://Stackoverflow.com/users/545637",
"pm_score": -1,
"selected": false,
"text": "<p>I settled for using the service and/or API of <strong>ipfy</strong>: <a href=\"https://www.ipify.org\" rel=\"nofollow\">https://www.ipify.org</a>.</p>\n\n<pre><code>#!/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</code></pre>\n\n<p>The response can also be obtained in <em>JSON</em> and <em>JSONP</em> formats.</p>\n\n<p>There's an <strong>ipify</strong> <a href=\"https://github.com/rdegges/python-ipify\" rel=\"nofollow\">Python library</a> on Github.</p>\n"
},
{
"answer_id": 41002096,
"author": "Wyrmwood",
"author_id": 1368703,
"author_profile": "https://Stackoverflow.com/users/1368703",
"pm_score": -1,
"selected": false,
"text": "<p>This is very similar to previously posted answers, but I could not find any with this usage of calls. This is what I use for ipv4. For ipv6 change the '.' in to ':' in </p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 44581122,
"author": "Villiam",
"author_id": 7727270,
"author_profile": "https://Stackoverflow.com/users/7727270",
"pm_score": 0,
"selected": false,
"text": "<pre><code>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</code></pre>\n"
},
{
"answer_id": 45222755,
"author": "NandaKrishnan",
"author_id": 8318939,
"author_profile": "https://Stackoverflow.com/users/8318939",
"pm_score": -1,
"selected": false,
"text": "<pre><code>import socket\nprint(socket.gethostbyname(socket.getfqdn()))\n</code></pre>\n"
},
{
"answer_id": 48004756,
"author": "Ishwarya",
"author_id": 9148547,
"author_profile": "https://Stackoverflow.com/users/9148547",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import netifaces as ni \n\nni.ifaddresses('eth0')\nip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']\nprint(ip)\n</code></pre>\n\n<p>This will return you the IP address in the Ubuntu system as well as MacOS. The output will be the system IP address as like my IP: 192.168.1.10.</p>\n"
},
{
"answer_id": 49269943,
"author": "hmofrad",
"author_id": 5412470,
"author_profile": "https://Stackoverflow.com/users/5412470",
"pm_score": 3,
"selected": false,
"text": "<p>If you're looking for an IPV4 address different from your localhost IP address <code>127.0.0.1</code>, here is a neat piece of python codes:</p>\n\n<pre><code>import subprocess\naddress = subprocess.check_output(['hostname', '-s', '-I'])\naddress = address.decode('utf-8') \naddress=address[:-1]\n</code></pre>\n\n<p>Which can also be written in a single line:</p>\n\n<pre><code>address = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1]\n</code></pre>\n\n<p>Even if you put <code>localhost</code> in <code>/etc/hostname</code>, the code will still give your local IP address.</p>\n"
},
{
"answer_id": 55824993,
"author": "Compl Yue",
"author_id": 6394508,
"author_profile": "https://Stackoverflow.com/users/6394508",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another variant to previous answers, can be saved to an executable script named <code>my-ip-to</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/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</code></pre>\n\n<p>it takes any number of remote hosts, and print out local ips to reach them one by one:</p>\n\n<pre><code>$ my-ip-to z.cn g.cn localhost\n192.168.11.102\n192.168.11.102\n127.0.0.1\n$\n</code></pre>\n\n<p>And print best-bet when no arg is given.</p>\n\n<pre><code>$ my-ip-to\n192.168.11.102\n</code></pre>\n"
},
{
"answer_id": 55857821,
"author": "Romolo",
"author_id": 11412897,
"author_profile": "https://Stackoverflow.com/users/11412897",
"pm_score": 0,
"selected": false,
"text": "<p>For a linux env, read the /proc/net/tcp, the second (localaddress) and third (remoteaddress) will give the IPs at hexa format.</p>\n\n<p>Tip: If second column is zeroed (00000000:0000) so its a Listen Port :)</p>\n\n<p><a href=\"https://github.com/romol0s/python/blob/master/general/functions/getTcpListenIpsByPort.py\" rel=\"nofollow noreferrer\">https://github.com/romol0s/python/blob/master/general/functions/getTcpListenIpsByPort.py</a></p>\n\n<p><a href=\"https://www.kernel.org/doc/Documentation/networking/proc_net_tcp.txt\" rel=\"nofollow noreferrer\">https://www.kernel.org/doc/Documentation/networking/proc_net_tcp.txt</a></p>\n"
},
{
"answer_id": 57196643,
"author": "Kasper Skytte Andersen",
"author_id": 8575867,
"author_profile": "https://Stackoverflow.com/users/8575867",
"pm_score": 4,
"selected": false,
"text": "<p>For linux, you can just use <code>check_output</code> of the <code>hostname -I</code> system command like so:</p>\n\n<pre><code>from subprocess import check_output\ncheck_output(['hostname', '-I'])\n</code></pre>\n"
},
{
"answer_id": 60048761,
"author": "Josh",
"author_id": 10794945,
"author_profile": "https://Stackoverflow.com/users/10794945",
"pm_score": -1,
"selected": false,
"text": "<p>pyroute2 is a great library that can be used to obtain not just ip addresses but also gateway information and other useful information.\nThe following code can obtain the ipv4 address of any interface.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 65130655,
"author": "nikhil swami",
"author_id": 12179956,
"author_profile": "https://Stackoverflow.com/users/12179956",
"pm_score": 0,
"selected": false,
"text": "<h2>Windows solution, Take it or leave it.</h2>\n<p>gets only the self ip, on the current active wlan[wireless LAN] ie the computer's ip on the (wifi router or network switch).</p>\n<p>note: its not the public ip of the device and does not involve any external requests or packages or public apis.</p>\n<p>The core idea is to parse the output of <code>shell command: ipconfig</code>, or ifconfig on linux. we are using subprocess to acquire the output.</p>\n<pre><code>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</code></pre>\n<h2>this is what happens after CMD:'ipconfig' :</h2>\n<p>we get this output, we captured it in python using subprocess output.</p>\n<blockquote>\n<p>C:\\Users\\dell>ipconfig</p>\n</blockquote>\n<pre><code>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</code></pre>\n<p>and we parsed the string in python, in a manner that selects the wireless adapter's ip on current network.</p>\n"
},
{
"answer_id": 68378891,
"author": "Laurens",
"author_id": 3640844,
"author_profile": "https://Stackoverflow.com/users/3640844",
"pm_score": -1,
"selected": false,
"text": "<p>@fatal_error solution should be the accepted answer! this is an implementation of his solution in nodejs in case people need it:</p>\n<pre class=\"lang-js prettyprint-override\"><code>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</code></pre>\n"
},
{
"answer_id": 69369114,
"author": "TCB919",
"author_id": 8345316,
"author_profile": "https://Stackoverflow.com/users/8345316",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this easily on modern *NIX systems that have the <code>iproute2</code> utility by calling it via <code>subprocess.run()</code> as you can output in JSON with the <code>-j</code> switch and then use the <code>json.loads()</code> module and method to convert that to a python data structure. The following code displays the first non loopback IP address.</p>\n<pre><code>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</code></pre>\n<p>Alternativly if you had multiple IP's and wanted to find the IP that would be used to connect to a specific destination you could use <code>ip -j route get 8.8.8.8</code> like this:</p>\n<pre><code>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</code></pre>\n<p>If your looking for all IP addresses you can iterate through the list of dictionaries returned by <code>ip -j a</code></p>\n<pre><code>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</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
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?
|
```
import socket
socket.gethostbyname(socket.gethostname())
```
This won't work always (returns `127.0.0.1` on machines having the hostname in `/etc/hosts` as `127.0.0.1`), a paliative would be what gimel shows, use `socket.getfqdn()` instead. Of course your machine needs a resolvable hostname.
|
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": "<pre><code>import socket\nsocket.gethostbyname(socket.gethostname())\n</code></pre>\n\n<p>This won't work always (returns <code>127.0.0.1</code> on machines having the hostname in <code>/etc/hosts</code> as <code>127.0.0.1</code>), a paliative would be what gimel shows, use <code>socket.getfqdn()</code> instead. Of course your machine needs a resolvable hostname.</p>\n"
},
{
"answer_id": 166521,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<p>I'm afraid there aren't any good platform independent ways to do this other than connecting to another computer and having it send you your IP address. For example: <a href=\"http://www.findmyipaddress.info/locateipaddresses.html\" rel=\"noreferrer\">findmyipaddress</a>. Note that this won't work if you need an IP address that's behind NAT unless the computer you're connecting to is behind NAT as well.</p>\n\n<p>Here's one solution that works in Linux: <a href=\"http://code.activestate.com/recipes/439094/\" rel=\"noreferrer\">get the IP address associated with a network interface</a>.</p>\n"
},
{
"answer_id": 166589,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 9,
"selected": false,
"text": "<p>I just found this but it seems a bit hackish, however they say tried it on *nix and I did on windows and it worked.</p>\n\n<pre><code>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</code></pre>\n\n<p>This assumes you have an internet access, and that there is no local proxy.</p>\n"
},
{
"answer_id": 166591,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 7,
"selected": false,
"text": "<p>You can use the <a href=\"http://pypi.python.org/pypi/netifaces\" rel=\"noreferrer\">netifaces</a> module. Just type:</p>\n\n<pre><code>pip install netifaces\n</code></pre>\n\n<p>in your command shell and it will install itself on default Python installation.</p>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>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</code></pre>\n\n<p>On my computer it printed:</p>\n\n<pre>{45639BDC-1050-46E0-9BE9-075C30DE1FBC}: 192.168.0.100\n{D43A468B-F3AE-4BF9-9391-4863A4500583}: 10.5.9.207</pre>\n\n<p>Author of this module claims it should work on Windows, UNIX and Mac OS X.</p>\n"
},
{
"answer_id": 166992,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 5,
"selected": false,
"text": "<p><strong>[Windows only]</strong> If you don't want to use external packages and don't want to rely on outside Internet servers, this might help. It's a code sample that I found on <a href=\"http://www.google.com/codesearch?hl=en&lr=&q=getMACAddrWin&sbtn=Search\" rel=\"nofollow noreferrer\">Google Code Search</a> and modified to return required information:</p>\n<pre><code>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</code></pre>\n<p>Usage:</p>\n<pre><code>>>> for addr in getIPAddresses():\n>>> print addr\n192.168.0.100\n10.5.9.207\n</code></pre>\n<p>As it relies on <code>windll</code>, this will work only on Windows.</p>\n"
},
{
"answer_id": 1267524,
"author": "Alexander",
"author_id": 131264,
"author_profile": "https://Stackoverflow.com/users/131264",
"pm_score": 7,
"selected": false,
"text": "<p><strong>As an alias called <code>myip</code>:</strong></p>\n<pre><code>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</code></pre>\n<ul>\n<li>Works correctly with Python 2.x, Python 3.x, modern and old Linux distros, OSX/macOS and Windows for finding the current IPv4 address.</li>\n<li>Will not return the correct result for machines with multiple IP addresses, IPv6, no configured IP address or no internet access.</li>\n<li>Reportedly, this does not work on the latest releases of macOS.</li>\n</ul>\n<p><strong>NOTE</strong>: If you intend to use something like this within a Python program, the proper way is to make use of a Python module that has IPv6 support.</p>\n<hr />\n<p><strong>Same as above, but only the Python code:</strong></p>\n\n<pre><code>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</code></pre>\n<ul>\n<li>This will throw an exception if no IP address is configured.</li>\n</ul>\n<hr />\n<p><strong>Version that will also work on LANs without an internet connection:</strong></p>\n\n<pre><code>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</code></pre>\n<p>(thanks <a href=\"https://stackoverflow.com/users/191246/ccpizza\">@ccpizza</a>)</p>\n<hr />\n<p><strong>Background</strong>:</p>\n<p>Using <code>socket.gethostbyname(socket.gethostname())</code> did not work here, because one of the computers I was on had an <code>/etc/hosts</code> with duplicate entries and references to itself. <code>socket.gethostbyname()</code> only returns the last entry in <code>/etc/hosts</code>.</p>\n<p>This was my initial attempt, which weeds out all addresses starting with <code>"127."</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import socket\nprint([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])\n</code></pre>\n<p>This works with Python 2 and 3, on Linux and Windows, but does not deal with several network devices or IPv6. However, it stopped working on recent Linux distros, so I tried this alternative technique instead. It tries to connect to the Google DNS server at <code>8.8.8.8</code> at port <code>53</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>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</code></pre>\n<p>Then I combined the two above techniques into a one-liner that should work everywhere, and created the <code>myip</code> alias and Python snippet at the top of this answer.</p>\n<p>With the increasing popularity of IPv6, and for servers with multiple network interfaces, using a third-party Python module for finding the IP address is probably both more robust and reliable than any of the methods listed here.</p>\n"
},
{
"answer_id": 1947766,
"author": "smerlin",
"author_id": 231717,
"author_profile": "https://Stackoverflow.com/users/231717",
"pm_score": 5,
"selected": false,
"text": "<p>im using following module:</p>\n\n<pre><code>#!/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</code></pre>\n\n<p>Tested with windows and linux (and doesnt require additional modules for those)\nintended for use on systems which are in a single IPv4 based LAN.</p>\n\n<p>The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by <a href=\"https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib/1947766?noredirect=1#comment35654143_1947766\">Alexander</a>.\nIn such cases, you need to manually replace the list with the interface names on your system, or use another solution like <a href=\"http://alastairs-place.net/projects/netifaces/\" rel=\"noreferrer\">netifaces</a>.</p>\n"
},
{
"answer_id": 1980854,
"author": "gavaletz",
"author_id": 240954,
"author_profile": "https://Stackoverflow.com/users/240954",
"pm_score": 3,
"selected": false,
"text": "<p>FYI I can verify that the method:</p>\n\n<pre><code>import socket\naddr = socket.gethostbyname(socket.gethostname())\n</code></pre>\n\n<p>Works in OS X (10.6,10.5), Windows XP, and on a well administered RHEL department server. It did not work on a very minimal CentOS VM that I just do some kernel hacking on. So for that instance you can just check for a 127.0.0.1 address and in that case do the following:</p>\n\n<pre><code>if addr == \"127.0.0.1\":\n import commands\n output = commands.getoutput(\"/sbin/ifconfig\")\n addr = parseaddress(output)\n</code></pre>\n\n<p>And then parse the ip address from the output. It should be noted that ifconfig is not in a normal user's PATH by default and that is why I give the full path in the command. I hope this helps.</p>\n"
},
{
"answer_id": 3177266,
"author": "shino",
"author_id": 244843,
"author_profile": "https://Stackoverflow.com/users/244843",
"pm_score": 5,
"selected": false,
"text": "<p>I use this on my ubuntu machines:</p>\n\n<pre><code>import commands\ncommands.getoutput(\"/sbin/ifconfig\").split(\"\\n\")[1].split()[1][5:]\n</code></pre>\n\n<p>This doesn't work.</p>\n"
},
{
"answer_id": 5111878,
"author": "Kulbir Saini",
"author_id": 625510,
"author_profile": "https://Stackoverflow.com/users/625510",
"pm_score": 2,
"selected": false,
"text": "<p>For a list of IP addresses on *nix systems,</p>\n\n<pre><code>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</code></pre>\n\n<p>Though it's a bit late for this answer, I thought someone else may find it useful :-)</p>\n\n<p>PS : It'll return Broadcast addresses and Netmask as well.</p>\n"
},
{
"answer_id": 6327620,
"author": "viker",
"author_id": 795536,
"author_profile": "https://Stackoverflow.com/users/795536",
"pm_score": 3,
"selected": false,
"text": "<p>One simple way to produce \"clean\" output via command line utils:</p>\n\n<pre><code>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</code></pre>\n\n<p>It will show all IPv4 addresses on the system.</p>\n"
},
{
"answer_id": 6452999,
"author": "ddewaele",
"author_id": 492410,
"author_profile": "https://Stackoverflow.com/users/492410",
"pm_score": 0,
"selected": false,
"text": "<p>A machine can have multiple network interfaces (including the local loopback 127.0.0.1) you mentioned. As far as the OS is concerned, it's also a \"real IP address\". </p>\n\n<p>If you want to track all of interfaces, have a look at the following Puthon package : <a href=\"http://alastairs-place.net/netifaces/\" rel=\"nofollow\">http://alastairs-place.net/netifaces/</a></p>\n\n<p>I think you can avoid having gethostbyname return 127.0.0.1 if you ommit the loopback entry from your hosts file. (to be verified).</p>\n"
},
{
"answer_id": 6453024,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 2,
"selected": false,
"text": "<p><code>127.0.1.1</code> <em>is</em> your real IP address. More generally speaking, a computer can have any number of IP addresses. You can filter them for private networks - 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.</p>\n\n<p>However, there is no cross-platform way to get all IP addresses. On Linux, you can use the <a href=\"http://linux.die.net/man/7/netdevice\" rel=\"nofollow\"><code>SIOCGIFCONF</code></a> ioctl.</p>\n"
},
{
"answer_id": 6453053,
"author": "ninjagecko",
"author_id": 711085,
"author_profile": "https://Stackoverflow.com/users/711085",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Socket API method</strong></p>\n\n<p>see <a href=\"https://stackoverflow.com/a/28950776/711085\">https://stackoverflow.com/a/28950776/711085</a></p>\n\n<p>Downsides:</p>\n\n<ul>\n<li><em>Not cross-platform.</em></li>\n<li>Requires more fallback code, tied to existence of particular addresses on the internet</li>\n<li>This will also not work if you're behind a NAT</li>\n<li>Probably creates a UDP connection, not independent of (usually ISP's) DNS availability (see other answers for ideas like using 8.8.8.8: Google's (coincidentally also DNS) server)</li>\n<li>Make sure you make the destination address UNREACHABLE, like a numeric IP address that is spec-guaranteed to be unused. Do NOT use some domain like fakesubdomain.google.com or somefakewebsite.com; you'll still be spamming that party (now or in the future), and spamming your own network boxes as well in the process.</li>\n</ul>\n\n<hr>\n\n<p><strong>Reflector method</strong></p>\n\n<p>(Do note that this does not answer the OP's question of the local IP address, e.g. 192.168...; it gives you your public IP address, which might be more desirable depending on use case.)</p>\n\n<p>You can query some site like whatismyip.com (but with an API), such as:</p>\n\n<pre><code>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</code></pre>\n\n<p>or if using python2:</p>\n\n<pre><code>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</code></pre>\n\n<p>Advantages:</p>\n\n<ul>\n<li>One upside of this method is it's cross-platform</li>\n<li>It works from behind ugly NATs (e.g. your home router).</li>\n</ul>\n\n<p>Disadvantages (and workarounds):</p>\n\n<ul>\n<li>Requires this website to be up, the format to not change (almost certainly won't), and your DNS servers to be working. One can mitigate this issue by also querying other third-party IP address reflectors in case of failure.</li>\n<li>Possible attack vector if you don't query multiple reflectors (to prevent a compromised reflector from telling you that your address is something it's not), or if you don't use HTTPS (to prevent a man-in-the-middle attack pretending to be the server)</li>\n</ul>\n\n<hr>\n\n<p><em>edit</em>: Though initially I thought these methods were really bad (unless you use many fallbacks, the code may be irrelevant many years from now), it does pose the question \"what is the internet?\". A computer may have many interfaces pointing to many different networks. For a more thorough description of the topic, google for <code>gateways and routes</code>. A computer may be able to access an internal network via an internal gateway, or access the world-wide web via a gateway on for example a router (usually the case). The local IP address that the OP asks about is only well-defined with respect to a single link layer, so you have to specify that (\"is it the network card, or the ethernet cable, which we're talking about?\"). There may be multiple non-unique answers to this question as posed. However the global IP address on the world-wide web is probably well-defined (in the absence of massive network fragmentation): probably the return path via the gateway which can access the TLDs.</p>\n"
},
{
"answer_id": 9267833,
"author": "tMC",
"author_id": 592851,
"author_profile": "https://Stackoverflow.com/users/592851",
"pm_score": 5,
"selected": false,
"text": "<p>On Linux:</p>\n\n<pre><code>>>> 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</code></pre>\n"
},
{
"answer_id": 10192097,
"author": "snakebarber",
"author_id": 688589,
"author_profile": "https://Stackoverflow.com/users/688589",
"pm_score": 1,
"selected": false,
"text": "<p>Ok so this is Windows specific, and requires the installation of the <a href=\"http://timgolden.me.uk/python/wmi/index.html\" rel=\"nofollow\">python WMI module</a>, but it seems much less hackish than constantly trying to call an external server. It's just another option, as there are already many good ones, but it might be a good fit for your project.</p>\n\n<pre><code>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</code></pre>\n\n<p>By the way, WMI is very powerful... if you are doing any remote admin of window machines you should definitely check out what it can do.</p>\n"
},
{
"answer_id": 10325724,
"author": "Etienne Perot",
"author_id": 109696,
"author_profile": "https://Stackoverflow.com/users/109696",
"pm_score": 2,
"selected": false,
"text": "<p>I had to solve the problem \"Figure out if an IP address is local or not\", and my first thought was to build a list of IPs that were local and then match against it. This is what led me to this question. However, I later realized there is a more straightfoward way to do it: Try to bind on that IP and see if it works.</p>\n\n<pre><code>_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</code></pre>\n\n<p>I know this doesn't answer the question directly, but this should be helpful to anyone trying to solve the related question and who was following the same train of thought. This has the advantage of being a cross-platform solution (I think).</p>\n"
},
{
"answer_id": 10350424,
"author": "fccoelho",
"author_id": 34747,
"author_profile": "https://Stackoverflow.com/users/34747",
"pm_score": 3,
"selected": false,
"text": "<p>This will work on most linux boxes:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 10377262,
"author": "Ben Last",
"author_id": 661571,
"author_profile": "https://Stackoverflow.com/users/661571",
"pm_score": 2,
"selected": false,
"text": "<p>A slight refinement of the commands version that uses the IP command, and returns IPv4 and IPv6 addresses:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 10946468,
"author": "Oink",
"author_id": 422242,
"author_profile": "https://Stackoverflow.com/users/422242",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import socket\nsocket.gethostbyname(socket.getfqdn())\n</code></pre>\n"
},
{
"answer_id": 10992813,
"author": "WolfRage",
"author_id": 1450678,
"author_profile": "https://Stackoverflow.com/users/1450678",
"pm_score": 3,
"selected": false,
"text": "<p>This answer is my personal attempt to solve the problem of getting the LAN IP, since <code>socket.gethostbyname(socket.gethostname())</code> also returned 127.0.0.1. This method does not require Internet just a LAN connection. Code is for Python 3.x but could easily be converted for 2.x. Using UDP Broadcast:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 16412954,
"author": "Nakilon",
"author_id": 322020,
"author_profile": "https://Stackoverflow.com/users/322020",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import socket\n[i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)]\n</code></pre>\n"
},
{
"answer_id": 18542718,
"author": "Artur Barseghyan",
"author_id": 2318839,
"author_profile": "https://Stackoverflow.com/users/2318839",
"pm_score": 2,
"selected": false,
"text": "<p>Note: This is not using the standard library, but quite simple.</p>\n\n<p>$ pip install pif</p>\n\n<pre><code>from pif import get_public_ip\nget_public_ip()\n</code></pre>\n"
},
{
"answer_id": 20275076,
"author": "DarkXDroid",
"author_id": 2179483,
"author_profile": "https://Stackoverflow.com/users/2179483",
"pm_score": 2,
"selected": false,
"text": "<p>Well you can use the command \"ip route\" on GNU/Linux to know your current IP address.</p>\n\n<p>This shows the IP given to the interface by the DHCP server running on the router/modem. Usually \"192.168.1.1/24\" is the IP for local network where \"24\" means the range of posible IP addresses given by the DHCP server within the mask range.</p>\n\n<p>Here's an example: Note that PyNotify is just an addition to get my point straight and is not required at all</p>\n\n<pre><code>#! /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</code></pre>\n\n<p>The advantage of this is that you don't need to specify the network interface. That's pretty useful when running a socket server</p>\n\n<p>You can install PyNotify using easy_install or even Pip:</p>\n\n<pre><code>easy_install py-notify\n</code></pre>\n\n<p>or</p>\n\n<pre><code>pip install py-notify\n</code></pre>\n\n<p>or within python script/interpreter</p>\n\n<pre><code>from pip import main\n\nmain(['install', 'py-notify'])\n</code></pre>\n"
},
{
"answer_id": 20312936,
"author": "Matt",
"author_id": 3054551,
"author_profile": "https://Stackoverflow.com/users/3054551",
"pm_score": -1,
"selected": false,
"text": "<p>Simple yet sweet!</p>\n\n<pre><code>def getip():\n\n import socket\n hostname= socket.gethostname()\n ip=socket.gethostbyname(hostname)\n\n return(ip)\n</code></pre>\n"
},
{
"answer_id": 20710035,
"author": "Eli Collins",
"author_id": 681277,
"author_profile": "https://Stackoverflow.com/users/681277",
"pm_score": 3,
"selected": false,
"text": "<p>This is a variant of UnkwnTech's answer -- it provides a <code>get_local_addr()</code> function, which returns the primary LAN ip address of the host. I'm posting it because this adds a number of things: ipv6 support, error handling, ignoring localhost/linklocal addrs, and uses a TESTNET addr (rfc5737) to connect to.</p>\n\n<pre><code># 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</code></pre>\n"
},
{
"answer_id": 23822431,
"author": "dlm",
"author_id": 748925,
"author_profile": "https://Stackoverflow.com/users/748925",
"pm_score": 5,
"selected": false,
"text": "<p>Variation on ninjagecko's answer. This should work on any LAN that allows UDP broadcast and doesn't require access to an address on the LAN or internet.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 24171358,
"author": "user3712955",
"author_id": 3712955,
"author_profile": "https://Stackoverflow.com/users/3712955",
"pm_score": 2,
"selected": false,
"text": "<p>netifaces is available via pip and easy_install. (I know, it's not in base, but it could be worth the install.)</p>\n\n<p>netifaces does have some oddities across platforms:</p>\n\n<ul>\n<li>The localhost/loop-back interface may not always be included (Cygwin).</li>\n<li>Addresses are listed per-protocol (e.g., IPv4, IPv6) and protocols are listed per-interface. On some systems (Linux) each protocol-interface pair has its own associated interface (using the interface_name:n notation) while on other systems (Windows) a single interface will have a list of addresses for each protocol. In both cases there is a protocol list, but it may contain only a single element.</li>\n</ul>\n\n<p>Here's some netifaces code to play with:</p>\n\n<pre><code>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</code></pre>\n\n<p>The above code doesn't map an address back to its interface name (useful for generating ebtables/iptables rules on the fly). So here's a version that keeps the above information with the interface name in a tuple:</p>\n\n<pre><code>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</code></pre>\n\n<p>And, no, I'm not in love with list comprehensions. It's just the way my brain works these days.</p>\n\n<p>The following snippet will print it all out:</p>\n\n<pre><code>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</code></pre>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 24564613,
"author": "www-0av-Com",
"author_id": 1863152,
"author_profile": "https://Stackoverflow.com/users/1863152",
"pm_score": 4,
"selected": false,
"text": "<p>On Debian (tested) and I suspect most Linux's..</p>\n\n<pre><code>import commands\n\nRetMyIP = commands.getoutput(\"hostname -I\")\n</code></pre>\n\n<p>On MS Windows (tested) </p>\n\n<pre><code>import socket\n\nsocket.gethostbyname(socket.gethostname())\n</code></pre>\n"
},
{
"answer_id": 25850698,
"author": "Collin Anderson",
"author_id": 131881,
"author_profile": "https://Stackoverflow.com/users/131881",
"pm_score": 6,
"selected": false,
"text": "<p>If the computer has a route to the Internet, this will <em>always</em> work to get the preferred local ip address, even if /etc/hosts is not set correctly.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 27788672,
"author": "Graham Chap",
"author_id": 3842040,
"author_profile": "https://Stackoverflow.com/users/3842040",
"pm_score": 4,
"selected": false,
"text": "<p>A version I do not believe that has been posted yet. \nI tested with python 2.7 on Ubuntu 12.04.</p>\n\n<p>Found this solution at : <a href=\"http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/\" rel=\"noreferrer\">http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/</a></p>\n\n<pre><code>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</code></pre>\n\n<p>Example Result:</p>\n\n<pre><code>>>> get_ip_address('eth0')\n'38.113.228.130'\n</code></pre>\n"
},
{
"answer_id": 28950776,
"author": "fatal_error",
"author_id": 1301627,
"author_profile": "https://Stackoverflow.com/users/1301627",
"pm_score": 9,
"selected": false,
"text": "<p><strong>This method returns the "primary" IP on the local box (the one with a default route)</strong>.</p>\n<ul>\n<li>Does NOT need routable net access or any connection at all.</li>\n<li>Works even if all interfaces are unplugged from the network.</li>\n<li>Does NOT need or even try to get <em>anywhere else</em>.</li>\n<li>Works with NAT, public, private, external, and internal IP's</li>\n<li>Pure Python 2 (or 3) with no external dependencies.</li>\n<li>Works on Linux, Windows, and OSX.</li>\n</ul>\n<p>Python 3 or 2:</p>\n<pre class=\"lang-py prettyprint-override\"><code> 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</code></pre>\n<p>This returns a single IP which is the primary (the one with a default route). If you need instead all IP's attached to all interfaces (including localhost, etc), see something like <a href=\"https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib/24564613#24564613\">this answer</a>.</p>\n<p>If you are behind a NAT firewall like your wifi router at home, then this will not show your public NAT IP, but instead your private IP on the local network which has a default route to your local WIFI router. If you instead need your external IP:</p>\n<ul>\n<li><p>running this function on THAT external device (wifi router), or</p>\n</li>\n<li><p>connecting to an external service such as <a href=\"https://www.ipify.org/\" rel=\"noreferrer\">https://www.ipify.org/</a> that could reflect back the IP as it's seen from the outside world</p>\n</li>\n</ul>\n<p>... but those ideas are completely different from the original question. :)</p>\n"
},
{
"answer_id": 29931604,
"author": "LRund",
"author_id": 4713795,
"author_profile": "https://Stackoverflow.com/users/4713795",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't very Pythonic, but it works reliably on Windows.</p>\n\n<pre><code>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</code></pre>\n\n<p>Yeah, it's a hack, but at times I don't feel like second-guessing an operating system, and just go ahead and use what's built-in and works.</p>\n"
},
{
"answer_id": 36446068,
"author": "Frederik Aalund",
"author_id": 554283,
"author_profile": "https://Stackoverflow.com/users/554283",
"pm_score": 2,
"selected": false,
"text": "<p>A Python 3.4 version utilizing the newly introduced asyncio package.</p>\n<pre class=\"lang-py prettyprint-override\"><code>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</code></pre>\n<p>This is based on UnkwnTech's <a href=\"https://stackoverflow.com/a/166589/554283\">excellent answer</a>.</p>\n"
},
{
"answer_id": 37618645,
"author": "RiccardoCh",
"author_id": 2000573,
"author_profile": "https://Stackoverflow.com/users/2000573",
"pm_score": 2,
"selected": false,
"text": "<p>To get the ip address you can use a <em>shell command</em> directly in <strong>python</strong>:</p>\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 38814772,
"author": "Apalala",
"author_id": 545637,
"author_profile": "https://Stackoverflow.com/users/545637",
"pm_score": -1,
"selected": false,
"text": "<p>I settled for using the service and/or API of <strong>ipfy</strong>: <a href=\"https://www.ipify.org\" rel=\"nofollow\">https://www.ipify.org</a>.</p>\n\n<pre><code>#!/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</code></pre>\n\n<p>The response can also be obtained in <em>JSON</em> and <em>JSONP</em> formats.</p>\n\n<p>There's an <strong>ipify</strong> <a href=\"https://github.com/rdegges/python-ipify\" rel=\"nofollow\">Python library</a> on Github.</p>\n"
},
{
"answer_id": 41002096,
"author": "Wyrmwood",
"author_id": 1368703,
"author_profile": "https://Stackoverflow.com/users/1368703",
"pm_score": -1,
"selected": false,
"text": "<p>This is very similar to previously posted answers, but I could not find any with this usage of calls. This is what I use for ipv4. For ipv6 change the '.' in to ':' in </p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 44581122,
"author": "Villiam",
"author_id": 7727270,
"author_profile": "https://Stackoverflow.com/users/7727270",
"pm_score": 0,
"selected": false,
"text": "<pre><code>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</code></pre>\n"
},
{
"answer_id": 45222755,
"author": "NandaKrishnan",
"author_id": 8318939,
"author_profile": "https://Stackoverflow.com/users/8318939",
"pm_score": -1,
"selected": false,
"text": "<pre><code>import socket\nprint(socket.gethostbyname(socket.getfqdn()))\n</code></pre>\n"
},
{
"answer_id": 48004756,
"author": "Ishwarya",
"author_id": 9148547,
"author_profile": "https://Stackoverflow.com/users/9148547",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import netifaces as ni \n\nni.ifaddresses('eth0')\nip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']\nprint(ip)\n</code></pre>\n\n<p>This will return you the IP address in the Ubuntu system as well as MacOS. The output will be the system IP address as like my IP: 192.168.1.10.</p>\n"
},
{
"answer_id": 49269943,
"author": "hmofrad",
"author_id": 5412470,
"author_profile": "https://Stackoverflow.com/users/5412470",
"pm_score": 3,
"selected": false,
"text": "<p>If you're looking for an IPV4 address different from your localhost IP address <code>127.0.0.1</code>, here is a neat piece of python codes:</p>\n\n<pre><code>import subprocess\naddress = subprocess.check_output(['hostname', '-s', '-I'])\naddress = address.decode('utf-8') \naddress=address[:-1]\n</code></pre>\n\n<p>Which can also be written in a single line:</p>\n\n<pre><code>address = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1]\n</code></pre>\n\n<p>Even if you put <code>localhost</code> in <code>/etc/hostname</code>, the code will still give your local IP address.</p>\n"
},
{
"answer_id": 55824993,
"author": "Compl Yue",
"author_id": 6394508,
"author_profile": "https://Stackoverflow.com/users/6394508",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another variant to previous answers, can be saved to an executable script named <code>my-ip-to</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/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</code></pre>\n\n<p>it takes any number of remote hosts, and print out local ips to reach them one by one:</p>\n\n<pre><code>$ my-ip-to z.cn g.cn localhost\n192.168.11.102\n192.168.11.102\n127.0.0.1\n$\n</code></pre>\n\n<p>And print best-bet when no arg is given.</p>\n\n<pre><code>$ my-ip-to\n192.168.11.102\n</code></pre>\n"
},
{
"answer_id": 55857821,
"author": "Romolo",
"author_id": 11412897,
"author_profile": "https://Stackoverflow.com/users/11412897",
"pm_score": 0,
"selected": false,
"text": "<p>For a linux env, read the /proc/net/tcp, the second (localaddress) and third (remoteaddress) will give the IPs at hexa format.</p>\n\n<p>Tip: If second column is zeroed (00000000:0000) so its a Listen Port :)</p>\n\n<p><a href=\"https://github.com/romol0s/python/blob/master/general/functions/getTcpListenIpsByPort.py\" rel=\"nofollow noreferrer\">https://github.com/romol0s/python/blob/master/general/functions/getTcpListenIpsByPort.py</a></p>\n\n<p><a href=\"https://www.kernel.org/doc/Documentation/networking/proc_net_tcp.txt\" rel=\"nofollow noreferrer\">https://www.kernel.org/doc/Documentation/networking/proc_net_tcp.txt</a></p>\n"
},
{
"answer_id": 57196643,
"author": "Kasper Skytte Andersen",
"author_id": 8575867,
"author_profile": "https://Stackoverflow.com/users/8575867",
"pm_score": 4,
"selected": false,
"text": "<p>For linux, you can just use <code>check_output</code> of the <code>hostname -I</code> system command like so:</p>\n\n<pre><code>from subprocess import check_output\ncheck_output(['hostname', '-I'])\n</code></pre>\n"
},
{
"answer_id": 60048761,
"author": "Josh",
"author_id": 10794945,
"author_profile": "https://Stackoverflow.com/users/10794945",
"pm_score": -1,
"selected": false,
"text": "<p>pyroute2 is a great library that can be used to obtain not just ip addresses but also gateway information and other useful information.\nThe following code can obtain the ipv4 address of any interface.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 65130655,
"author": "nikhil swami",
"author_id": 12179956,
"author_profile": "https://Stackoverflow.com/users/12179956",
"pm_score": 0,
"selected": false,
"text": "<h2>Windows solution, Take it or leave it.</h2>\n<p>gets only the self ip, on the current active wlan[wireless LAN] ie the computer's ip on the (wifi router or network switch).</p>\n<p>note: its not the public ip of the device and does not involve any external requests or packages or public apis.</p>\n<p>The core idea is to parse the output of <code>shell command: ipconfig</code>, or ifconfig on linux. we are using subprocess to acquire the output.</p>\n<pre><code>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</code></pre>\n<h2>this is what happens after CMD:'ipconfig' :</h2>\n<p>we get this output, we captured it in python using subprocess output.</p>\n<blockquote>\n<p>C:\\Users\\dell>ipconfig</p>\n</blockquote>\n<pre><code>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</code></pre>\n<p>and we parsed the string in python, in a manner that selects the wireless adapter's ip on current network.</p>\n"
},
{
"answer_id": 68378891,
"author": "Laurens",
"author_id": 3640844,
"author_profile": "https://Stackoverflow.com/users/3640844",
"pm_score": -1,
"selected": false,
"text": "<p>@fatal_error solution should be the accepted answer! this is an implementation of his solution in nodejs in case people need it:</p>\n<pre class=\"lang-js prettyprint-override\"><code>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</code></pre>\n"
},
{
"answer_id": 69369114,
"author": "TCB919",
"author_id": 8345316,
"author_profile": "https://Stackoverflow.com/users/8345316",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this easily on modern *NIX systems that have the <code>iproute2</code> utility by calling it via <code>subprocess.run()</code> as you can output in JSON with the <code>-j</code> switch and then use the <code>json.loads()</code> module and method to convert that to a python data structure. The following code displays the first non loopback IP address.</p>\n<pre><code>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</code></pre>\n<p>Alternativly if you had multiple IP's and wanted to find the IP that would be used to connect to a specific destination you could use <code>ip -j route get 8.8.8.8</code> like this:</p>\n<pre><code>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</code></pre>\n<p>If your looking for all IP addresses you can iterate through the list of dictionaries returned by <code>ip -j a</code></p>\n<pre><code>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</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24789/"
] |
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
|
```
import socket
socket.gethostbyname(socket.gethostname())
```
This won't work always (returns `127.0.0.1` on machines having the hostname in `/etc/hosts` as `127.0.0.1`), a paliative would be what gimel shows, use `socket.getfqdn()` instead. Of course your machine needs a resolvable hostname.
|
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": "<p>This will fetch your remote IP address</p>\n\n<pre><code>import urllib\nip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()\n</code></pre>\n\n<p>If you don't want to rely on someone else, then just upload something like this PHP script:</p>\n\n<pre><code><?php echo $_SERVER['REMOTE_ADDR']; ?>\n</code></pre>\n\n<p>and change the URL in the Python or if you prefer ASP:</p>\n\n<pre><code><%\nDim UserIPAddress\nUserIPAddress = Request.ServerVariables(\"REMOTE_ADDR\")\n%>\n</code></pre>\n\n<p>Note: I don't know ASP, but I figured it might be useful to have here so I googled.</p>\n"
},
{
"answer_id": 166563,
"author": "Steve Losh",
"author_id": 13498,
"author_profile": "https://Stackoverflow.com/users/13498",
"pm_score": 3,
"selected": false,
"text": "<p>whatismyip.org is better... it just tosses back the ip as plaintext with no extraneous crap.</p>\n\n<pre><code>import urllib\nip = urllib.urlopen('http://whatismyip.org').read()\n</code></pre>\n\n<p>But yeah, it's impossible to do it easily without relying on something outside the network itself.</p>\n"
},
{
"answer_id": 16304401,
"author": "powlo",
"author_id": 944717,
"author_profile": "https://Stackoverflow.com/users/944717",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't mind expletives then try:</p>\n\n<p><a href=\"http://wtfismyip.com/json\" rel=\"nofollow\">http://wtfismyip.com/json</a></p>\n\n<p>Bind it up in the usual urllib stuff as others have shown.</p>\n\n<p>There's also:</p>\n\n<p><a href=\"http://www.networksecuritytoolkit.org/nst/tools/ip.php\" rel=\"nofollow\">http://www.networksecuritytoolkit.org/nst/tools/ip.php</a></p>\n"
},
{
"answer_id": 36406616,
"author": "Arch Angeles",
"author_id": 6156770,
"author_profile": "https://Stackoverflow.com/users/6156770",
"pm_score": 2,
"selected": false,
"text": "<pre><code>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</code></pre>\n\n<p>Try putting whatever 'findmyipsite' you can find into a list and iterating through them for comparison. This one seems to work well.</p>\n"
},
{
"answer_id": 38436633,
"author": "twig",
"author_id": 253704,
"author_profile": "https://Stackoverflow.com/users/253704",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://api.ipify.org/?format=json\" rel=\"noreferrer\">https://api.ipify.org/?format=json</a> is pretty straight forward</p>\n\n<p>can be parsed by just running <code>requests.get(\"https://api.ipify.org/?format=json\").json()['ip']</code></p>\n"
},
{
"answer_id": 38445997,
"author": "loretoparisi",
"author_id": 758836,
"author_profile": "https://Stackoverflow.com/users/758836",
"pm_score": 1,
"selected": false,
"text": "<p>This is simple as</p>\n\n<pre><code>>>> import urllib\n>>> urllib.urlopen('http://icanhazip.com/').read().strip('\\n')\n'xx.xx.xx.xx'\n</code></pre>\n"
},
{
"answer_id": 47548460,
"author": "Abhijeet",
"author_id": 452708,
"author_profile": "https://Stackoverflow.com/users/452708",
"pm_score": 3,
"selected": false,
"text": "<pre><code>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</code></pre>\n\n<p><a href=\"http://blog.tankorsmash.com/?p=340\" rel=\"noreferrer\">Reference</a></p>\n"
},
{
"answer_id": 71074002,
"author": "htaccess",
"author_id": 599390,
"author_profile": "https://Stackoverflow.com/users/599390",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use DNS which in some cases may be more reliable than http methods:</p>\n<pre><code>#!/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</code></pre>\n<p>This is the python equivalent of <code>dig +short -4 myip.opendns.com @resolver1.opendns.com</code></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
How can I find the public facing IP for my net work in Python?
|
This will fetch your remote IP address
```
import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
```
If you don't want to rely on someone else, then just upload something like this PHP script:
```
<?php echo $_SERVER['REMOTE_ADDR']; ?>
```
and change the URL in the Python or if you prefer ASP:
```
<%
Dim UserIPAddress
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
%>
```
Note: I don't know ASP, but I figured it might be useful to have here so I googled.
|
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": 166560,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer the first one. The condition should be as simple as possible and it should be fairly obvious which is simpler out of condition and !condition</p>\n"
},
{
"answer_id": 166564,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 5,
"selected": true,
"text": "<p>I prefer to put the most common path first, and I am a strong believer in nesting reduction so I will break, continue, or return instead of elsing whenever possible. I generally prefer to test against positive conditions, or invert [and name] negative conditions as a positive.</p>\n\n<pre><code>if (condition)\n return;\n\nDoSomething();\n</code></pre>\n\n<p>I have found that by drastically reducing the usage of else my code is more readable and maintainable and when I do have to use else its almost always an excellent candidate for a more structured switch statement.</p>\n"
},
{
"answer_id": 166573,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on your flow. For many functions, I'll use preconditions:</p>\n\n<pre><code>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</code></pre>\n\n<p>If I need to <em>do</em> something each case, I'll use an <code>if (positive_clause) {} else {}</code> format.</p>\n"
},
{
"answer_id": 166576,
"author": "Ian Jacobs",
"author_id": 22818,
"author_profile": "https://Stackoverflow.com/users/22818",
"pm_score": 1,
"selected": false,
"text": "<p>For me it depends on the condition, for example:</p>\n\n<pre><code>if (!PreserveData.Checked)\n{ resetfields();}\n</code></pre>\n\n<p>I tend to talk to my self with what I want the logic to be and code it to the little voice in my head.</p>\n"
},
{
"answer_id": 166579,
"author": "Simon Howard",
"author_id": 24806,
"author_profile": "https://Stackoverflow.com/users/24806",
"pm_score": 2,
"selected": false,
"text": "<p>If the code is to check for an error condition, I prefer to put that code first, and the \"successful\" code second; conceptually, this keeps a function call and its error-checking code together, which makes sense to me because they are related. For example:</p>\n\n<pre><code> if (!some_function_that_could_fail())\n {\n // Error handling code\n }\n else\n {\n // Success code\n }\n</code></pre>\n"
},
{
"answer_id": 166580,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with Oli on using a positive if clause when possible.</p>\n\n<p>Just please never do this:</p>\n\n<pre><code>if (somePositiveCondition)\nelse {\n //stuff\n}\n</code></pre>\n\n<p>I used to see this a lot at one place I worked and used to wonder if one of the coders didn't understand how not works...</p>\n"
},
{
"answer_id": 166583,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 0,
"selected": false,
"text": "<p>As a general rule, if one is significantly larger than the other, I make the larger one the <code>if</code> block.</p>\n"
},
{
"answer_id": 166584,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>put the common path first</li>\n<li>turn negative cheking into positive ones (<code>!full == empty</code>)</li>\n</ol>\n"
},
{
"answer_id": 166612,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "<p>I know this isn't exactly what you're looking for, but ... A lot of developers use a \"guard clause\", that is, a negative \"if\" statement that breaks out of the method as soon as possible. At that point, there is no \"else\" really.</p>\n\n<p>Example:</p>\n\n<pre><code>if (blah == false)\n{\n return; // perhaps with a message\n}\n\n// do rest of code here...\n</code></pre>\n\n<p>There are some hard-core c/c++/assembly guys out there that will tell you that you're destroying your CPU!!! (in many cases, processors favor the \"true\" statement and try to \"prefetch\" the next thing to do... so theoretically any \"false\" condition will flush the pipe and will go microseconds slower).</p>\n\n<p>In my opinion, we are at the point where \"better\" (more understandable) code wins out over microseconds of CPU time.</p>\n"
},
{
"answer_id": 166644,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>I think that for a single variable the not operator is simple enough and naming issues start being more relevant. </p>\n\n<p>Never name a variable not_X, if in need use a thesaurus and find an opposite. I've seen plenty of awful code like</p>\n\n<pre><code>if (not_dead) {\n} else {\n}\n</code></pre>\n\n<p>instead of the obvious</p>\n\n<pre><code>if (alive) {\n} else {\n}\n</code></pre>\n\n<p>Then you can sanely use (very readable, no need to invert the code blocks)</p>\n\n<pre><code>if (!alive) {\n} else {\n}\n</code></pre>\n\n<p>If we're talking about more variables I think the best rule is to simplify the condition. After a while projects tend to get conditions like:</p>\n\n<pre><code>if (dead || (!dead && sleeping)) {\n} else {\n}\n</code></pre>\n\n<p>Which translates to</p>\n\n<pre><code>if (dead || sleeping) {\n} else {\n}\n</code></pre>\n\n<p>Always pay attention to what conditions look like and how to simplify them. </p>\n"
},
{
"answer_id": 166674,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "<p>If you must have multiple exit points, put them first and make them clear:</p>\n\n<pre><code>if TerminatingCondition1 then\n Exit\nif TerminatingCondition2 then\n Exit\n</code></pre>\n\n<p>Now we can progress with the usual stuff:</p>\n\n<pre><code>if NormalThing then\n DoNormalThing\nelse\n DoAbnormalThing\n</code></pre>\n"
},
{
"answer_id": 166687,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 2,
"selected": false,
"text": "<p>Two (contradictory) textbook quotes:</p>\n\n<blockquote>\n <p>Put the shortest clause of an if/else\n on top</p>\n</blockquote>\n\n<p>--Allen Holub, \"Enough Rope to Shoot Yourself in the Foot\", p52</p>\n\n<blockquote>\n <p>Put the normal case after the if rather than after the else</p>\n</blockquote>\n\n<p>--Steve McConnell, \"Code Complete, 2nd ed.\", p356</p>\n"
},
{
"answer_id": 166696,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>Software is knowledge capture. You're encoding someone's knowledge of how to do something. </p>\n\n<p>The software should fit what's \"natural\" for the problem. When in doubt, ask someone else and see what people actually say and do.</p>\n\n<p>What about the situation where the \"common\" case is do nothing? What then</p>\n\n<pre><code>if( common ) {\n // pass\n}\nelse {\n // great big block of exception-handling folderol\n}\n</code></pre>\n\n<p>Or do you do this?</p>\n\n<pre><code>if( ! common ) {\n // great big block of except-handling folderol\n}\n</code></pre>\n\n<p>The \"always positive\" rule isn't really what you want first. You want to look at rules more like the following.</p>\n\n<ol>\n<li>Always natural -- it should read like English (or whatever the common language in your organization is.)</li>\n<li>Where possible, common cases first -- so they appear common.</li>\n<li>Where possible use positive logic; negative logic can be used where it's commonly said that way or where the common case is a do-nothing.</li>\n</ol>\n"
},
{
"answer_id": 166716,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 2,
"selected": false,
"text": "<p>If one of the two paths is very short (1 to 10 lines or so) and the other is much longer, I follow the <a href=\"https://stackoverflow.com/questions/166550/what-to-put-in-the-if-block-and-what-to-put-in-the-else-block#166687\">Holub rule mentioned here</a> and put the shorter piece of code in the if. That makes it easier to see the if/else flow on one screen when reviewing the code.</p>\n\n<p>If that is not possible, then I structure to make the condition as simple as possible.</p>\n"
},
{
"answer_id": 166721,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 2,
"selected": false,
"text": "<p>When I am looking at data validation, I try to make my conditions \"white listing\" - that is, I test for what I will accept:</p>\n\n<pre><code>if DataIsGood() then\n DoMyNormalStuff\nelse\n TakeEvasiveAction\n</code></pre>\n\n<p>Rather than the other way around, which tends to degenerate into:</p>\n\n<pre><code>if SomeErrorTest then\n TakeSomeEvasiveAction\nelse if SomeOtherErrorCondition then\n CorrectMoreStupidUserProblems\nelse if YetAnotherErrorThatNoOneThoughtOf then\n DoMoreErrorHandling\nelse\n DoMyNormalStuff\n</code></pre>\n"
},
{
"answer_id": 166730,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 1,
"selected": false,
"text": "<p>You can usually make the condition positive without switching around the if / else blocks.</p>\n\n<p>Change </p>\n\n<pre><code> if (!widget.enabled()) {\n // more common \n } else {\n // less common \n }\n</code></pre>\n\n<p>to </p>\n\n<pre><code> if (widget.disabled()) {\n // more common \n } else {\n // less common\n }\n</code></pre>\n"
},
{
"answer_id": 166873,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 1,
"selected": false,
"text": "<p>Intel Pentium branch prediction pre-fetches instructions for the \"if\" case. If it instead follows the \"else\" branch: it has the flush the instruction pipeline, causing a stall. </p>\n\n<p>If you care a lot about performance: put the most likely outcome in the 'if' clause.</p>\n\n<p>Personally i write it as</p>\n\n<pre><code>if (expected)\n{\n //expected path\n}\nelse\n{\n //fallback other odd case\n} \n</code></pre>\n"
},
{
"answer_id": 166913,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 0,
"selected": false,
"text": "<p>I always keep the most likely first.</p>\n\n<p>In Perl I have an extra control structure to help with that. The inverse of if.</p>\n\n<pre><code>unless (alive) {\n go_to_heaven;\n} else {\n say \"MEDIC\";\n}\n</code></pre>\n"
},
{
"answer_id": 167044,
"author": "Chris B-C",
"author_id": 1517,
"author_profile": "https://Stackoverflow.com/users/1517",
"pm_score": 1,
"selected": false,
"text": "<p>If you have both true and false conditions then I'd opt for a positive conditional - This reduces confusion and in general I believe makes your code easier to read.</p>\n\n<p>On the other hand, if you're using a language such as Perl, and particularly if your false condition is either an error condition or the most common condition, you can use the 'unless' structure, which executes the code block unless the condition is true (i.e. the opposite of if):</p>\n\n<pre><code>unless ($foo) {\n $bar;\n}\n</code></pre>\n"
},
{
"answer_id": 167251,
"author": "dicroce",
"author_id": 3886,
"author_profile": "https://Stackoverflow.com/users/3886",
"pm_score": 0,
"selected": false,
"text": "<p>You should always put the most likely case first. Besides being more readable, it is faster. This also applies to switch statements.</p>\n"
},
{
"answer_id": 167469,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm horrible when it comes to how I set up if statements. Basically, I set it up based on what exactly I'm looking for, which leads everything to be different.<br>\n<br>\nif (userinput = null){ <br>\n explodeViolently(); <br>\n} else {<br>\nactually do stuff;<br>\n}<br>\n<br>\nor perhaps something like <br>\n<br>\nif (1+1=2) {<br>\ndo stuff;<br>\n} else {<br>\nexplodeViolently();<br>\n}<br></p>\n\n<p>Which section of the if/else statement actually does things for me is a bad habit of mine.</p>\n"
},
{
"answer_id": 252990,
"author": "Yarik",
"author_id": 31415,
"author_profile": "https://Stackoverflow.com/users/31415",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, let's put aside situations when it is better to avoid using \"else\" in the first place (I hope everyone agrees that such situations do exist and determining such cases probably should be a separate topic).</p>\n\n<p>So, let's assume that there must be an \"else\" clause.</p>\n\n<p>I think that readability/comprehensibility imposes at least three key requirements or rules, which unfortunately often compete with each other:</p>\n\n<ol>\n<li><p>The shorter is the first block (the \"if\" block) the easier is it to grasp the entire \"if-else\" construct. When the \"if\" block is long enough, it becomes way too easy to overlook existence of \"else\" block.</p></li>\n<li><p>When the \"if\" and \"else\" paths are logically asymmetric (e.g. \"normal processing\" vs. \"error processing\"), in a <strong>standalone</strong> \"if-else\" construct it does not really matter much which path is first and which is second. However, when there are <strong>multiple</strong> \"if-else\" constructs in proximity to each other (including nesting), and when all those \"if-else\" constructs have asymmetry of the same kind - that's when it is very important to arrange those asymmetric paths consistently. </p>\n\n<p>Again, it can be \"if ... normal path ... else ... abnormal path\" for all, or \"if ... abnormal path ... else ... normal path\" for all, but it should not be a mix of these two variants.</p>\n\n<p>With all other conditions equal, putting the normal path first is probably more natural for most human beings (I think it's more about psychology than aesthetics :-).</p></li>\n<li><p>An expression that starts with a negation usually is less readable/comprehensible than an expression that doesn't.</p></li>\n</ol>\n\n<p>So, we have these three competing requirements/rules, and the real question is: which of them are more important than others. For Allen Holub the rule #1 is probably the most important one. For Steve McConnell - it is the rule #2. But I don't think that you can really choose only one of these rules as a single quideline.</p>\n\n<p>I bet you've already guessed my personal priorities here (from the way I ordered the rules above :-). </p>\n\n<p>My reasons are simple: </p>\n\n<ul>\n<li><p>The rule #1 is unconditional and impossible to circumvent. If one of the blocks is so long that it runs off the screen - it must become the \"else\" block. (No, it is not a good idea to create a function/method mechanically just to decrease the number of lines in an \"if\" or \"else\" block! I am assuming that each block already has a <strong>logically justifiable</strong> minimum amount of lines.)</p></li>\n<li><p>The rule #2 involves a lot of conditions: multiple \"if-else\" constructs, all having asymmetry of the same kind, etc. So it just does not apply in many cases. </p>\n\n<p>Also, I often observe the following interesting phenomenon: when the rule #2 does apply and when it is used properly, it actually does not conflict with the rule #1! For example, whenever I have a bunch of \"if-else\" statements with \"normal vs. abnormal\" asymmetry, all the \"abnormal\" paths are shorter than \"normal\" ones (or vice versa). I cannot explain this phenomenon, but I think that it's just a sign of good code organization. In other words, whenever I see a situation when rules #1 and #2 are in conflict, I start looking for \"code smells\" and more often than not I do find some; and after refactoring - tada! no more painful choosing between rule #1 and rule #2, :-) </p></li>\n<li><p>Finally, the rule #3 hase the smallest scope and therefore is the least critical. </p>\n\n<p>Also, as mentined here by other colleagues, it is often very easy to \"cheat\" with this rule (for example, to write \"if(disabled),,,\" instead of \"if(!enabled)...\").</p></li>\n</ul>\n\n<p>I hope someone can make some sense of this opus...</p>\n"
},
{
"answer_id": 11505844,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I generally put the positive result (so the method) at the start so:</p>\n\n<pre><code>if(condition)\n{\ndoSomething();\n}\nelse\n{\nSystem.out.println(\"condition not true\")\n}\n</code></pre>\n\n<p>But if the condition has to be false for the method to be used, I would do this:</p>\n\n<pre><code>if(!condition)\n{\ndoSomething();\n}\nelse\n{\nSystem.out.println(\"condition true\");\n}\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14663/"
] |
This is a minor style question, but every bit of readability you add to your code counts.
So if you've got:
```
if (condition) then
{
// do stuff
}
else
{
// do other stuff
}
```
How do you decide if it's better like that, or like this:
```
if (!condition) then
{
// do other stuff
{
else
{
// do stuff
}
```
My heuristics are:
1. Keep the condition positive (less
mental calculation when reading it)
2. Put the most common path into the
first block
|
I prefer to put the most common path first, and I am a strong believer in nesting reduction so I will break, continue, or return instead of elsing whenever possible. I generally prefer to test against positive conditions, or invert [and name] negative conditions as a positive.
```
if (condition)
return;
DoSomething();
```
I have found that by drastically reducing the usage of else my code is more readable and maintainable and when I do have to use else its almost always an excellent candidate for a more structured switch statement.
|
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": "<p>Try this:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 167183,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>OK, the linked to forum post DID help, thank you. I did however find a simpler solution, which I include below:</p>\n\n<p>1) Use Apache commons.lang java library<br>\n2) Use the following java code: </p>\n\n\n\n<pre class=\"lang-java prettyprint-override\"><code>//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</code></pre>\n"
},
{
"answer_id": 191865,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Well, I did run into a problem - it doesn't appear to me (and I could be wrong) that there was any way to convert from and ISO string that DateUtils (from apache commons lang) creates, back to a date!<br>\nie. apache commons will format it the way I would like, but not convert it back to a date again</p>\n\n<p>So, I switched to JodaTime, and its much easier since its based on ISO8601 - here is the code:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 1060276,
"author": "doodaddy",
"author_id": 24973,
"author_profile": "https://Stackoverflow.com/users/24973",
"pm_score": 1,
"selected": false,
"text": "<p>Great find regarding commons.lang.java! You can even save yourself from creating your own format string by doing the following:</p>\n\n<pre><code>DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date());\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
In java, when using SimpleDateFormat with the pattern:
```
yyyy-MM-dd'T'HH:mm:ss.SSSZ
```
the date is outputted as:
```
"2002-02-01T18:18:42.703-0700"
```
In xquery, when using the xs:dateTime function, it gives the error:
```
"Invalid lexical value [err:FORG0001]"
```
with the above date. In order for xquery to parse properly, the date needs to look like:
```
"2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string
```
which is based on the ISO 8601, whereas Java date is based on the RFC 822 standard.
I would like to be able to easily specify the timezone in Java so that it will output the way that xquery wants.
Thanks!
|
OK, the linked to forum post DID help, thank you. I did however find a simpler solution, which I include below:
1) Use Apache commons.lang java library
2) Use the following java code:
```java
//NOTE: ZZ on end is not compatible with jdk, but allows for formatting
//dates like so (note the : 3rd from last spot, which is iso8601 standard):
//date=2008-10-03T10:29:40.046-04:00
private static final String DATE_FORMAT_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ";
DateFormatUtils.format(new Date(), DATE_FORMAT_8601)
```
|
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": "<h1>The method</h1>\n<p>Connect to port 80 on the host and send it</p>\n<pre><code>HEAD / HTTP/1.0\n</code></pre>\n<p>This needs to be followed by carriage-return + line-feed twice</p>\n<p>You'll get back something like this</p>\n<pre><code>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</code></pre>\n<p>You can then extract the apache version from the Server: header</p>\n<h1>Typical tools you can use</h1>\n<p>You could use the HEAD utility which comes with a full install of Perl's <a href=\"http://search.cpan.org/%7Egaas/libwww-perl-5.816/lib/LWP.pm\" rel=\"noreferrer\">LWP</a> library, e.g.</p>\n<pre><code>HEAD http://your.webserver.com/\n</code></pre>\n<p>Or, use the <a href=\"http://curl.haxx.se/\" rel=\"noreferrer\">curl</a> utility, e.g.</p>\n<pre><code> curl --head http://your.webserver.com/\n</code></pre>\n<p>You could also use a browser extension which lets you view server headers, such as <a href=\"https://addons.mozilla.org/en-US/firefox/addon/3829\" rel=\"noreferrer\">Live HTTP Headers</a> or <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"noreferrer\">Firebug</a> for Firefox, or <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"noreferrer\">Fiddler</a> for IE</p>\n<h1>Stuck with Windows?</h1>\n<p>Finally. if you're on Windows, and have nothing else at your disposal, open a command prompt (Start Menu->Run, type "cmd" and press return), and then type this</p>\n<pre><code>telnet your.webserver.com 80\n</code></pre>\n<p>Then type (carefully, your characters won't be echoed back)</p>\n<pre><code>HEAD / HTTP/1.0\n</code></pre>\n<p>Press return twice and you'll see the server headers.</p>\n<h1>Other methods</h1>\n<p>As mentioned by cfeduke and Veynom, the server may be set to return limited information in the Server: header. Try and upload a PHP script to your host with this in it</p>\n<pre><code><?php phpinfo() ?>\n</code></pre>\n<p>Request the page with a web browser and you should see the Apache version reported there.</p>\n<p>You could also try and use <a href=\"http://phpshell.sourceforge.net/\" rel=\"noreferrer\">PHPShell</a> to have a poke around, try a command like</p>\n<pre><code>/usr/sbin/apache2 -V\n</code></pre>\n"
},
{
"answer_id": 166625,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 1,
"selected": false,
"text": "<p>Telnet to the host at port 80.</p>\n\n<p>Type:</p>\n\n<pre><code>get / http1.1\n::enter::\n::enter::\n</code></pre>\n\n<p>It is kind of an HTTP request, but it's not valid so the 500 error it gives you will probably give you the information you want. The blank lines at the end are important otherwise it will just seem to hang.</p>\n"
},
{
"answer_id": 166635,
"author": "Jonathan Mueller",
"author_id": 13832,
"author_profile": "https://Stackoverflow.com/users/13832",
"pm_score": 0,
"selected": false,
"text": "<p>If they have error pages enabled, you can go to a non-existent page and look at the bottom of the 404 page.</p>\n"
},
{
"answer_id": 166637,
"author": "Oli",
"author_id": 15296,
"author_profile": "https://Stackoverflow.com/users/15296",
"pm_score": 0,
"selected": false,
"text": "<p>In the default installation, call a page that doesn't exist and you get an error with the version at the end:</p>\n<blockquote>\n<p><b>Object not found!</b></p>\n<p>The requested URL was not found on this server. If you entered the URL manually please\ncheck your spelling and try again.\n<br/>\nIf you think this is a server error, please contact the webmaster.\n<br/>\nError 404 <br/>\nlocalhost <br/>\n10/03/08 14:41:45 <br/>\nApache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5 <br/></p>\n</blockquote>\n"
},
{
"answer_id": 166648,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 3,
"selected": false,
"text": "<p>Rarely, a hardened HTTP server is configured to give no server information or misleading server information. In those scenarios if the server has PHP enabled you can add:</p>\n\n<pre><code><?php phpinfo(); ?>\n</code></pre>\n\n<p>in a file and browse to it and look for the</p>\n\n<pre><code>_SERVER[\"SERVER_SOFTWARE\"]\n</code></pre>\n\n<p>entry. This is susceptible to the same hardening lack of information/misleading though I would imagine that it's not altered often, because this method first requires access to the machine to create the PHP file.</p>\n"
},
{
"answer_id": 166769,
"author": "Veynom",
"author_id": 11670,
"author_profile": "https://Stackoverflow.com/users/11670",
"pm_score": 3,
"selected": false,
"text": "<p>Warning, some Apache servers do not always send their version number when using HEAD, like in this case:</p>\n\n<pre><code>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</code></pre>\n\n<p>If PHP is installed then indeed, just use the php info command:</p>\n\n<pre><code><?php phpinfo(); ?>\n</code></pre>\n"
},
{
"answer_id": 166815,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": 2,
"selected": false,
"text": "<p>The level of version information given out by an Apache server can be configured by the ServerTokens setting in its configuration.</p>\n\n<p>I believe there is also a setting that controls whether the version appears in server error pages, although I can't remember what it is off the top of my head. If you don't have direct access to the server, and the server administrator is competent and doesn't want you to know the version they're running... I think you may be <a href=\"https://en.wiktionary.org/wiki/SOL#Adjective\" rel=\"nofollow noreferrer\">SOL</a>.</p>\n"
},
{
"answer_id": 166829,
"author": "Eduardo",
"author_id": 9823,
"author_profile": "https://Stackoverflow.com/users/9823",
"pm_score": 0,
"selected": false,
"text": "<p>Your best option is through PHP: \nAll version requests from the client side cannot be trusted since your Apache could be configured with ServerTokens Prod and ServerSignature Off. See: <a href=\"http://www.petefreitag.com/item/419.cfm\" rel=\"nofollow noreferrer\">http://www.petefreitag.com/item/419.cfm</a></p>\n"
},
{
"answer_id": 12110433,
"author": "crmpicco",
"author_id": 691505,
"author_profile": "https://Stackoverflow.com/users/691505",
"pm_score": 5,
"selected": false,
"text": "<p><code>httpd -v</code> will give you the version of Apache running on your server (if you have SSH/shell access).</p>\n\n<p>The output should be something like this:</p>\n\n<pre><code>Server version: Apache/2.2.3\nServer built: Oct 20 2011 17:00:12\n</code></pre>\n\n<p>As has been suggested you can also do <code>apachectl -v</code> which will give you the same output, but will be supported by more flavours of Linux.</p>\n"
},
{
"answer_id": 23841194,
"author": "Martin Zeitler",
"author_id": 549372,
"author_profile": "https://Stackoverflow.com/users/549372",
"pm_score": 0,
"selected": false,
"text": "<p>Simply use something like the following - the string should be there already:</p>\n\n<pre><code><?php\n if(isset($_SERVER['SERVER_SOFTWARE'])){\n echo $_SERVER['SERVER_SOFTWARE'];\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 32045766,
"author": "matinict",
"author_id": 2239022,
"author_profile": "https://Stackoverflow.com/users/2239022",
"pm_score": -1,
"selected": false,
"text": "<p>Use this PHP script:</p>\n\n<pre><code> $version = apache_get_version();\n echo \"$version\\n\";\n</code></pre>\n\n<p>Se <em><a href=\"http://php.net/manual/en/function.apache-get-version.php\" rel=\"nofollow noreferrer\">apache_get_version</a></em>.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24039/"
] |
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.
I have tried HEAD and do not get a version number reported.
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.
Still no closer...
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.
|
The method
==========
Connect to port 80 on the host and send it
```
HEAD / HTTP/1.0
```
This needs to be followed by carriage-return + line-feed twice
You'll get back something like this
```
HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 12:39:43 GMT
Server: 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
Last-Modified: Thu, 02 Aug 2007 20:50:09 GMT
ETag: "438118-197-436bd96872240"
Accept-Ranges: bytes
Content-Length: 407
Connection: close
Content-Type: text/html; charset=UTF-8
```
You can then extract the apache version from the Server: header
Typical tools you can use
=========================
You could use the HEAD utility which comes with a full install of Perl's [LWP](http://search.cpan.org/%7Egaas/libwww-perl-5.816/lib/LWP.pm) library, e.g.
```
HEAD http://your.webserver.com/
```
Or, use the [curl](http://curl.haxx.se/) utility, e.g.
```
curl --head http://your.webserver.com/
```
You could also use a browser extension which lets you view server headers, such as [Live HTTP Headers](https://addons.mozilla.org/en-US/firefox/addon/3829) or [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843) for Firefox, or [Fiddler](http://www.fiddlertool.com/fiddler/) for IE
Stuck with Windows?
===================
Finally. if you're on Windows, and have nothing else at your disposal, open a command prompt (Start Menu->Run, type "cmd" and press return), and then type this
```
telnet your.webserver.com 80
```
Then type (carefully, your characters won't be echoed back)
```
HEAD / HTTP/1.0
```
Press return twice and you'll see the server headers.
Other methods
=============
As mentioned by cfeduke and Veynom, the server may be set to return limited information in the Server: header. Try and upload a PHP script to your host with this in it
```
<?php phpinfo() ?>
```
Request the page with a web browser and you should see the Apache version reported there.
You could also try and use [PHPShell](http://phpshell.sourceforge.net/) to have a poke around, try a command like
```
/usr/sbin/apache2 -V
```
|
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": "<p>It is legal, though as far as I'm aware, you have to explicitly say it's 'empty' by assigning null to it,</p>\n\n<pre><code>$hasMany = array ('Product' => array(\n'className' => 'Product',\n'conditions'=> null, // is this allowed?\n'order'=> null, // same thing here\n'foreignKey'=>'dealer_id'));\n</code></pre>\n\n<p>The example you've given sounds very wrong, and probably shouldn't work, as it isn't.</p>\n"
},
{
"answer_id": 166629,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 4,
"selected": true,
"text": "<p>Assign the value null instead of leaving anything out. The <a href=\"http://php.net/isset\" rel=\"noreferrer\">manual says</a></p>\n\n<blockquote>\n <p>isset() will return FALSE if testing a variable that has been set to NULL</p>\n</blockquote>\n\n<pre><code><?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</code></pre>\n\n<p>This works fine.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24218/"
] |
I am currently plowing my way through [IBM's tutorial on CakePHP](http://www-128.ibm.com/developerworks/edu/os-dw-os-php-cake1.html)
At one point I run into this snippet of 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'
)
);
}
?>
```
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"
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?
|
Assign the value null instead of leaving anything out. The [manual says](http://php.net/isset)
>
> isset() will return FALSE if testing a variable that has been set to NULL
>
>
>
```
<?php
class Dealer extends AppModel
{
var $name = 'Dealer';
var $hasMany = array ('Product' => array(
'className' => 'Product',
'conditions'=> null,
'order'=> null,
'foreignKey'=>'dealer_id')
);
}
?>
```
This works fine.
|
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": 166699,
"author": "Jon Trauntvein",
"author_id": 19674,
"author_profile": "https://Stackoverflow.com/users/19674",
"pm_score": 3,
"selected": true,
"text": "<p>After further investigation, I found that this error was due to a failure to initialise the openSSL library by calling SSL_library_init(). </p>\n"
},
{
"answer_id": 5580270,
"author": "Glen",
"author_id": 484110,
"author_profile": "https://Stackoverflow.com/users/484110",
"pm_score": 3,
"selected": false,
"text": "<p>I had the same problem, just thought I'd add the note that rather than calling the OpenSsl export SSL_library_init directly it can be fixed by adding the flag CURL_GLOBAL_SSL to <a href=\"http://curl.haxx.se/libcurl/c/curl_global_init.html\">curl_global_init</a></p>\n"
},
{
"answer_id": 37317423,
"author": "vidstige",
"author_id": 363437,
"author_profile": "https://Stackoverflow.com/users/363437",
"pm_score": 0,
"selected": false,
"text": "<p>I encountered the same symptom after upgrading to Ubuntu 16.04 as described in <a href=\"https://stackoverflow.com/a/37295100/363437\">this answer</a>. The solution was to Use TLS like so.</p>\n\n<pre><code>curl_easy_setopt(curl_, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2));\n</code></pre>\n\n<p>Apparently SSLv3 <a href=\"https://launchpad.net/ubuntu/+source/openssl/1.0.2g-1ubuntu1\" rel=\"nofollow noreferrer\">was disabled</a> on Ubuntu 16.04.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19674/"
] |
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:
>
>
> ```
>
> 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);
> }
>
> ```
>
>
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?
|
After further investigation, I found that this error was due to a failure to initialise the openSSL library by calling SSL\_library\_init().
|
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": "<p>First of all, and I'll get to UTF-8 later if nobody else answers, iterating like you are is a very bad way to search through an array. PHP has built-in functions just for that:</p>\n\n<p><a href=\"http://fr.php.net/array_search\" rel=\"nofollow noreferrer\">http://fr.php.net/array_search</a></p>\n\n<p>So you might want to give that a try and see if it helps with your problem. Also make sure that the PHP file you're writing is also encoded in UTF-8!</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Try the following code, which works just fine on my server. If it doesn't work check that PHP is configured to work with UTF-8 by default, or add the necessary ini_set calls.</p>\n\n<pre><code><!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</code></pre>\n"
},
{
"answer_id": 166659,
"author": "Mote",
"author_id": 24789,
"author_profile": "https://Stackoverflow.com/users/24789",
"pm_score": 0,
"selected": false,
"text": "<p>See if you have mbstring extension installed</p>\n"
},
{
"answer_id": 166675,
"author": "Joeri Sebrechts",
"author_id": 20980,
"author_profile": "https://Stackoverflow.com/users/20980",
"pm_score": 2,
"selected": false,
"text": "<p>If your PHP script file has an ANSI encoding, instead of UTF-8, then on the byte-level those norwegian characters will be different from what they would be if they were encoded in UTF-8. Since PHP is a byte-processing language, not a text-processing language, it duly compares the byte sequences and concludes they don't match.</p>\n\n<p>To resolve this, you can either make sure that your PHP script has the same encoding as the character set you're comparing against, or you can use the iconv or mbstring libraries to convert to appropriate character sets.</p>\n\n<p>Also, if you haven't read it, read this: <a href=\"http://www.joelonsoftware.com/articles/Unicode.html\" rel=\"nofollow noreferrer\">http://www.joelonsoftware.com/articles/Unicode.html</a></p>\n\n<p><strong>Update:</strong><br>another point you take into account is to make sure that what you're passing into this function is what you think it is. If you're looping across a string one character at a time with the array indexing operator, it won't work, because your UTF-8 string might use two bytes (two array index positions) to store one character. There are functions in mbstring to copy out text from strings based on character positions, not byte positions.</p>\n"
},
{
"answer_id": 166691,
"author": "Benny Wong",
"author_id": 2999,
"author_profile": "https://Stackoverflow.com/users/2999",
"pm_score": 0,
"selected": false,
"text": "<p>From what I know, your best bet is to install the mbstring (<a href=\"http://www.php.net/manual/en/ref.mbstring.php\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/ref.mbstring.php</a>) extention if you have access to the webserver.</p>\n"
},
{
"answer_id": 166715,
"author": "Mote",
"author_id": 24789,
"author_profile": "https://Stackoverflow.com/users/24789",
"pm_score": 0,
"selected": false,
"text": "<p>Try using the functions for utf8-encoding and decoding. might help</p>\n"
},
{
"answer_id": 167494,
"author": "Christoffer",
"author_id": 24811,
"author_profile": "https://Stackoverflow.com/users/24811",
"pm_score": 1,
"selected": false,
"text": "<p>I finally figured it out. It might not be a nice way to do it, but it works. </p>\n\n<p>It seems like the array I was working with was in a different charset than the input character. I solved this by making a string of all the array elements and then use mb_strpos to search for the characters. So the only change to the code is the isNorwegianChar function. The new function looks like this:</p>\n\n<pre><code>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</code></pre>\n\n<p>Thanks for all the help!</p>\n"
},
{
"answer_id": 172359,
"author": "user22960",
"author_id": 22960,
"author_profile": "https://Stackoverflow.com/users/22960",
"pm_score": 0,
"selected": false,
"text": "<p>As the problem is to separate Norvegian word(s) from Chinese ones, why don't you use an explicit glyph to do so (I personnaly like \"¶\"), instead of relying on an algorithm ?</p>\n\n<p>impulsiv¶形 衝動的</p>\n\n<p>Then use <a href=\"http://fr.php.net/manual/en/function.mb-split.php\" rel=\"nofollow noreferrer\">mb-split</a>, or <a href=\"http://fr.php.net/manual/en/function.mb-substr.php\" rel=\"nofollow noreferrer\">mb-substr</a> combined with <a href=\"http://fr.php.net/manual/en/function.mb-strpos.php\" rel=\"nofollow noreferrer\">mb-strpos</a>.</p>\n\n<p>You can easily replace it with a space if you need to output the string!</p>\n\n<p>Sadly, PCRE in PHP doesn't allow us to use \\p with <a href=\"http://regexkit.sourceforge.net/Documentation/pcre/pcresyntax.html#SEC6\" rel=\"nofollow noreferrer\">script names</a>.</p>\n\n<p>(look for \"InMusicalSymbols\" in <a href=\"http://fr.php.net/manual/en/regexp.reference.php\" rel=\"nofollow noreferrer\">regexp.reference</a>, in § \"Unicode character properties\", to understand what I mean)</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24811/"
] |
I have some problems comparing an array with Norwegian characters with a utf8 character.
All characters except the special Norwegian characters(æ, ø, å) works fine.
```
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;
}
```
If anyone has any idea about what I can do pleas let me know.
**Update:**
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:
impulsiv 形 衝動的
imøtegå 動 反對,反駁
imøtekomme 動 符合
alkoholmisbruk(er) 名 濫用酒精 (名 濫用酒精的人)
alkoholpåvirket 形 受酒精影響的
alkotest 名 呼吸性酒精測試
alkymi(st) 名 煉金術 (名 煉金術士)
all, alt, alle, 形 全部, 所有
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.
The problem is that it æ, ø and å is not returned as a Norwegian character and it think the Chinese word has started.
Here is the 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);
```
|
First of all, and I'll get to UTF-8 later if nobody else answers, iterating like you are is a very bad way to search through an array. PHP has built-in functions just for that:
<http://fr.php.net/array_search>
So you might want to give that a try and see if it helps with your problem. Also make sure that the PHP file you're writing is also encoded in UTF-8!
**UPDATE:**
Try the following code, which works just fine on my server. If it doesn't work check that PHP is configured to work with UTF-8 by default, or add the necessary ini\_set calls.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head><title>norvegian utf-8 test</title>
<meta http-equiv="Content-type" value="text/html; charset=UTF-8" />
</head>
<body>
<?php
function isSpecial($char) {
$special_chars = array("æ", "ø", "å", "か");
return (array_search($char, $special_chars) !== false);
}
if (isset($_REQUEST["char"])) {
echo $_REQUEST["char"].(isSpecial($_REQUEST["char"])?" (true)":" (false)");
}
?>
<form method="POST" accept-charset="UTF-8">
<input type="text" name="char">
<input type="submit" value="submit">
</form>
</body>
</html>
```
|
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": "<p>In the particular case of repeating a single character, you can use <a href=\"http://www.cppreference.com/wiki/string/string_constructors\" rel=\"noreferrer\"><code>std::string(size_type count, CharT ch)</code></a>:</p>\n<pre><code>std::string(5, '.') + "lolcat"\n</code></pre>\n<p>This can't be used to repeat multi-character strings.</p>\n"
},
{
"answer_id": 166668,
"author": "Roskoto",
"author_id": 13635,
"author_profile": "https://Stackoverflow.com/users/13635",
"pm_score": 3,
"selected": false,
"text": "<p>You should write your own stream manipulator</p>\n<ul>\n<li><a href=\"http://www.two-sdg.demon.co.uk/curbralan/papers/WritingStreamManipulators.html\" rel=\"nofollow noreferrer\">http://www.two-sdg.demon.co.uk/curbralan/papers/WritingStreamManipulators.html</a></li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>cout << multi(5) << "whatever" << "lolcat";\n</code></pre>\n"
},
{
"answer_id": 166924,
"author": "camh",
"author_id": 23744,
"author_profile": "https://Stackoverflow.com/users/23744",
"pm_score": 5,
"selected": false,
"text": "<p>Use one of the forms of string::insert:</p>\n\n<pre><code>std::string str(\"lolcat\");\nstr.insert(0, 5, '.');\n</code></pre>\n\n<p>This will insert \".....\" (five dots) at the start of the string (position 0).</p>\n"
},
{
"answer_id": 167810,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 6,
"selected": false,
"text": "<p>There's no direct idiomatic way to repeat strings in C++ equivalent to the <b>*</b> operator in Python or the <b>x</b> operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well:</p>\n\n<pre><code>std::string(5, '.')\n</code></pre>\n\n<p>This is a contrived example of how you might use an ostringstream to repeat a string n times:</p>\n\n<pre><code>#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</code></pre>\n\n<p>Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.</p>\n"
},
{
"answer_id": 3193642,
"author": "Ian",
"author_id": 385391,
"author_profile": "https://Stackoverflow.com/users/385391",
"pm_score": 4,
"selected": false,
"text": "<p>I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation</p>\n\n<p><a href=\"http://www.java-samples.com/showtutorial.php?tutorialid=458\" rel=\"noreferrer\">http://www.java-samples.com/showtutorial.php?tutorialid=458</a></p>\n\n<pre><code>cout.width(11);\ncout.fill('.');\ncout << \"lolcat\" << endl;\n</code></pre>\n\n<p>outputs</p>\n\n<pre><code>.....lolcat\n</code></pre>\n"
},
{
"answer_id": 34321702,
"author": "Daniel",
"author_id": 2970186,
"author_profile": "https://Stackoverflow.com/users/2970186",
"pm_score": 4,
"selected": false,
"text": "<p>As Commodore Jaeger alluded to, I don't think any of the other answers actually answer this question; the question asks how to repeat a string, not a character.</p>\n\n<p>While the answer given by Commodore is correct, it is quite inefficient. Here is a faster implementation, the idea is to minimise copying operations and memory allocations by first exponentially growing the string:</p>\n\n<pre><code>#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</code></pre>\n\n<p>We can also define an <code>operator*</code> to get something closer to the Python version:</p>\n\n<pre><code>#include <utility>\n\nstd::string operator*(std::string str, std::size_t n)\n{\n return repeat(std::move(str), n);\n}\n</code></pre>\n\n<p>On my machine this is around 10x faster than the implementation given by Commodore, and about 2x faster than a naive <em>'append n - 1 times'</em> solution.</p>\n"
},
{
"answer_id": 49613515,
"author": "sorosh_sabz",
"author_id": 1539100,
"author_profile": "https://Stackoverflow.com/users/1539100",
"pm_score": 3,
"selected": false,
"text": "<p>You can use a C++ function for doing this:</p>\n<pre><code> 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</code></pre>\n"
},
{
"answer_id": 49743791,
"author": "Pavel P",
"author_id": 468725,
"author_profile": "https://Stackoverflow.com/users/468725",
"pm_score": 4,
"selected": false,
"text": "<p>For the purposes of the example provided by the OP std::string's ctor is sufficient: <code>std::string(5, '.')</code>.\nHowever, if anybody is looking for a function to repeat std::string multiple times:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 64919825,
"author": "claytonjwong",
"author_id": 8334739,
"author_profile": "https://Stackoverflow.com/users/8334739",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example of the string "abc" <code>repeated</code> 3 times:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#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</code></pre>\n"
},
{
"answer_id": 71564035,
"author": "Matthew M.",
"author_id": 7410473,
"author_profile": "https://Stackoverflow.com/users/7410473",
"pm_score": 1,
"selected": false,
"text": "<p>@Daniel provided an implementation that is significantly faster than other answers in its primary execution branch (where n > 1 and str is not empty). However, the corner cases are handled much more inefficiently than they could be.</p>\n<p>This implementation corrects those issues:</p>\n<pre><code>#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</code></pre>\n<p>A benchmark comparison of the two implementations on quick-bench.com shows the following differences in these corner cases. Clang 13.0 is the first number and GCC 10.3 is the second. -O3 optimization in all cases.</p>\n<ul>\n<li>For n == 0, this implementation is (9x / 11x) faster.</li>\n<li>For str.empty() == true, it is (2.4x / 3.4x) faster.</li>\n<li>For n == 1 and str.size() > 1, it is (2.1x / 1.4x) faster.</li>\n<li>And for str.size() == 1, it is (1.3x / 1.2x) faster.</li>\n</ul>\n<p>The problem with the original implementation boils down to passing <code>str</code> into the function by value. This invokes a copy of <code>str</code> on every call to <code>repeat</code> that is unnecessary in some of the corner cases; especially when n == 0.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
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?
E.g., in Python you could simply do
```
>>> "." * 5 + "lolcat"
'.....lolcat'
```
|
In the particular case of repeating a single character, you can use [`std::string(size_type count, CharT ch)`](http://www.cppreference.com/wiki/string/string_constructors):
```
std::string(5, '.') + "lolcat"
```
This can't be used to repeat multi-character strings.
|
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": 166654,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 4,
"selected": false,
"text": "<p>It all depends on what the vector's size implementation is, how aggressive the compiler is and if it listen/uses to inline directives.</p>\n\n<p>I would be more defensive and introduce the temporary as you don't have any guarantees about how efficient your compiler will be.</p>\n\n<p>Of course, if this routine is called once or twice and the vector is small, it really doesn't matter.</p>\n\n<p>If it will be called thousands of times, then I would use the temporary.</p>\n\n<p>Some might call this premature optimization, but I would tend to disagree with that assessment.<br>\nWhile you are trying to optimize the code, you are not investing time or obfuscating the code in the name of performance. </p>\n\n<p>I have a hard time considering what is a refactoring to be an optimization. But in the end, this is along the lines of \"you say tomato, I say tomato\"...</p>\n"
},
{
"answer_id": 166672,
"author": "Benny Wong",
"author_id": 2999,
"author_profile": "https://Stackoverflow.com/users/2999",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Benoit. The introduction of a new variable, especially an int or even a short will have a bigger benefit that calling it each time.</p>\n\n<p>It's one less thing to worry about if the loop ever gets large enough that it may impact performance.</p>\n"
},
{
"answer_id": 166673,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 1,
"selected": false,
"text": "<p>The size method from std::vector should be inlined by the compiler, meaning that every call to size() is replaced by its actual body (see the question <a href=\"https://stackoverflow.com/questions/132738/why-should-i-ever-use-inline-code\">Why should I ever use inline code</a> for more information about inlining). Since in most implementations size() basically computes the difference between end() and begin() (which should be inlined too), you don't have to worry too much about loss of performance.</p>\n\n<p>Moreover, if I remember correctly, some compilers are \"smart\" enough to detect the constness of an expression in the second part of the for construct, and generate code that evaluates the expression only once.</p>\n"
},
{
"answer_id": 166678,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 3,
"selected": false,
"text": "<p>Start with size() in the 'for' construct until you need to optimize for speed.</p>\n\n<p>If it is too slow, look for ways to make it faster, such as using a temporary variable to hold the result of size.</p>\n"
},
{
"answer_id": 166688,
"author": "Thomas Koschel",
"author_id": 2012356,
"author_profile": "https://Stackoverflow.com/users/2012356",
"pm_score": 1,
"selected": false,
"text": "<p>If you hold the size of the vector in a temporary variable, you will be independent of the compiler.</p>\n\n<p>My guess is, that most compilers will optimize the code in a way, that size() will be called only once. But using a temporary variable will give you a guarantee, size() will only be called once!</p>\n"
},
{
"answer_id": 166704,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 2,
"selected": false,
"text": "<p>Worth noting that even if you are dealing with millions of items the overhead is going to be negligible.</p>\n\n<p>In any case this should really be written using iterator - as there may be more overhead accessing a specific example.</p>\n\n<p>There is really no way that the compiler can assume that size() won't change - because it could do..</p>\n\n<p>If the order of iteration isn't important then you could always write it as which is slightly more efficient.</p>\n\n<pre><code>for (int i=v.size()-1; i>=0 ;i--)\n{\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 166774,
"author": "Curro",
"author_id": 10688,
"author_profile": "https://Stackoverflow.com/users/10688",
"pm_score": 1,
"selected": false,
"text": "<p>The compiler will not know if the value of .size() changes between calls, so it won't do any optimizations. I know you just asked about the use of .size(), but you should be using iterators anyway.</p>\n\n<pre><code>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</code></pre>\n\n<p>In this case, the call to .end() is similar to the problem you expose with .size(). If you know the loop does not perform any operation in the vector that invalidates the iterators, you can initialize an iterator to the .end() position prior to enter the loop and use that as your boundary.</p>\n"
},
{
"answer_id": 166885,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 1,
"selected": false,
"text": "<p>In such cases using iterators is cleaner - in some it's even faster. There's only one call to the container - getting the iterator holding a pointer to the vector member if there are any left, or null otherwise.</p>\n\n<p>Then of course <code>for</code> can become a <code>while</code> and there are no temporary variables needed at all - you can even pass an iterator to the sumVector function instead of a const reference/value.</p>\n"
},
{
"answer_id": 166888,
"author": "camh",
"author_id": 23744,
"author_profile": "https://Stackoverflow.com/users/23744",
"pm_score": 1,
"selected": false,
"text": "<p>Always write code the first time exactly as you mean it. If you are iterating over the vector from zero to size(), write it like that. Do not optimise the call to size() into a temporary variable unless you have profiled the call to be a bottleneck in your program that needs optimising.</p>\n\n<p>In all likelihood, a good compiler will be able to optimise away the call to size(), particularly given that the vector is declared as const.</p>\n"
},
{
"answer_id": 166903,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": true,
"text": "<p>Here's one way to do it that makes it explicit - size() is called only once.</p>\n\n<pre><code>for (size_t ii = 0, count = values.size(); ii < count; ++ii)\n</code></pre>\n\n<p><strong>Edit:</strong> I've been asked to actually answer the question, so here's my best shot.</p>\n\n<p>A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize.</p>\n\n<p>Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt.</p>\n\n<p>P.S. I wrote this before I read <a href=\"https://stackoverflow.com/questions/166641/is-using-size-for-the-2nd-expression-in-a-for-construct-always-bad#166654\">Benoit's</a> answer carefully, I believe we're in complete agreement.</p>\n"
},
{
"answer_id": 166985,
"author": "mxcl",
"author_id": 6444,
"author_profile": "https://Stackoverflow.com/users/6444",
"pm_score": 0,
"selected": false,
"text": "<p>Most, maybe even all, standard implementations of size() will be inlined by the compiler to what would be the equivalent of a temporary or at most a pointer dereference.</p>\n\n<p>However, you can never be sure. Inlining is about as hidden as these things get, and 3rd party containers may have virtual function tables - which means you may not get inlined.</p>\n\n<p>However, seriously, using a temporary reduces readability slightly for almost certainly no gain. Only optimise to a temporary if profiling says it is fruitful. If you make these micro optimisations everywhere, your code could become unreadable, perhaps even for yourself.</p>\n\n<p>As a slight aside, no compiler would optimise size() to one of call assigning to a temporary. There is almost no guarantee of const in C++. The compiler cannot risk assuming size() will return the same value for the whole loop. For example. Another thread could change the vector in between loop iterations.</p>\n"
},
{
"answer_id": 167022,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't part of the question but why are you using <code>at</code> in your code in place of the subscript operator <code>[]</code>?</p>\n\n<p>The sense in <code>at</code> is to ensure that no operation on an invalid index occurs. However, this will never be the case in your loop since you <em>know</em> from your code what the indices are going to be (always assuming single-threadedness).</p>\n\n<p>Even <em>if</em> your code contained a logical error, causing you to access an invalid element, <code>at</code> in this place would be useless because you don't expect the resulting exception and hence you don't treat it (or do you enclose <em>all</em> of your loops by <code>try</code> blocks?).</p>\n\n<p>The use of <code>at</code> here is misleading because it tells the reader that you (as a programmer) don't know what values the index will have – which is obviously wrong.</p>\n\n<p>I agree with Curro, this is a typical case for the use of iterators. Although this is more verbose (at least if you don't use constructs like <a href=\"http://engineering.meta-comm.com/resources/cs-win32_metacomm/doc/html/foreach.html\" rel=\"nofollow noreferrer\">Boost.Foreach</a>), it is also much more expressive and safer.</p>\n\n<p>Boost.Foreach would allow you to write the code as follows:</p>\n\n<pre><code>double sum = 0.0;\nforeach (double d, values)\n sum += d;\n</code></pre>\n\n<p>This operation is safe, efficient, short and readable.</p>\n"
},
{
"answer_id": 167405,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't matter at all. The performance overhead of .at() is so large (it contains a conditional throw statement) that a non-optimized version will spend most of its time there. An optimizing compiler smart enough to eliminiate the conditional throw will necessarily spot that size() does not change.</p>\n"
},
{
"answer_id": 167825,
"author": "Kaz Dragon",
"author_id": 24913,
"author_profile": "https://Stackoverflow.com/users/24913",
"pm_score": 3,
"selected": false,
"text": "<p>No matter the optimisation settings, putting the .size() call in the second expression will be <em>at most</em> as performant as outlining the .size() call before the for-loop. That is:</p>\n\n<pre><code>size_t size = values.size();\nfor (size_t ii = 0; ii < size; ++ii) {\n sum += values.at(ii)\n}\n</code></pre>\n\n<p>will always perform at least as well as, if not better than:</p>\n\n<pre><code>for (size_t ii = 0; ii < values.size(); ++ii) {\n sum += values.at(ii);\n}\n</code></pre>\n\n<p>In practice, it probably wont matter, since outlining the .size() call is a common compiler optimisation. However, I do find the second version easier to read.</p>\n\n<p>I find this even easier, though:</p>\n\n<pre><code>double sum = std::accumulate(values.begin(), values.end(), 0);\n</code></pre>\n"
},
{
"answer_id": 169645,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "<p>If you were using a container where <code>size()</code> was O(n) (like <code>std::list</code>) and not O(1) (like <code>std::vector</code>), you would not be iterating through that container using indices. You would be using iterators instead.</p>\n\n<p>Anyway, if the body of the loop is so trivial that recalculating <code>std::vector::size()</code> matters, then there is probably a more efficient (but possibly platform-specific) way to do the calculation, regardless of what it is. If the body of the loop is non-trivial, recalculating <code>std::vector::size()</code> each time is unlikely to matter.</p>\n"
},
{
"answer_id": 170641,
"author": "Dan Cristoloveanu",
"author_id": 24873,
"author_profile": "https://Stackoverflow.com/users/24873",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>If you are modifying the vector (adding or removing elements) in the for loop then you should not use a temporary variable since this could lead to bugs.</li>\n<li>If you are not modifying the vector size in the for loop then I would all the time use a temporary variable to store the size (this would make your code independant on the implementation details of vector::size.</li>\n</ul>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3229/"
] |
In the following example should I expect that `values.size()` will be called every time around the loop? In which case it might make sense to introduce a temporary `vectorSize` variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change.
```
double sumVector(const std::vector<double>& values) {
double sum = 0.0;
for (size_t ii = 0; ii < values.size(); ++ii) {
sum += values.at(ii);
}
}
```
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.
|
Here's one way to do it that makes it explicit - size() is called only once.
```
for (size_t ii = 0, count = values.size(); ii < count; ++ii)
```
**Edit:** I've been asked to actually answer the question, so here's my best shot.
A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize.
Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt.
P.S. I wrote this before I read [Benoit's](https://stackoverflow.com/questions/166641/is-using-size-for-the-2nd-expression-in-a-for-construct-always-bad#166654) answer carefully, I believe we're in complete agreement.
|
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": 166654,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 4,
"selected": false,
"text": "<p>It all depends on what the vector's size implementation is, how aggressive the compiler is and if it listen/uses to inline directives.</p>\n\n<p>I would be more defensive and introduce the temporary as you don't have any guarantees about how efficient your compiler will be.</p>\n\n<p>Of course, if this routine is called once or twice and the vector is small, it really doesn't matter.</p>\n\n<p>If it will be called thousands of times, then I would use the temporary.</p>\n\n<p>Some might call this premature optimization, but I would tend to disagree with that assessment.<br>\nWhile you are trying to optimize the code, you are not investing time or obfuscating the code in the name of performance. </p>\n\n<p>I have a hard time considering what is a refactoring to be an optimization. But in the end, this is along the lines of \"you say tomato, I say tomato\"...</p>\n"
},
{
"answer_id": 166672,
"author": "Benny Wong",
"author_id": 2999,
"author_profile": "https://Stackoverflow.com/users/2999",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Benoit. The introduction of a new variable, especially an int or even a short will have a bigger benefit that calling it each time.</p>\n\n<p>It's one less thing to worry about if the loop ever gets large enough that it may impact performance.</p>\n"
},
{
"answer_id": 166673,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 1,
"selected": false,
"text": "<p>The size method from std::vector should be inlined by the compiler, meaning that every call to size() is replaced by its actual body (see the question <a href=\"https://stackoverflow.com/questions/132738/why-should-i-ever-use-inline-code\">Why should I ever use inline code</a> for more information about inlining). Since in most implementations size() basically computes the difference between end() and begin() (which should be inlined too), you don't have to worry too much about loss of performance.</p>\n\n<p>Moreover, if I remember correctly, some compilers are \"smart\" enough to detect the constness of an expression in the second part of the for construct, and generate code that evaluates the expression only once.</p>\n"
},
{
"answer_id": 166678,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 3,
"selected": false,
"text": "<p>Start with size() in the 'for' construct until you need to optimize for speed.</p>\n\n<p>If it is too slow, look for ways to make it faster, such as using a temporary variable to hold the result of size.</p>\n"
},
{
"answer_id": 166688,
"author": "Thomas Koschel",
"author_id": 2012356,
"author_profile": "https://Stackoverflow.com/users/2012356",
"pm_score": 1,
"selected": false,
"text": "<p>If you hold the size of the vector in a temporary variable, you will be independent of the compiler.</p>\n\n<p>My guess is, that most compilers will optimize the code in a way, that size() will be called only once. But using a temporary variable will give you a guarantee, size() will only be called once!</p>\n"
},
{
"answer_id": 166704,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 2,
"selected": false,
"text": "<p>Worth noting that even if you are dealing with millions of items the overhead is going to be negligible.</p>\n\n<p>In any case this should really be written using iterator - as there may be more overhead accessing a specific example.</p>\n\n<p>There is really no way that the compiler can assume that size() won't change - because it could do..</p>\n\n<p>If the order of iteration isn't important then you could always write it as which is slightly more efficient.</p>\n\n<pre><code>for (int i=v.size()-1; i>=0 ;i--)\n{\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 166774,
"author": "Curro",
"author_id": 10688,
"author_profile": "https://Stackoverflow.com/users/10688",
"pm_score": 1,
"selected": false,
"text": "<p>The compiler will not know if the value of .size() changes between calls, so it won't do any optimizations. I know you just asked about the use of .size(), but you should be using iterators anyway.</p>\n\n<pre><code>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</code></pre>\n\n<p>In this case, the call to .end() is similar to the problem you expose with .size(). If you know the loop does not perform any operation in the vector that invalidates the iterators, you can initialize an iterator to the .end() position prior to enter the loop and use that as your boundary.</p>\n"
},
{
"answer_id": 166885,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 1,
"selected": false,
"text": "<p>In such cases using iterators is cleaner - in some it's even faster. There's only one call to the container - getting the iterator holding a pointer to the vector member if there are any left, or null otherwise.</p>\n\n<p>Then of course <code>for</code> can become a <code>while</code> and there are no temporary variables needed at all - you can even pass an iterator to the sumVector function instead of a const reference/value.</p>\n"
},
{
"answer_id": 166888,
"author": "camh",
"author_id": 23744,
"author_profile": "https://Stackoverflow.com/users/23744",
"pm_score": 1,
"selected": false,
"text": "<p>Always write code the first time exactly as you mean it. If you are iterating over the vector from zero to size(), write it like that. Do not optimise the call to size() into a temporary variable unless you have profiled the call to be a bottleneck in your program that needs optimising.</p>\n\n<p>In all likelihood, a good compiler will be able to optimise away the call to size(), particularly given that the vector is declared as const.</p>\n"
},
{
"answer_id": 166903,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": true,
"text": "<p>Here's one way to do it that makes it explicit - size() is called only once.</p>\n\n<pre><code>for (size_t ii = 0, count = values.size(); ii < count; ++ii)\n</code></pre>\n\n<p><strong>Edit:</strong> I've been asked to actually answer the question, so here's my best shot.</p>\n\n<p>A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize.</p>\n\n<p>Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt.</p>\n\n<p>P.S. I wrote this before I read <a href=\"https://stackoverflow.com/questions/166641/is-using-size-for-the-2nd-expression-in-a-for-construct-always-bad#166654\">Benoit's</a> answer carefully, I believe we're in complete agreement.</p>\n"
},
{
"answer_id": 166985,
"author": "mxcl",
"author_id": 6444,
"author_profile": "https://Stackoverflow.com/users/6444",
"pm_score": 0,
"selected": false,
"text": "<p>Most, maybe even all, standard implementations of size() will be inlined by the compiler to what would be the equivalent of a temporary or at most a pointer dereference.</p>\n\n<p>However, you can never be sure. Inlining is about as hidden as these things get, and 3rd party containers may have virtual function tables - which means you may not get inlined.</p>\n\n<p>However, seriously, using a temporary reduces readability slightly for almost certainly no gain. Only optimise to a temporary if profiling says it is fruitful. If you make these micro optimisations everywhere, your code could become unreadable, perhaps even for yourself.</p>\n\n<p>As a slight aside, no compiler would optimise size() to one of call assigning to a temporary. There is almost no guarantee of const in C++. The compiler cannot risk assuming size() will return the same value for the whole loop. For example. Another thread could change the vector in between loop iterations.</p>\n"
},
{
"answer_id": 167022,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't part of the question but why are you using <code>at</code> in your code in place of the subscript operator <code>[]</code>?</p>\n\n<p>The sense in <code>at</code> is to ensure that no operation on an invalid index occurs. However, this will never be the case in your loop since you <em>know</em> from your code what the indices are going to be (always assuming single-threadedness).</p>\n\n<p>Even <em>if</em> your code contained a logical error, causing you to access an invalid element, <code>at</code> in this place would be useless because you don't expect the resulting exception and hence you don't treat it (or do you enclose <em>all</em> of your loops by <code>try</code> blocks?).</p>\n\n<p>The use of <code>at</code> here is misleading because it tells the reader that you (as a programmer) don't know what values the index will have – which is obviously wrong.</p>\n\n<p>I agree with Curro, this is a typical case for the use of iterators. Although this is more verbose (at least if you don't use constructs like <a href=\"http://engineering.meta-comm.com/resources/cs-win32_metacomm/doc/html/foreach.html\" rel=\"nofollow noreferrer\">Boost.Foreach</a>), it is also much more expressive and safer.</p>\n\n<p>Boost.Foreach would allow you to write the code as follows:</p>\n\n<pre><code>double sum = 0.0;\nforeach (double d, values)\n sum += d;\n</code></pre>\n\n<p>This operation is safe, efficient, short and readable.</p>\n"
},
{
"answer_id": 167405,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't matter at all. The performance overhead of .at() is so large (it contains a conditional throw statement) that a non-optimized version will spend most of its time there. An optimizing compiler smart enough to eliminiate the conditional throw will necessarily spot that size() does not change.</p>\n"
},
{
"answer_id": 167825,
"author": "Kaz Dragon",
"author_id": 24913,
"author_profile": "https://Stackoverflow.com/users/24913",
"pm_score": 3,
"selected": false,
"text": "<p>No matter the optimisation settings, putting the .size() call in the second expression will be <em>at most</em> as performant as outlining the .size() call before the for-loop. That is:</p>\n\n<pre><code>size_t size = values.size();\nfor (size_t ii = 0; ii < size; ++ii) {\n sum += values.at(ii)\n}\n</code></pre>\n\n<p>will always perform at least as well as, if not better than:</p>\n\n<pre><code>for (size_t ii = 0; ii < values.size(); ++ii) {\n sum += values.at(ii);\n}\n</code></pre>\n\n<p>In practice, it probably wont matter, since outlining the .size() call is a common compiler optimisation. However, I do find the second version easier to read.</p>\n\n<p>I find this even easier, though:</p>\n\n<pre><code>double sum = std::accumulate(values.begin(), values.end(), 0);\n</code></pre>\n"
},
{
"answer_id": 169645,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "<p>If you were using a container where <code>size()</code> was O(n) (like <code>std::list</code>) and not O(1) (like <code>std::vector</code>), you would not be iterating through that container using indices. You would be using iterators instead.</p>\n\n<p>Anyway, if the body of the loop is so trivial that recalculating <code>std::vector::size()</code> matters, then there is probably a more efficient (but possibly platform-specific) way to do the calculation, regardless of what it is. If the body of the loop is non-trivial, recalculating <code>std::vector::size()</code> each time is unlikely to matter.</p>\n"
},
{
"answer_id": 170641,
"author": "Dan Cristoloveanu",
"author_id": 24873,
"author_profile": "https://Stackoverflow.com/users/24873",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>If you are modifying the vector (adding or removing elements) in the for loop then you should not use a temporary variable since this could lead to bugs.</li>\n<li>If you are not modifying the vector size in the for loop then I would all the time use a temporary variable to store the size (this would make your code independant on the implementation details of vector::size.</li>\n</ul>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] |
I am using [MailLogger](http://nant.sourceforge.net/release/0.85-rc2/help/fundamentals/listeners.html#MailLogger) 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?
|
Here's one way to do it that makes it explicit - size() is called only once.
```
for (size_t ii = 0, count = values.size(); ii < count; ++ii)
```
**Edit:** I've been asked to actually answer the question, so here's my best shot.
A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize.
Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt.
P.S. I wrote this before I read [Benoit's](https://stackoverflow.com/questions/166641/is-using-size-for-the-2nd-expression-in-a-for-construct-always-bad#166654) answer carefully, I believe we're in complete agreement.
|
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": "<p>It's in UIApplication:</p>\n\n<p><strong>For Objective C:</strong></p>\n\n<p>Start:</p>\n\n<pre><code>[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;\n</code></pre>\n\n<p>End:</p>\n\n<pre><code>[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;\n</code></pre>\n\n<p><strong>For swift :</strong></p>\n\n<p>Start</p>\n\n<pre><code>UIApplication.shared.isNetworkActivityIndicatorVisible = true\n</code></pre>\n\n<p>End</p>\n\n<pre><code>UIApplication.shared.isNetworkActivityIndicatorVisible = false\n</code></pre>\n"
},
{
"answer_id": 1750967,
"author": "Michael Waterfall",
"author_id": 106244,
"author_profile": "https://Stackoverflow.com/users/106244",
"pm_score": 5,
"selected": false,
"text": "<p>I've found the following macros pretty useful!</p>\n\n<pre><code>#define ShowNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = YES\n#define HideNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = NO\n</code></pre>\n\n<p>So you can just call <code>ShowNetworkActivityIndicator();</code> or <code>HideNetworkActivityIndicator();</code> from within your app (as long as the header is included of course!).</p>\n"
},
{
"answer_id": 13412791,
"author": "Resh32",
"author_id": 1611950,
"author_profile": "https://Stackoverflow.com/users/1611950",
"pm_score": 5,
"selected": false,
"text": "<p>I wrote a singleton that solves the problem of multiple connections by keeping a counter of what is happening (to avoid removing the status when a connection returns but another one is still active):</p>\n\n<p>The header file:</p>\n\n<pre><code>#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</code></pre>\n\n<p>and implementation:</p>\n\n<pre><code>#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</code></pre>\n\n<p>Example:</p>\n\n<pre><code> [[RMActivityIndicator sharedManager]increaseActivity];\n [NSURLConnection sendAsynchronousRequest:urlRequest queue:self.networkReceiveProcessQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)\n {\n [[RMActivityIndicator sharedManager]decreaseActivity];\n }\n</code></pre>\n"
},
{
"answer_id": 13623764,
"author": "asish",
"author_id": 1175051,
"author_profile": "https://Stackoverflow.com/users/1175051",
"pm_score": 4,
"selected": false,
"text": "<p>A single line code to do that:</p>\n\n<pre><code>[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;\n</code></pre>\n"
},
{
"answer_id": 29040799,
"author": "Sev",
"author_id": 2640458,
"author_profile": "https://Stackoverflow.com/users/2640458",
"pm_score": 2,
"selected": false,
"text": "<p>It might also be helpful to make sure you are running it on the main thread as it is UI related. </p>\n\n<pre><code>dispatch_async(dispatch_get_main_queue(), ^{\n [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];\n});\n</code></pre>\n"
},
{
"answer_id": 35449012,
"author": "Babu Lal",
"author_id": 4309479,
"author_profile": "https://Stackoverflow.com/users/4309479",
"pm_score": 3,
"selected": false,
"text": "<p>You need to take care of hiding the activity indicator also once your network call is done.</p>\n\n<p>If you use <code>AFNetworking</code>, then you don't need to do much.</p>\n\n<p>Do following changes in <code>AppDelegate</code> Class:</p>\n\n<ol>\n<li><p>Import <code>AFNetworking/AFNetworkActivityIndicatorManager.h</code></p></li>\n<li><p>Put this in <code>didFinishLaunchingWithOptions:</code></p></li>\n</ol>\n\n<p><code>[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]</code></p>\n"
},
{
"answer_id": 53200832,
"author": "erickva",
"author_id": 1931036,
"author_profile": "https://Stackoverflow.com/users/1931036",
"pm_score": 2,
"selected": false,
"text": "<p>As many have said, there is no network activity indicator for the iPhone X and probably for the other new iPhones with the notch.</p>\n\n<p>I came across this incredible library written by Ortwin Gentz, FutureTap:\n<a href=\"https://github.com/futuretap/FTLinearActivityIndicator\" rel=\"nofollow noreferrer\">https://github.com/futuretap/FTLinearActivityIndicator</a></p>\n\n<p>It puts the indicator right back where it was when the iPhone X was initially released, many would remember the Knight Rider type of indicator.</p>\n\n<p>This library is available for Swift 4.2, so you will need to change the Swift Language settings, as described here:\n<a href=\"https://stackoverflow.com/questions/46520306/type-nsattributedstringkey-aka-nsstring-has-no-member-font\">Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font'</a></p>\n"
},
{
"answer_id": 56697071,
"author": "M Reza",
"author_id": 3815069,
"author_profile": "https://Stackoverflow.com/users/3815069",
"pm_score": 3,
"selected": false,
"text": "<p>The status bar network activity indicator was deprecated in <strong>iOS 13</strong>. </p>\n\n<p>Using <code>UIApplication.shared.isNetworkActivityIndicatorVisible = true</code> will not work anymore.</p>\n\n<p>The deprecation message says:</p>\n\n<blockquote>\n <p>Provide a custom network activity UI in your app if desired.</p>\n</blockquote>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] |
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?
|
It's in UIApplication:
**For Objective C:**
Start:
```
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
```
End:
```
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
```
**For swift :**
Start
```
UIApplication.shared.isNetworkActivityIndicatorVisible = true
```
End
```
UIApplication.shared.isNetworkActivityIndicatorVisible = false
```
|
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": 166773,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 0,
"selected": false,
"text": "<p>An obvious question, but are you sure that you don't have a reference to MyControl from your Sheep object; be it an object or a list or anything? If this is the case this is what is preventing you from cloning your business object.</p>\n\n<p>The more than likely candidates would be a <strong>.Parent</strong> or <strong>.Tag</strong> property.</p>\n"
},
{
"answer_id": 166880,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "<p>Do you have an event that the UI is subscribing to? A {Foo}Changed event if data-binding, or perhaps INotifyPropertyChanged?\nYou might have to mark the event backing field as [NonSerialized] (or however attributes look in VB - I'm a C# person...). If you are using field-like-events (i.e. the abbreviated syntax without add/remove), then mark the entire event with [field: NonSerialized] (again, translate to VB).</p>\n"
},
{
"answer_id": 166883,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "<p>In third party libraries if something is not marked as serializable it <em>should</em> not be serialized for a good reason, but often its not serializable because the developer just simply didn't include it. You can use reflection to make a copy of the public properties of the control and return its state to your reflected version on a cancel. There are performance implications to this approach but because you are working at the UI tier I imagine it won't be much of a worry. This method is not guaranteed error free; public properties do not necessarily represent the entire state of a class and setting some properties may have side effects (they shouldn't, but you didn't write the code, so either ILDasm it and see or hope for the best).</p>\n\n<p>Additionally not all of the types of the properties may be serializable, in which case you need to go further by manually writing serialization routines for those types (and possibly those type's properties).</p>\n\n<pre><code>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</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6165/"
] |
**Background**
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.
The class I am trying to serialize is marked as "Serializable" along with the child objects that are contained within the class.
I have tested that the clone method works by writing code similar to the following:
```
Dim obj as New Sheep()
Dim dolly as Sheep = obj.Clone()
```
All works fine at this point.
**Problem**
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).
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.
My thought would be to write code along the lines of the following:
```
Dim copy as Sheep = MyControl.Sheep.Clone()
```
Then allow the user to manipulate the properties on `MyControl.Sheep`. When I attempt to do this however, the clone method throws an exception stating:
*Type 'MyControl' in Assembly 'My\_Assembly\_Info\_Here' is not marked as serializable*
This error is thrown at the point where I call `BinaryFormatter.Serialize(stream,Me)`.
I have tried creating a method on `MyControl` that returns a copy of the object and also first assigning `MyControl.Sheep` 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!
Any idea's where I am going wrong?
**Solution**
Marc's answer helped point me in the right direction on this one. [This](http://www.lhotka.net/WeBlog/CommentView.aspx?guid=776f44e8-aaec-4845-b649-e0d840e6de2c) blog post from Rocky Lhotka explains the problem and how to solve it.
|
Do you have an event that the UI is subscribing to? A {Foo}Changed event if data-binding, or perhaps INotifyPropertyChanged?
You might have to mark the event backing field as [NonSerialized] (or however attributes look in VB - I'm a C# person...). If you are using field-like-events (i.e. the abbreviated syntax without add/remove), then mark the entire event with [field: NonSerialized] (again, translate to VB).
|
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": 166825,
"author": "Thad",
"author_id": 24500,
"author_profile": "https://Stackoverflow.com/users/24500",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the sp_MSforeacheachdb.</p>\n\n<p>sp_MSforeachdb 'IF EXISTS(SELECT * FROM sys.tables WHERE [Name] = ''TableName'') PRINT ''?''';</p>\n"
},
{
"answer_id": 166866,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 1,
"selected": false,
"text": "<p>use master </p>\n\n<p>DECLARE @db_name varchar(128)\nDECLARE @DbID int\nDECLARE @sql_string nvarchar(4000)\nDECLARE @TableName varchar(30) </p>\n\n<p>Select @TableName = ''</p>\n\n<p>set nocount on</p>\n\n<p>CREATE TABLE [#tblDatabaseName] (\n [DbName] [varchar] (128) NOT NULL ,\n [TableName] [varchar] (128) NOT NULL ) </p>\n\n<p>declare db_cursor cursor forward_only for</p>\n\n<pre><code>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</code></pre>\n\n<p>open db_cursor</p>\n\n<p>fetch next from db_cursor into @db_name, @DbID</p>\n\n<p>while @@FETCH_STATUS = 0\nbegin</p>\n\n<pre><code>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</code></pre>\n\n<p>end </p>\n\n<p>deallocate db_cursor</p>\n\n<p>select * from #tblDatabaseName</p>\n\n<p>drop table #tblDatabaseName</p>\n"
},
{
"answer_id": 166932,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": 1,
"selected": false,
"text": "<p>sp_MSForEachDB is an undocumented proc that could do this for you. Getting the output out is a little harder so I'll leave that for you.</p>\n\n<pre><code>EXEC sp_MSForEachDB 'USE [?] IF EXISTS(SELECT * FROM Sys.Objects WHERE Type = ''U'' AND Name = ''Product'') PRINT ''?'''\n</code></pre>\n"
},
{
"answer_id": 202354,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 3,
"selected": true,
"text": "<p>As above but use system function not system tables</p>\n\n<pre><code>EXEC sp_MSForEachDB 'USE [?] IF OBJECT_ID(''dbo.mytable'') IS NOT NULL PRINT ''?'''\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5716/"
] |
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?
|
As above but use system function not system tables
```
EXEC sp_MSForEachDB 'USE [?] IF OBJECT_ID(''dbo.mytable'') IS NOT NULL PRINT ''?'''
```
|
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": "<p>Try</p>\n\n<pre><code>float f = BitConverter.ToSingle(bytearray, 0);\n</code></pre>\n\n<p>In VB (I think):</p>\n\n<pre><code>Dim single s;\ns = BitConverter.ToSingle(bytearray, 0);\n</code></pre>\n"
},
{
"answer_id": 171829,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "<pre><code>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</code></pre>\n\n<p>The fastest way to do this (in terms of performance as opposed to how long it takes to write) would probably be to use the <a href=\"http://www.codeproject.com/KB/vb/netcopymemorysample.aspx\" rel=\"nofollow noreferrer\">CopyMemory</a> API call.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2135219/"
] |
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 ?
The code that gets it is
```
CType(Me._applicationBuffer.Read(Me._nextCaptureOffset, GetType(Byte), LockFlag.None, LockSize), Byte())
```
which creates the byte array, can Ctype handle single ? (note, I can't figure out a way to do it!)
|
```
public float[] ByteArrayToFloatArray(byte[] byteArray)
{
float[] floatArray = new float[byteArray.Length / 4];
for (int i = 0; i < floatArray.Length; i++)
{
floatArray[i] = BitConverter.ToSingle(byteArray, i * 4);
}
return floatArray;
}
```
The fastest way to do this (in terms of performance as opposed to how long it takes to write) would probably be to use the [CopyMemory](http://www.codeproject.com/KB/vb/netcopymemorysample.aspx) API call.
|
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": "<pre><code>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</code></pre>\n\n<p>From the <a href=\"https://stackoverflow.com/questions/127776/where-can-you-find-the-c-language-specifications\">C# specification</a> 2.4.4.2 Integer literals and 2.4.4.3 Real literals. Take note that L and UL are preferred as opposed to their lowercase variants for clarity as recommended by <a href=\"https://stackoverflow.com/users/22656/jon-skeet\">Jon Skeet</a>.</p>\n"
},
{
"answer_id": 166787,
"author": "Nic Wise",
"author_id": 2947,
"author_profile": "https://Stackoverflow.com/users/2947",
"pm_score": 3,
"selected": false,
"text": "<p>You might want to start by <a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx\" rel=\"noreferrer\">looking at the C# language spec</a>. Most of the types are listed in there, and have a suffix:</p>\n\n<ul>\n<li>L = long</li>\n<li>F = float</li>\n<li>U = uint</li>\n<li>ulong's are a <a href=\"http://msdn.microsoft.com/en-us/library/t98873t4(VS.71).aspx\" rel=\"noreferrer\">little different</a> </li>\n<li>m = decimal (money)</li>\n<li>D = double</li>\n</ul>\n\n<p>Of course, if you stop using <em>var</em> then you get around the whole problem, and your code becomes more readable (ok, thats subjective, but for something like this, it's more readable by other people:</p>\n\n<pre><code>var x = 0; //whats x?\nfloat x = 0; //oh, it's a float\nbyte x = 0; // or not!\n</code></pre>\n"
},
{
"answer_id": 166809,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "<p>If you don't want to have to remember them, then the compiler also accepts a cast for the same purpose (you can check the IL that the effect is the same - i.e. the compiler, not the runtime, does the cast). To borrow the earlier example:</p>\n\n<pre><code> 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</code></pre>\n\n<p>And for the record, I agree that \"var\" is a bad choice here; I'll happily use var for a SortedDictionary<SomeLongType, SomeOtherLongType>, but for \"int\" it is just lazy...</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6276/"
] |
Does anyone know the full list of C# compiler number literal modifiers?
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...
```
var x = 0; // x is Int32
var y = 0f; // y is Single
```
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.
|
```
var y = 0f; // y is single
var z = 0d; // z is double
var r = 0m; // r is decimal
var i = 0U; // i is unsigned int
var j = 0L; // j is long (note capital L for clarity)
var k = 0UL; // k is unsigned long (note capital L for clarity)
```
From the [C# specification](https://stackoverflow.com/questions/127776/where-can-you-find-the-c-language-specifications) 2.4.4.2 Integer literals and 2.4.4.3 Real literals. Take note that L and UL are preferred as opposed to their lowercase variants for clarity as recommended by [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet).
|
166,772 |
<p>I am trying to update a custom firefox extension that I created for some tasks at work. Basically it is a sidebar that pulls up one of our webpages in an iframe for various purposes. When moving to Firefox 3 the iframe won't appear at all.</p>
<p>Below is an example of the XUL files that contains extension specific code including iframe, currently with just an attempt to load google but it it won't work with anything. I can't find any mention online of changes in FF3 that would cause this. Any suggestions would be appreciated.</p>
<pre><code><?xml version="1.0"?>
<?xml-stylesheet href="chrome://customsidebar/skin/customsidebar.css" type="text/css"?>
<overlay id="customsidebar-Main" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript" src="chrome://customsidebar/content/customsidebar.js"/>
<vbox flex="1">
<toolbar>
<vbox>
<hbox id="customsidebar_TopToolbarRow">
<toolbarbutton label="Refresh" id="customsidebar_Refresh" oncommand="customsidebar_Refresh()" />
</hbox>
<hbox>
<label control="customsidebar_StatusBox" value="Log"/>
<textbox id="customsidebar_StatusBox" multiline="true" rows="1" wrap="off" />
</hbox>
</vbox>
</toolbar>
<iframe id="customsidebar_Iframe" src="http://www.google.com" />
</vbox>
</overlay>
</code></pre>
<p>Here is the overlay XUL file</p>
<pre><code><?xml version="1.0"?>
<overlay id="CustomSidebar-Overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<menupopup id="viewSidebarMenu">
<menuitem observes="viewCustomSidebar" />
</menupopup>
<broadcasterset id="mainBroadcasterSet">
<broadcaster id="viewCustomSidebar"
autoCheck="false"
label="CustomSidebar"
type="checkbox" group="sidebar"
sidebarurl="chrome://customersidebar/content/customersidebarMain.xul"
sidebartitle="CustomSidebar"
oncommand="toggleSidebar('viewCustomSidebar');"/>
</broadcasterset>
</overlay>
</code></pre>
|
[
{
"answer_id": 166878,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 1,
"selected": false,
"text": "<p>I would try setting flex=\"1\" on the iframe. If that's not working, perhaps try it with the <a href=\"http://developer.mozilla.org/en/XUL/browser\" rel=\"nofollow noreferrer\">browser</a> element instead of iframe.</p>\n"
},
{
"answer_id": 168153,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li>Set flex=\"1\" on the iframe</li>\n<li>The XUL code for sidebar is not an overlay, it's a document loaded inside an iframe (look at the Firefox main window in the DOM inspector). So the root element should be <page>, not <overlay>. This, combined with the flex=\"1\", should make the page display.</li>\n<li>You usually want to put type=\"content\" or type=\"content-primary\" on the iframe. Definitely so if you load untrusted pages in it.</li>\n</ol>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8345/"
] |
I am trying to update a custom firefox extension that I created for some tasks at work. Basically it is a sidebar that pulls up one of our webpages in an iframe for various purposes. When moving to Firefox 3 the iframe won't appear at all.
Below is an example of the XUL files that contains extension specific code including iframe, currently with just an attempt to load google but it it won't work with anything. I can't find any mention online of changes in FF3 that would cause this. Any suggestions would be appreciated.
```
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://customsidebar/skin/customsidebar.css" type="text/css"?>
<overlay id="customsidebar-Main" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript" src="chrome://customsidebar/content/customsidebar.js"/>
<vbox flex="1">
<toolbar>
<vbox>
<hbox id="customsidebar_TopToolbarRow">
<toolbarbutton label="Refresh" id="customsidebar_Refresh" oncommand="customsidebar_Refresh()" />
</hbox>
<hbox>
<label control="customsidebar_StatusBox" value="Log"/>
<textbox id="customsidebar_StatusBox" multiline="true" rows="1" wrap="off" />
</hbox>
</vbox>
</toolbar>
<iframe id="customsidebar_Iframe" src="http://www.google.com" />
</vbox>
</overlay>
```
Here is the overlay XUL file
```
<?xml version="1.0"?>
<overlay id="CustomSidebar-Overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<menupopup id="viewSidebarMenu">
<menuitem observes="viewCustomSidebar" />
</menupopup>
<broadcasterset id="mainBroadcasterSet">
<broadcaster id="viewCustomSidebar"
autoCheck="false"
label="CustomSidebar"
type="checkbox" group="sidebar"
sidebarurl="chrome://customersidebar/content/customersidebarMain.xul"
sidebartitle="CustomSidebar"
oncommand="toggleSidebar('viewCustomSidebar');"/>
</broadcasterset>
</overlay>
```
|
1. Set flex="1" on the iframe
2. The XUL code for sidebar is not an overlay, it's a document loaded inside an iframe (look at the Firefox main window in the DOM inspector). So the root element should be <page>, not <overlay>. This, combined with the flex="1", should make the page display.
3. You usually want to put type="content" or type="content-primary" on the iframe. Definitely so if you load untrusted pages in it.
|
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": "<p>As long as each class has a default constructor:</p>\n\n<pre><code> public B instance() throws Exception {\n return getClass().newInstance();\n }\n</code></pre>\n"
},
{
"answer_id": 166861,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I think this might be possible to do using reflection, i.e. in your superclass you have:</p>\n\n<pre><code>public ClassName getFoo() throws InstantiationException, IllegalAccessException\n{\n return getClass().newInstance();\n}\n</code></pre>\n\n<p>Where ClassName is the name of your base class.</p>\n\n<p>You'll have to cast it wherever you want to use it though... I'm not sure this is really a great solution!</p>\n\n<p><b>Edit:</b> newInstance() type methods are usually static, and of course you won't have an idea of what the type of your subclass is with a static method.</p>\n\n<p>I don't think there's any way of getting a <em>static</em> method to (dynamically) create an instance of a subclass.</p>\n"
},
{
"answer_id": 166877,
"author": "MattC",
"author_id": 21126,
"author_profile": "https://Stackoverflow.com/users/21126",
"pm_score": 1,
"selected": false,
"text": "<p>Well, I could be off but I would assume that since \"this\" always refers to the current object, you could do something like</p>\n\n<pre><code>public B foo() {\n return this.getClass().newInstance();\n}\n</code></pre>\n\n<p>or something along those lines? If you create an instance of D and then call d.foo() you should get an instance of D returned as a B. You could return it as a plain Object but you should be as specific as possible in this instance, I think.</p>\n"
},
{
"answer_id": 166896,
"author": "Jake",
"author_id": 10675,
"author_profile": "https://Stackoverflow.com/users/10675",
"pm_score": 0,
"selected": false,
"text": "<p>@Rik</p>\n\n<p>Well, the real problem is that I have a abstract base class Thing. And Thing has a method called getNextThing() which returns a new instance of Thing.</p>\n\n<p>Then, I have a number of subclasses like BigThing, LittleThing, SomethingThing, and I don't want to keep rewriting the getNextThing() method for each of them. It seems wasteful, since they all do the same... thing.</p>\n\n<p>Am I incorrect in my approach?</p>\n"
},
{
"answer_id": 166934,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure why you're trying to do what you're actually trying to do. Providing more of a context might let us give you more help.</p>\n\n<pre><code>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</code></pre>\n\n<p>Let me offer you this piece of advice. The way CS classes tend to be taught is that professors are enamored with inheritance, but haven't figured out composition. I think What you might be looking for is composition. So instead of calling getNextThing on the Thing itself, maybe you should think about making Thing implement <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterable.html\" rel=\"nofollow noreferrer\">Iterable</a></p>\n\n<p>This means you will just need to write an <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Iterator.html\" rel=\"nofollow noreferrer\">Iterator</a> that can encapsulate the logic of getting the next thing, as it doesn't seem to fit into your inheritance model. Another advantage of this is that you get some nice syntactic devices out of this (enhanced for loop comprehension).</p>\n"
},
{
"answer_id": 166949,
"author": "Bruno Ranschaert",
"author_id": 4900,
"author_profile": "https://Stackoverflow.com/users/4900",
"pm_score": 1,
"selected": false,
"text": "<p>Apart from the fact that I think there probably is a design flaw if you want to accomplish this, you could try the following approach.</p>\n\n<p>In your question, you are using static (class) methods, B.foo(), D.foo(), this cannot be accomplished using inheritance because the static methods do not have a dynamic nature, they do not take part in the lookup system. So you don't have enough type information.</p>\n\n<p>If you are using a member function foo() you could have the following construct:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 166959,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 1,
"selected": false,
"text": "<p>As the other answers say, you can use getClass().newInstance() if there is a no-argument constructor in each subclass (make sure to catch InstantiationException and IllegalAccessException).</p>\n\n<p>If any of the constructors require arguments, you can either use reflection or (preferable in my view) define a method like getNewInstance() which you can override in the subclass only if needed.</p>\n\n<p>e.g.</p>\n\n<pre><code>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</code></pre>\n\n<p>Then getNewInstance() can be overridden only if you really need to, for subclasses that don't have the default constructor.</p>\n\n<pre><code>Thing getNewInstance() {\n return new BigThing(10, ThingSize.METRES);\n}\n</code></pre>\n"
},
{
"answer_id": 167163,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 3,
"selected": true,
"text": "<p>Don't. Make the \"foo\" method abstract.</p>\n\n<pre><code>abstract class B {\n public abstract B foo();\n}\n</code></pre>\n\n<p>Or receive an abstract factory through the base class constructor:</p>\n\n<pre><code>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</code></pre>\n\n<p>Add covariant return types and generics to taste.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
] |
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.
Is this possible?
|
Don't. Make the "foo" method abstract.
```
abstract class B {
public abstract B foo();
}
```
Or receive an abstract factory through the base class constructor:
```
abstract class B {
private final BFactory factory;
protected B(BFactory factory) {
this.factory = factory;
}
public B foo() {
return factory.create();
}
}
interface BFactory {
B create();
}
```
Add covariant return types and generics to taste.
|
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": 166890,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 0,
"selected": false,
"text": "<p>You could use IPC Channels: <a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6143016.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6143016.html</a></p>\n\n<p>Or maybe two way remoting: <a href=\"http://www.codeproject.com/KB/IP/TwoWayRemoting.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/IP/TwoWayRemoting.aspx</a></p>\n\n<p>The database route would be <em>simple</em>, but not necessarily the best.</p>\n"
},
{
"answer_id": 166893,
"author": "Ian Jacobs",
"author_id": 22818,
"author_profile": "https://Stackoverflow.com/users/22818",
"pm_score": 1,
"selected": false,
"text": "<p>WMI calls should give you what you need. You can catch started/finished events and do what you need to from there. (Thanks to Chris Lively for showing me this)</p>\n\n<p><a href=\"http://weblogs.asp.net/whaggard/archive/2006/02/11/438006.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://weblogs.asp.net/whaggard/archive/2006/02/11/438006.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/whaggard/archive/2006/02/11/438006.aspx</a></a></p>\n\n<p>Alternatively you can use System.Diagnostics.Processes namespace to query for one particular active process, and loop until the process is killed.</p>\n"
},
{
"answer_id": 166951,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 4,
"selected": true,
"text": "<p>You can pass a <code>Semaphore</code> name to the service on the command line (or via some other mechanism, like <em>hard coding</em>), and then wait on the service to <code>Release()</code> it, by calling <code>WaitOne()</code> in your exe.</p>\n\n<p>App code:</p>\n\n<pre><code>Semaphore s = new Semaphore(1, 1, \"MyNamedSemaphore\");\n// start service, passing the string \"MyNamedSemaphore\"\ns.WaitOne(); // will wait for Release() in service\n</code></pre>\n\n<p>Service code:</p>\n\n<pre><code>// 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</code></pre>\n"
},
{
"answer_id": 166975,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 1,
"selected": false,
"text": "<p>Can you modify the service code? </p>\n\n<p>If so, use a kernel Event object - the service can create one, your app can wait for it to be signalled, and the service can signal it when its finished. You'll have to give the event a name for it to be used cross-process but that's about as simple as it gets. The service can even continue to run with the event code present, no-one will notice unless they try to create an event with the same name. (or, your testapp could create the event, the service can then try to open it, depending which one is started first. If it succeeds, it can performs its triggering, otherwise it works as usual).</p>\n\n<p>Hint: you want a auto-reset event which 'flips' its state back immediately its triggered all waiting threads.</p>\n\n<p>I'm not sure of the .NET routines, but you want the Win32 CreateEvent, SetEvent, and WaitForSingleObject.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] |
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.
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)?
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?
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. ;-)
Also, this is purely for integration testing purposes, and will never go into production, so "simple" is the operative word.
|
You can pass a `Semaphore` name to the service on the command line (or via some other mechanism, like *hard coding*), and then wait on the service to `Release()` it, by calling `WaitOne()` in your exe.
App code:
```
Semaphore s = new Semaphore(1, 1, "MyNamedSemaphore");
// start service, passing the string "MyNamedSemaphore"
s.WaitOne(); // will wait for Release() in service
```
Service code:
```
// perform the initial task
// find semaphore name (i.e. from Environment.CommandLine)
Semaphore s = new Semaphore(1, 1, semaphoreName); // will use existing kernel object
s.Release(); // WaitOne in exe will complete
```
|
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": "<p>You are looking for <code>System.Text.RegularExpressions</code>;</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\nRegex r = new Regex(\"=C0\");\nstring output = r.Replace(text);\n</code></pre>\n\n<p>To get PHP's array behaviour the way you have you need multiple instances of `Regex</p>\n\n<p>However, in your example, you'd be much better served by .Replace(old, new), it's much faster than compiling state machines.</p>\n"
},
{
"answer_id": 166939,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>Real men use regular expressions, but here is an extension method that adds it to String if you wanted it:</p>\n\n<pre><code>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</code></pre>\n\n<p>You use it like this:</p>\n\n<pre><code> 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</code></pre>\n"
},
{
"answer_id": 166940,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>You can use .Select() (in .NET 3.5 and C# 3) to ease applying functions to members of a collection.</p>\n\n<pre><code>stringsList.Select( s => replacementsList.Select( r => s.Replace(s,r) ) );\n</code></pre>\n\n<p>You don't need regexp support, you just want an easy way to iterate over the arrays.</p>\n"
},
{
"answer_id": 167116,
"author": "Programmin Tool",
"author_id": 21691,
"author_profile": "https://Stackoverflow.com/users/21691",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Edit: Uhg I just realized this question was for 2.0, but I'll leave it in case you do have access to 3.5.</strong></p>\n\n<p>Just another take on the Linq thing. Now I used List<Char> instead of Char[] but that's just to make it look a little cleaner. There is no IndexOf method on arrays but there is one on List. Why did I need this? Well from what I am guessing, there is no direct correlation between the replacement list and the list of ones to be replaced. Just the index. </p>\n\n<p>So with that in mind, you can do this with Char[] just fine. But when you see the IndexOf method, you have to add in a .ToList() before it.</p>\n\n<p>Like this: someArray.ToList().IndexOf</p>\n\n<pre>\n String text;\n List<Char> patternsToReplace;\n List<Char> patternsToUse;\n\n patternsToReplace = new List<Char>();\n patternsToReplace.Add('a');\n patternsToReplace.Add('c');\n patternsToUse = new List<Char>();\n patternsToUse.Add('X');\n patternsToUse.Add('Z');\n\n text = \"This is a thing to replace stuff with\";\n\n var allAsAndCs = text.ToCharArray()\n .Select\n (\n currentItem => patternsToReplace.Contains(currentItem) \n ? patternsToUse[patternsToReplace.IndexOf(currentItem)] \n : currentItem\n )\n .ToArray();\n\n text = new String(allAsAndCs);\n</pre>\n\n<p>This just converts the text to a character array, selects through each one. If the current character is not in the replacement list, just send back the character as is. If it is in the replacement list, return the character in the same index of the replacement characters list. Last thing is to create a string from the character array.</p>\n\n<pre>\n using System;\n using System.Collections.Generic;\n using System.Linq;\n</pre>\n"
},
{
"answer_id": 167296,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": true,
"text": "<pre><code>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</code></pre>\n\n<p>Here is what I will use. Some code of Jonathan Holland but not in C#3.5 but in C#2.0 :)</p>\n\n<p>Thx all.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
What is the PHP preg\_replace in C#?
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").
```
$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';
$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);
```
|
```
public static class StringManipulation
{
public static string PregReplace(string input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
throw new ArgumentException("Replacement and Pattern Arrays must be balanced");
for (int i = 0; i < pattern.Length; i++)
{
input = Regex.Replace(input, pattern[i], replacements[i]);
}
return input;
}
}
```
Here is what I will use. Some code of Jonathan Holland but not in C#3.5 but in C#2.0 :)
Thx all.
|
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": "<p>To quote the <a href=\"http://maven.apache.org/pom.html#Profiles\" rel=\"noreferrer\">Maven documentation on this</a>:</p>\n\n<blockquote>A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment. <i>Or dependencies may be pulled from different repositories based upon the JDK version used</i>.</blockquote>\n\n<p>(Emphasis is mine)</p>\n\n<p>Just put the dependency for the <code>release</code> profile inside the profile declaration itself and do the same for <code>debug</code>.</p>\n\n<pre>\n<profiles>\n <profile>\n <id>debug</id>\n …\n <dependencies>\n <dependency>…</dependency>\n </dependencies>\n …\n </profile>\n <profile>\n <id>release</id>\n …\n <dependencies>\n <dependency>…</dependency>\n </dependencies>\n …\n </profile>\n</profiles>\n</pre>\n"
},
{
"answer_id": 1157516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Your groupId, artifactId should be tokenized in your profiles as properties and you can move your dependencies to the generic section.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
] |
Is it possible to have a different set of dependencies in a maven pom.xml file for different profiles?
e.g.
```
mvn -P debug
mvn -P release
```
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.
|
To quote the [Maven documentation on this](http://maven.apache.org/pom.html#Profiles):
> A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment. *Or dependencies may be pulled from different repositories based upon the JDK version used*.
(Emphasis is mine)
Just put the dependency for the `release` profile inside the profile declaration itself and do the same for `debug`.
```
<profiles>
<profile>
<id>debug</id>
…
<dependencies>
<dependency>…</dependency>
</dependencies>
…
</profile>
<profile>
<id>release</id>
…
<dependencies>
<dependency>…</dependency>
</dependencies>
…
</profile>
</profiles>
```
|
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": "<p>If I'm not misunderstanding your requirement, I was able to achieve formatting of the value in the input box during the rendering of the view with:</p>\n\n<pre><code><h:inputText id=\"text1\" value=\"#{...}\">\n <f:convertNumber pattern=\"#,###,##0.00\"/>\n</h:inputText>\n</code></pre>\n\n<p>I was using the Standard Faces Components in my vendor-branded Eclipse so I'm assuming the <code>pattern</code> attribute is part of standard JSF.</p>\n"
},
{
"answer_id": 168434,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 1,
"selected": false,
"text": "<p>If what you are trying to do is make the value of the input text field change on screen (to correct user input), you should probably look into using one of the JSF ajax frameworks like <a href=\"http://livedemo.exadel.com/richfaces-demo/richfaces/support.jsf?c=support&tab=usage\" rel=\"nofollow noreferrer\">Rich Faces</a>. </p>\n\n<p>A possible example would look like this:</p>\n\n<pre><code><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</code></pre>\n\n<p>I haven't tested this, but I think it may work.</p>\n"
},
{
"answer_id": 19330604,
"author": "Mosty Mostacho",
"author_id": 268273,
"author_profile": "https://Stackoverflow.com/users/268273",
"pm_score": 0,
"selected": false,
"text": "<p>It seems you're actually formatting a currency. There already exists a specific formatter to handle currencies that you can assign many options to:</p>\n\n<pre><code><f:convertNumber type=\"currency\" />\n</code></pre>\n\n<p>Some interesting attributes of this tag are: <code>locale</code>, <code>currencyCode</code>, <code>integerOnly</code>, <code>currencySymbol</code> and <code>pattern</code>.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24828/"
] |
I have a problem similar to the one found here : [JSF selectItem label formatting](https://stackoverflow.com/questions/86531/jsf-selectitem-label-formatting).
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?
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.
My code so far:
```
<h:inputText id="december" value="#{budgetMB.december}" onchange="setDirty()" styleClass="StandardBlack">
<f:convertNumber maxFractionDigits="2" groupingUsed="false" />
</h:inputText>
```
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.
|
If I'm not misunderstanding your requirement, I was able to achieve formatting of the value in the input box during the rendering of the view with:
```
<h:inputText id="text1" value="#{...}">
<f:convertNumber pattern="#,###,##0.00"/>
</h:inputText>
```
I was using the Standard Faces Components in my vendor-branded Eclipse so I'm assuming the `pattern` attribute is part of standard JSF.
|
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": "<p>I'm not sure of the etiquette of answering your own question... but having experimented in a trial-and-error way, here's how I've managed to get Selenium working with PHP/Firefox3 on Ubuntu.</p>\n\n<ol>\n<li>I downloaded RC and copied the php client directory to /usr/share/php as 'Selenium'</li>\n<li>I navigated to the Selenium Server directory in the download, and started selenium with <code>java -jar selenium-server.jar</code></li>\n<li>I created a new Firefox profile (by running firefox -ProfileManager). I called the new Profile 'Selenium'</li>\n<li>Within that profile, I editing the Firefox Network preferences to proxy all protocols via localhost port 4444.</li>\n<li><p>I created my php script and ran it with this command:</p>\n\n<p><code>php -d include_path=\".:/usr/share/php:/usr/share/php/Selenium/PEAR\" test.php</code></p></li>\n</ol>\n\n<p>I've listed my (basic, non-PHPUnit, non-OO) first test script below for reference.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 3192944,
"author": "Deepan Chakravarthy",
"author_id": 271764,
"author_profile": "https://Stackoverflow.com/users/271764",
"pm_score": 1,
"selected": false,
"text": "<p>I use phpunit, selenium RC php api to run my testcases. My testcase looks like </p>\n\n<pre><code>\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\", \"[email protected]\");\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</code></pre>\n\n<p>This will connect to browsers running inside virtual machines </p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24106/"
] |
I am trying to get [Selenium RC](http://selenium-rc.openqa.org/tutorial.html) working with Firefox 3 on Linux with PHP/Apache but am experiencing problems. Here's what I've done:
* I have installed the Firefox Selenium-IDE extension.
* 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
* I have a PHP script as follows:
PHP:
```
require_once 'Testing/Selenium.php';
$browser = new Testing_Selenium("*custom /usr/lib/firefox-3.0.3/firefox", "https://www.example.com");
$browser->start();
```
When I run the PHP script, it does launch a new Firefox tab, but **I get this error message**:
```
The requested URL /selenium-server/core/RemoteRunner.html was not found on this server.
```
I have had more success with Firefox 2 (by using `"*firefox"` instead of `"*custom"` but don't want to use that for my current project.
|
I'm not sure of the etiquette of answering your own question... but having experimented in a trial-and-error way, here's how I've managed to get Selenium working with PHP/Firefox3 on Ubuntu.
1. I downloaded RC and copied the php client directory to /usr/share/php as 'Selenium'
2. I navigated to the Selenium Server directory in the download, and started selenium with `java -jar selenium-server.jar`
3. I created a new Firefox profile (by running firefox -ProfileManager). I called the new Profile 'Selenium'
4. Within that profile, I editing the Firefox Network preferences to proxy all protocols via localhost port 4444.
5. I created my php script and ran it with this command:
`php -d include_path=".:/usr/share/php:/usr/share/php/Selenium/PEAR" test.php`
I've listed my (basic, non-PHPUnit, non-OO) first test script below for reference.
```
require_once 'Testing/Selenium.php';
$oSelenium = new Testing_Selenium(
"*custom /usr/lib/firefox-3.0.3/firefox -P Selenium",
"https://www.example.com");
$oSelenium->start();
$oSelenium->open("/");
if (!$oSelenium->isElementPresent("id=login_button")) {
$oSelenium->click("logout");
$oSelenium->waitForPageToLoad(10000);
if (!$oSelenium->isElementPresent("id=login_button")) {
echo "Failed to log out\n\n";
exit;
}
}
$oSelenium->type("login", "my_username");
$oSelenium->type("password", "my_password");
$oSelenium->click("login_button");
$oSelenium->waitForPageToLoad(10000);
$oSelenium->click("top_nav_campaigns");
$oSelenium->stop();
```
|
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": "<p>Depending on what you are doing, <a href=\"http://php.net/manual/en/function.system.php\" rel=\"noreferrer\">system()</a> or <a href=\"http://php.net/manual/en/function.popen.php\" rel=\"noreferrer\">popen()</a> may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out <a href=\"http://us.php.net/manual/en/function.proc-open.php\" rel=\"noreferrer\">proc_open()</a>, but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.</p>\n\n<p>If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like \"; evilcommand ;\" and make your program execute arbitrary commands against your will.</p>\n\n<p><a href=\"http://www.php.net/manual/en/function.escapeshellarg.php\" rel=\"noreferrer\">escapeshellarg()</a> and <a href=\"http://www.php.net/manual/en/function.escapeshellcmd.php\" rel=\"noreferrer\">escapeshellcmd()</a> can help with this, but personally I like to remove everything that isn't a known good character, using something like</p>\n\n<pre><code>preg_replace('/[^a-zA-Z0-9]/', '', $str)\n</code></pre>\n"
},
{
"answer_id": 167205,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 3,
"selected": false,
"text": "<p>I do this kind of thing all the time for quick-and-dirty scripts. It's quite common to have a CGI or PHP script that just uses system/popen to call some external program.</p>\n\n<p>Just be extra careful if your web server is open to the internet at large. Be sure to sanitize your GET/POST input in this case so as to not allow attackers to run arbitrary commands on your machine.</p>\n"
},
{
"answer_id": 11601572,
"author": "Idealmind",
"author_id": 1527663,
"author_profile": "https://Stackoverflow.com/users/1527663",
"pm_score": 4,
"selected": false,
"text": "<p>You can run a python script via php, and outputs on browser.</p>\n\n<p>Basically you have to call the python script this way:</p>\n\n<pre><code>$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</code></pre>\n\n<p>Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.</p>\n\n<p>For full codes working, visit <a href=\"http://blog.idealmind.com.br/php/how-to-execute-python-script-from-php-and-show-output-on-browser/\" rel=\"noreferrer\" title=\"How to execute python script from php and show output on browser\">How to execute python script from php and show output on browser</a></p>\n"
},
{
"answer_id": 18921091,
"author": "user",
"author_id": 1892742,
"author_profile": "https://Stackoverflow.com/users/1892742",
"pm_score": 5,
"selected": false,
"text": "<p>The shell_exec() operator will also allow you to run python scripts using similar syntax to above</p>\n<p>In a python file called python.py:</p>\n<pre><code>hello = "hello"\nworld = "world"\nprint hello + " " + world\n</code></pre>\n<p>In a php file called python.php:</p>\n<pre><code>$python = shell_exec(python python.py);\necho $python;\n</code></pre>\n"
},
{
"answer_id": 37870761,
"author": "Gouled Med",
"author_id": 6108635,
"author_profile": "https://Stackoverflow.com/users/6108635",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to execute your Python script in PHP, it's necessary to do this command in your php script:</p>\n\n<pre><code>exec('your script python.py')\n</code></pre>\n"
},
{
"answer_id": 40356103,
"author": "Aze",
"author_id": 7098644,
"author_profile": "https://Stackoverflow.com/users/7098644",
"pm_score": 2,
"selected": false,
"text": "<p>Your call_python_file.php should look like this:</p>\n\n<pre><code><?php\n $item='Everything is awesome!!';\n $tmp = exec(\"py.py $item\");\n echo $tmp;\n?>\n</code></pre>\n\n<p>This executes the python script and outputs the result to the browser.\nWhile in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:</p>\n\n<pre><code>import sys\n\nlist1 = ' '.join(sys.argv[1:])\n\ndef main():\n print list1\n\nif __name__ == '__main__':\n main()\n</code></pre>\n"
},
{
"answer_id": 45592623,
"author": "Bob3411",
"author_id": 7086083,
"author_profile": "https://Stackoverflow.com/users/7086083",
"pm_score": 0,
"selected": false,
"text": "<p>Note that if you are using a virtual environment (as in shared hosting) then you must adjust your path to python, e.g: <code>/home/user/mypython/bin/python ./cgi-bin/test.py</code></p>\n"
},
{
"answer_id": 53071179,
"author": "SMshrimant",
"author_id": 8355510,
"author_profile": "https://Stackoverflow.com/users/8355510",
"pm_score": 1,
"selected": false,
"text": "<p>The above methods seems to be complex. Use my method as a reference.</p>\n\n<p>I have this two files</p>\n\n<blockquote>\n <p>run.php</p>\n \n <p>mkdir.py</p>\n</blockquote>\n\n<p>Here, I've created a html page which contains GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.</p>\n\n<blockquote>\n <p>run.php</p>\n</blockquote>\n\n<pre><code><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</code></pre>\n\n<blockquote>\n <p>mkdir.py</p>\n</blockquote>\n\n<pre><code>#!/usr/bin/env python \nimport os \nos.makedirs(\"thisfolder\");\n</code></pre>\n"
},
{
"answer_id": 65859369,
"author": "Raeen",
"author_id": 15025468,
"author_profile": "https://Stackoverflow.com/users/15025468",
"pm_score": 0,
"selected": false,
"text": "<p>is so easy \nYou can use [phpy - library for php][1]\nphp file</p>\n<pre><code><?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</code></pre>\n<p>python file:</p>\n<pre><code>import include.library.phpy as phpy\nprint(phpy.get_data(number of data , first = 1 , two =2 ...))\n</code></pre>\n<p>you can see also example in github page\n[1]: <a href=\"https://github.com/Raeen123/phpy\" rel=\"nofollow noreferrer\">https://github.com/Raeen123/phpy</a></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/166944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2999/"
] |
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.
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.
Any better ideas? Thanks in advance!
|
Depending on what you are doing, [system()](http://php.net/manual/en/function.system.php) or [popen()](http://php.net/manual/en/function.popen.php) may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out [proc\_open()](http://us.php.net/manual/en/function.proc-open.php), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.
If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.
[escapeshellarg()](http://www.php.net/manual/en/function.escapeshellarg.php) and [escapeshellcmd()](http://www.php.net/manual/en/function.escapeshellcmd.php) can help with this, but personally I like to remove everything that isn't a known good character, using something like
```
preg_replace('/[^a-zA-Z0-9]/', '', $str)
```
|
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": "<pre><code>[1-9ondOND][123][0-9]\n</code></pre>\n\n<p>I omitted the <code>^</code> and <code>$</code> (beginning and end of string markers) because you said you'd have three-character strings, but there's no harm in including them, and they may improve speed, not that that'll be a big deal on such short input.</p>\n\n<p>Of course, this assumes you're working in a language and locale where the uppercase equivalent of <code>o</code>, <code>n</code>, and <code>d</code> are <code>O</code>, <code>N</code>, and <code>D</code>. If not, you'll need to tell your regex interpreter to ignore case. The mechanism varies by language/framework.</p>\n\n<p>For python, you'd use something like:</p>\n\n<pre><code>re.match('[1-9ond][123][0-9]', inputstring, re.IGNORECASE)\n</code></pre>\n\n<p>The <code>re.match</code> forces a match at the beginning of string, so you wouldn't need the <code>^</code> in any case.</p>\n"
},
{
"answer_id": 167010,
"author": "codebunny",
"author_id": 13667,
"author_profile": "https://Stackoverflow.com/users/13667",
"pm_score": 2,
"selected": false,
"text": "<p>Perl RegEx: <code>/^[1-9ondOND][1-3][0-9]$/</code></p>\n\n<p><code>^</code> at the start of the string;<br>\n<code>$</code> at the end of the string.</p>\n"
},
{
"answer_id": 167023,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": -1,
"selected": false,
"text": "<p>In a PREG-based system (most of them these days):</p>\n\n<pre><code>^(?:[1-9]|[ond])[1-3][0-9]$\n</code></pre>\n\n<p>Some systems require the start/end markers (PHP, Perl, but not .NET for instance), if yours does, it'd end up something like:</p>\n\n<pre><code>/^(?:[1-9]|[ond])[1-3][0-9]$/\n</code></pre>\n"
},
{
"answer_id": 167047,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 4,
"selected": true,
"text": "<p>Slight variation on a few other answers. Restrict the input to be exactly the matched text.</p>\n\n<pre>\n<code>\n^[1-9ondOND][123][0-9]$\n</code></pre>\n"
},
{
"answer_id": 167051,
"author": "Greg",
"author_id": 13009,
"author_profile": "https://Stackoverflow.com/users/13009",
"pm_score": 2,
"selected": false,
"text": "<pre><code>[1-9ond][123][0-9]\n</code></pre>\n\n<p><a href=\"http://web.archive.org/web/20151030080919/http://osteele.com:80/tools/rework/\" rel=\"nofollow noreferrer\">Here's a useful place to test your RegEx.</a></p>\n"
},
{
"answer_id": 26636470,
"author": "Suganthan Madhavan Pillai",
"author_id": 2534236,
"author_profile": "https://Stackoverflow.com/users/2534236",
"pm_score": 0,
"selected": false,
"text": "<p>A very late answer, but hope this will help</p>\n\n<pre><code>([1-9]|(?i)(o|n|d))[123][\\d]\n</code></pre>\n\n<p><a href=\"http://regex101.com/r/vE2jT1/1\" rel=\"nofollow\">http://regex101.com/r/vE2jT1/1</a></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] |
I generally stay away from `regular expressions` because I seldom find a good use for them. But in this case, I don't think I have choice.
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 `1-9 or the letters o,n,d (lower or upper)` AND the second character is `1,2 or 3` and the third character is `0-9`.
Can anybody help me out?
|
Slight variation on a few other answers. Restrict the input to be exactly the matched text.
```
^[1-9ondOND][123][0-9]$
```
|
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": "<p>Will this work for you? Put this in MAKEFILE.:</p>\n\n<pre><code>export : *.bmml\n \"C:\\Program Files\\Balsamiq Mockups\\Balsamiq Mockups.exe\" export $** $(**B).png\n</code></pre>\n\n<p>Then run:</p>\n\n<pre><code>nmake /A\n</code></pre>\n\n<p>I don't have Balsamiq so I can't test this but in my case if I have the following MAKEFILE.:</p>\n\n<pre><code>export : *.txt\n copy $** $(**B).dat\n</code></pre>\n\n<p>and run <code>nmake /A</code> in a folder with myFile.txt, it will create myFile.dat.</p>\n"
},
{
"answer_id": 640880,
"author": "Eric Melski",
"author_id": 77345,
"author_profile": "https://Stackoverflow.com/users/77345",
"pm_score": 5,
"selected": true,
"text": "<p>NMAKE pattern rules are a lot like GNU make old-school suffix rules. In your case, you had it almost right to begin with, but you were missing the .SUFFIXES declaration. For example:</p>\n\n<pre><code>.SUFFIXES: .bmml .png\n.bmml.png:\n @echo Building $@ from $<\n</code></pre>\n\n<p>I think this is only part of your solution though, because you also mentioned wanting to avoid explicitly listing all of the files to be converted. Unfortunately, I don't know of a very clean way to do that in NMAKE, since it only expands wildcards in dependency lists, and what you really want in your dependency list is not the list of files that already exist (the *.bmml files), but the list of files that will be created from those files (the *.png files). Nevertheless, I think you can achieve your goal with a recursive NMAKE invocation like this:</p>\n\n<pre><code>all: *.bmml\n $(MAKE) $(**:.bmml=.png)\n</code></pre>\n\n<p>Here, NMAKE will expand <code>*.bmml</code> in the prereq list for <code>all</code> into the list of .bmml files in the directory, and then it will start a new NMAKE instance, specifying the goals to build as that list of files with all instances of <code>.bmml</code> replaced by <code>.png</code>. So, putting it all together:</p>\n\n<pre><code>.SUFFIXES: .bmml .png\nall: *.bmml\n @echo Converting $(**) to .png...\n @$(MAKE) $(**:.bmml=.png)\n\n.bmml.png:\n @echo Building $@ from $<\n</code></pre>\n\n<p>If I create files Test1.bmml and Test2.bmml and then run this makefile, I get the following output:</p>\n\n<pre><code>Converting Test1.bmml Test2.bmml to .png...\nBuilding Test1.png from Test1.bmml\nBuilding Test2.png from Test2.bmml\n</code></pre>\n\n<p>Of course, if you have very many of these .bmml files, you may run afoul of command-line length limitations, so watch out for that. In that case, I recommend either explicitly listing the source files, or using a more capable make tool, like GNU make (which is available for Windows in a variety of forms).</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
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.
[This page](http://www.balsamiq.com/blog/?p=231) details the command line syntax for exporting the files, and [this page](http://msdn.microsoft.com/en-us/library/ms925728.aspx) contains an example which looks like it contains a generic rule for .obj files to .exe files.
The makefile I have tried so far looks like this:
```
.bmml.png:
"C:\Program Files\Balsamiq Mockups\Balsamiq Mockups.exe" export $< $@
```
But this doesn't work.
If I simply run nmake (with some outdated png files), nmake just does this:
```
[C:\Temp] :nmake
Microsoft (R) Program Maintenance Utility Version 9.00.30729.01
Copyright (C) Microsoft Corporation. All rights reserved.
[C:\Temp] :
```
If I ask it to build one specific file, it does this:
```
[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] :
```
Any nmake gurus out there that can set me straight?
An example makefile which simply makes .dat files from .txt files by copying them, to experiment with, looks like this:
```
.txt.dat:
copy $< $@
```
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?
|
NMAKE pattern rules are a lot like GNU make old-school suffix rules. In your case, you had it almost right to begin with, but you were missing the .SUFFIXES declaration. For example:
```
.SUFFIXES: .bmml .png
.bmml.png:
@echo Building $@ from $<
```
I think this is only part of your solution though, because you also mentioned wanting to avoid explicitly listing all of the files to be converted. Unfortunately, I don't know of a very clean way to do that in NMAKE, since it only expands wildcards in dependency lists, and what you really want in your dependency list is not the list of files that already exist (the \*.bmml files), but the list of files that will be created from those files (the \*.png files). Nevertheless, I think you can achieve your goal with a recursive NMAKE invocation like this:
```
all: *.bmml
$(MAKE) $(**:.bmml=.png)
```
Here, NMAKE will expand `*.bmml` in the prereq list for `all` into the list of .bmml files in the directory, and then it will start a new NMAKE instance, specifying the goals to build as that list of files with all instances of `.bmml` replaced by `.png`. So, putting it all together:
```
.SUFFIXES: .bmml .png
all: *.bmml
@echo Converting $(**) to .png...
@$(MAKE) $(**:.bmml=.png)
.bmml.png:
@echo Building $@ from $<
```
If I create files Test1.bmml and Test2.bmml and then run this makefile, I get the following output:
```
Converting Test1.bmml Test2.bmml to .png...
Building Test1.png from Test1.bmml
Building Test2.png from Test2.bmml
```
Of course, if you have very many of these .bmml files, you may run afoul of command-line length limitations, so watch out for that. In that case, I recommend either explicitly listing the source files, or using a more capable make tool, like GNU make (which is available for Windows in a variety of forms).
|
167,018 |
<p>I have been tinkering with BSP trees for a while now and am also playing with threads. When adding a triangle to a BSP tree, an opportunity arises to create a new thread for the purposes of processing data in parallel.</p>
<pre>
insert(triangle, bspnode)
{
....
else if(triangle spans bspnode)
{
(frontpiece, backpiece) = plane_split(triangle, bspnode)
insert(frontpiece, bspnode.front)
insert(backpiece, bspnode.back)
}
....
}
</pre>
<p>The two insert operations above could be executed by two threads, and since they do not modify the same data, cheap synchronization can be used.</p>
<pre>
insert(triangle, bspnode)
{
....
else if(triangle spans bspnode)
{
(frontpiece, backpiece) = split(triangle, bspnode)
handle = beginthread(insert(backpiece, bspnode.front))
insert(frontpiece, bspnode.back)
if(handle)
{
waitforthread(handle)
}
else
{
insert(backpiece, bspnode.front)
}
}
....
}
</pre>
<p>This new method attempts to create a thread to complete the operation in parallel, but should not fail if the thread cannot be created (it will simply revert to the original algorithm).</p>
<p>Is this a sound programming practice, or am I using threads improperly? I have not been able to find any literature on this technique. I like that it tends to use my CPU to its fullest (2 cores), and would theoretically scale to any number of processors available. I don't like that it might be horribly wasteful on CPU and memory.</p>
|
[
{
"answer_id": 167036,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 5,
"selected": true,
"text": "<p>Threads are great if some part of the processing is waiting on something external (user input, I/O, some other processing) - the thread that's waiting can continue to wait, while a thread that isn't waiting forges on ahead.</p>\n\n<p>However, for processing-intensive tasks, more threads than processors actually creates overhead. It seems like your threads are doing all \"CPU work\", so I'd stick to one thread per core - test to find the optimal number, though.</p>\n\n<p>The biggest overhead created is from context switching (freezing one thread and loading the execution context of the next one), as well as cache misses when threads are doing tasks with different memory (if your thread can use the CPU cache effectively).</p>\n"
},
{
"answer_id": 167143,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "<p>your best bet would be to create a threadpool, and then use it 'transparently' to add nodes.</p>\n\n<p>eg, create 2 threads at program start, have them wait on a semaphore or event. When you have nodes to add, you pop the data onto a queue then trigger the semaphore. This wakes one of the threads which pops the data off the queue and performs the processing. (make sure access to the queue is threadsafe - fully synchronised with a critical section is best).</p>\n\n<p>The overall performance of your app is slower as you have more overhead, in copying data to the queue and running the extra threads, but if you used to run on a single core you will now be running on 2. It works best if the threaded processing is expensive.</p>\n"
},
{
"answer_id": 167173,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 0,
"selected": false,
"text": "<p>Sure, for example, Quicksort can be programmed multithreaded quite easily and get some large performance gains on multi-core systems, and some small performance losses on non-multithreaded. Just remember that you're adding overhead twice now - once for the stack save on the recursion and once on the thread, so if you're doing a large number of recursions then it could overwhelm a system faster than a non-multithreaded approach.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] |
I have been tinkering with BSP trees for a while now and am also playing with threads. When adding a triangle to a BSP tree, an opportunity arises to create a new thread for the purposes of processing data in parallel.
```
insert(triangle, bspnode)
{
....
else if(triangle spans bspnode)
{
(frontpiece, backpiece) = plane_split(triangle, bspnode)
insert(frontpiece, bspnode.front)
insert(backpiece, bspnode.back)
}
....
}
```
The two insert operations above could be executed by two threads, and since they do not modify the same data, cheap synchronization can be used.
```
insert(triangle, bspnode)
{
....
else if(triangle spans bspnode)
{
(frontpiece, backpiece) = split(triangle, bspnode)
handle = beginthread(insert(backpiece, bspnode.front))
insert(frontpiece, bspnode.back)
if(handle)
{
waitforthread(handle)
}
else
{
insert(backpiece, bspnode.front)
}
}
....
}
```
This new method attempts to create a thread to complete the operation in parallel, but should not fail if the thread cannot be created (it will simply revert to the original algorithm).
Is this a sound programming practice, or am I using threads improperly? I have not been able to find any literature on this technique. I like that it tends to use my CPU to its fullest (2 cores), and would theoretically scale to any number of processors available. I don't like that it might be horribly wasteful on CPU and memory.
|
Threads are great if some part of the processing is waiting on something external (user input, I/O, some other processing) - the thread that's waiting can continue to wait, while a thread that isn't waiting forges on ahead.
However, for processing-intensive tasks, more threads than processors actually creates overhead. It seems like your threads are doing all "CPU work", so I'd stick to one thread per core - test to find the optimal number, though.
The biggest overhead created is from context switching (freezing one thread and loading the execution context of the next one), as well as cache misses when threads are doing tasks with different memory (if your thread can use the CPU cache effectively).
|
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": "<p>Did you try setting the style:</p>\n\n<pre><code>input {\n text-align:right;\n}\n</code></pre>\n\n<p>Just tested, this works fine (in FF3 at least):</p>\n\n<pre><code><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</code></pre>\n\n<p>You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from \"rightAligned\" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. \"numeric\" might be good, or perhaps the business function of the text boxes.</p>\n"
},
{
"answer_id": 167038,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 4,
"selected": false,
"text": "<p>Using inline styles:</p>\n\n<pre><code><input type=\"text\" style=\"text-align: right\"/>\n</code></pre>\n\n<p>or, put it in a style sheet, like so:</p>\n\n<pre><code><style>\n .rightJustified {\n text-align: right;\n }\n</style>\n</code></pre>\n\n<p>and reference the class:</p>\n\n<pre><code><input type=\"text\" class=\"rightJustified\"/>\n</code></pre>\n"
},
{
"answer_id": 167043,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": false,
"text": "<p>Apply <code>style=\"text-align: right\"</code> to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] |
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.
|
Did you try setting the style:
```
input {
text-align:right;
}
```
Just tested, this works fine (in FF3 at least):
```
<html>
<head>
<title>Blah</title>
<style type="text/css">
input { text-align:right; }
</style>
</head>
<body>
<input type="text" value="2">
</body>
</html>
```
You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.
|
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": "<p>You can do this via the registry. Just save it as a .reg file, and open it on the new VM. I believe this should do it for remapping to Dvorak:</p>\n\n<pre><code>[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</code></pre>\n\n<p>And if you want to go back:</p>\n\n<pre><code>[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</code></pre>\n"
},
{
"answer_id": 11784116,
"author": "Bobulous",
"author_id": 1515834,
"author_profile": "https://Stackoverflow.com/users/1515834",
"pm_score": 5,
"selected": true,
"text": "<p>I may be four years late to the party, but did you ever find this:</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/cc722068%28v=WS.10%29.aspx\" rel=\"noreferrer\">Intlcfg Command-Line Options</a></p>\n\n<p>I don't have Windows Vista (very bad habit, Windows), but looking at this page and also at <a href=\"http://technet.microsoft.com/en-us/library/cc722435%28v=ws.10%29.aspx\" rel=\"noreferrer\">Available Language Packs</a> and <a href=\"http://technet.microsoft.com/en-us/library/cc766503%28v=ws.10%29.aspx\" rel=\"noreferrer\">Default Input Locales</a> I reckon the command you want might well be:</p>\n\n<pre><code>intlcfg.exe -inputlocale:0409:00010409\n</code></pre>\n\n<p>for English (United States) language with United States Dvorak input locale.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23283/"
] |
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.
|
I may be four years late to the party, but did you ever find this:
[Intlcfg Command-Line Options](http://technet.microsoft.com/en-us/library/cc722068%28v=WS.10%29.aspx)
I don't have Windows Vista (very bad habit, Windows), but looking at this page and also at [Available Language Packs](http://technet.microsoft.com/en-us/library/cc722435%28v=ws.10%29.aspx) and [Default Input Locales](http://technet.microsoft.com/en-us/library/cc766503%28v=ws.10%29.aspx) I reckon the command you want might well be:
```
intlcfg.exe -inputlocale:0409:00010409
```
for English (United States) language with United States Dvorak input locale.
|
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": 167244,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not a Ruby programmer, but generally speaking a connection pool is a good idea. You can make that connection pool a singleton and hand out/take back connections. The pool can check after taking back a connection whether everything is still in order. </p>\n\n<p>You should have a distinct life cycle and ownership for each connection so two threads don't use a connection at the same time.</p>\n\n<p>Be careful with temporary tables because they belong to one database session. We've had a bug where in high load situations we encountered weird errors. Finally we remembered that we were using temporary tables in our application. In the high load situation database connections broke down and were automatically regenerated by the connection object without the application code knowing it (we had implemented the reconnect, but forgot that it was a problem in such a situation). The temporary table we wanted to read had disappeared.</p>\n"
},
{
"answer_id": 167265,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 1,
"selected": false,
"text": "<p>Are the databases on the same server?</p>\n\n<p>I have a application where some of the model objects are from one database and others are from a different database. I override the table_name function to specify the database. Won't work if they are different servers but will work for different databases in the same server.</p>\n\n<pre><code>class xx < ActiveRecord.base\n\ndef self.table_name\n \"otherdatabase.table\"\nend\n</code></pre>\n\n<p>It also looks like database pooling may be on the way for an upcomming version of rails.</p>\n\n<p><a href=\"http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools\" rel=\"nofollow noreferrer\">What's New In Edge Rails</a></p>\n"
},
{
"answer_id": 170310,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 0,
"selected": false,
"text": "<p>First regarding the comment left on your initial post : this has <em>nothing</em> to do with ruby. it has everything to do with the design of rails. </p>\n\n<p>with that said, you could probably hijack the ActiveRecord::Base behaviour to keep a hash of connections indexed by a key (in your case the key would be the user name) then intercept establish_connection to check in the pool if the connection is open already</p>\n\n<p>that would require that you reopen ActiveRecord base,which makes your change dependant on AR internals. </p>\n"
},
{
"answer_id": 170708,
"author": "Priit",
"author_id": 22964,
"author_profile": "https://Stackoverflow.com/users/22964",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not going to cover your question on pooling. However, i'm sure that pooling will help to improve things a lot. I also have a installation where each client has it's own database and codebase is shared among them.</p>\n\n<p>Method to parse url is implemented outside Rails in Apache Rewrite configuration because multiple hosts can be mapped to single customer. Also i use customer \"key\" to access cached files on webserver disk. Rewrite configuration looks something like this:</p>\n\n<pre><code>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</code></pre>\n\n<p>And customer key will map directly to database name which will be connected in before_filter method.</p>\n\n<p>So far, switching a database connection on Rails side is not an performance issue. Problems are in MySQL configuration and we're facing problems where there are too many databases and too many requests cause too many open databases in MySQL.</p>\n\n<p>I'm sure you've been considering migrating issues. It wasn't a problem in the beginning with < 2000 database schemas. Now there's > 15K customer databases (and growing) so we're merging them back into small number of sharded databases.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22083/"
] |
I'm trying to understand the best way to get the connection to my databases.
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
```
ActiveRecord::Base.establish_connection(conn_string)
```
where conn\_string contains the name of the database.
This method (set\_db) is called with a
```
before_filter :set_db
```
in my Application controller, so basically for each request I get, the URL is parsed and the application try to do an establish\_connection.
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?
Thanks!
Roberto
|
Are the databases on the same server?
I have a application where some of the model objects are from one database and others are from a different database. I override the table\_name function to specify the database. Won't work if they are different servers but will work for different databases in the same server.
```
class xx < ActiveRecord.base
def self.table_name
"otherdatabase.table"
end
```
It also looks like database pooling may be on the way for an upcomming version of rails.
[What's New In Edge Rails](http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools)
|
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": "<p>Maybe something like</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 167573,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "<p>My first suggestion is to use a subquery to generate the list of item ID's and return items matching those item ID's. But this doesn't include the TagName in your result set. I'll submit a separate answer with another solution.</p>\n\n<pre><code>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</code></pre>\n\n<p>This is a non-correlated subquery, so a good SQL engine should factor it out and run it only once.</p>\n"
},
{
"answer_id": 167600,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "<p>My second solution uses a MySQL function GROUP_CONCAT() to combine all tags matching the item into a comma-separated string in the result set.</p>\n\n<pre><code>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</code></pre>\n\n<p>The GROUP_CONCAT() function is a MySQL feature, it's not part of standard SQL.</p>\n"
},
{
"answer_id": 167653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You could also use Distinct/Group By:</p>\n\n<p><code>\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</code></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22277/"
] |
Given a SCHEMA for implementing tags
ITEM
ItemId, ItemContent
TAG
TagId, TagName
ITEM\_TAG
ItemId, TagId
What is the best way to limit the number of ITEMS to return when selecting with tags?
```
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
```
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.
|
My second solution uses a MySQL function GROUP\_CONCAT() to combine all tags matching the item into a comma-separated string in the result set.
```
SELECT i.ItemContent, GROUP_CONCAT(t.TagName ORDER BY t.TagName) AS TagList
FROM item AS i
INNER JOIN ItemTag AS it ON i.id = it.ItemId
INNER JOIN tag AS t ON t.id = it.TagId
GROUP BY i.ItemId;
```
The GROUP\_CONCAT() function is a MySQL feature, it's not part of standard SQL.
|
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": "<p>I haven't used ASP.NET MVC yet myself, but you could try using <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveclienturl.aspx\" rel=\"nofollow noreferrer\">ResolveClientUrl</a> when writing out the href for your CSS:</p>\n\n<pre><code><link href=\"<%= ResolveClientUrl(\"../../content/Site.css\") %> rel=\"stylesheet\" type=\"text/css\" />\n</code></pre>\n"
},
{
"answer_id": 179678,
"author": "Jared",
"author_id": 24841,
"author_profile": "https://Stackoverflow.com/users/24841",
"pm_score": 1,
"selected": true,
"text": "<p>Thanks Ian Oxley. The problem wasn't solved with the ResolveClientUrl though. </p>\n\n<p>It had to deal with the web.config file. I had code that looked like this:</p>\n\n<pre><code><authorization>\n <deny users=\"?\" />\n <allow users=\"*\" />\n</authorization>\n</code></pre>\n\n<p>I added a location element below the main one and said that anybody could view that content, and it works now. It turns out that files like the CSS file were not viewable until authorized before. That is now fixed. </p>\n\n<p>This is what I added:</p>\n\n<pre><code><location path=\"Content\">\n <system.web>\n <authorization>\n <allow users=\"*\" />\n </authorization>\n </system.web>\n</location>\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24841/"
] |
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.
```
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" name=".ADAuthCookie" timeout="10" />
</authentication>
```
When I visit the page now, the link tag for the CSS looks like this:
```
<link href="../Content/Site.css" rel="stylesheet" type="text/css" />
```
When it *should* look like this:
```
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
```
|
Thanks Ian Oxley. The problem wasn't solved with the ResolveClientUrl though.
It had to deal with the web.config file. I had code that looked like this:
```
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
```
I added a location element below the main one and said that anybody could view that content, and it works now. It turns out that files like the CSS file were not viewable until authorized before. That is now fixed.
This is what I added:
```
<location path="Content">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
```
|
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": "<p>I would never suggest altering a user's resolution unless you're doing something like a full-screen game, you can use</p>\n\n<pre><code> System.Windows.Forms.Screen.PrimaryScreen\n</code></pre>\n\n<p>to give you metrics about that main monitor.</p>\n"
},
{
"answer_id": 167133,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 0,
"selected": false,
"text": "<p>If you're working on a WinForms-based application, in addition to using the Screen metrics described by Bob King, you can also go with layout controls, such as TableLayout and FlowLayout. Layout controls allow you to design your UI to adapt to the screen/window size cleanly. (The WinForms app I'm currently working on does this very well, down to a minimum of 1024x768, up to whatever your heart desires, scaling controls all the way.)</p>\n\n<p>Preemptive comment: Yes, TableLayouts do involve a performance hit. However, my experience has been that users tend to be OK with it when shown the benefits. (New monitor: The app still looks great and works!)</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
What is the the best of detecting and later altering the screen resolution and multiple desktop within .net
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)
|
I would never suggest altering a user's resolution unless you're doing something like a full-screen game, you can use
```
System.Windows.Forms.Screen.PrimaryScreen
```
to give you metrics about that main monitor.
|
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": 167150,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "<p>The compiler may put the data into a different section of the binary depending on whether it's const or not - that's entirely at the discretion of the compiler.</p>\n"
},
{
"answer_id": 167307,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 0,
"selected": false,
"text": "<p>Although there are no guarantees, the const is unlikely to break binary compatibility in the case of an array, so shared libraries should end up with the same layout.</p>\n\n<p>Note this would likely <em>not</em> be the case for a single int:</p>\n\n<pre><code>struct Test\n{\n static int const TEST;\n};\nint const Test::TEST = 7;\n</code></pre>\n\n<p>because TEST is a compile-time constant.</p>\n"
},
{
"answer_id": 167666,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>The compiler (or, actually, the linker) could place the second into a segment marked as read-only, to trigger a hardware exception if you tried to write to it. Since writing to things not intended to be written to is a vector for security attacks, more systems are securing their read-only data.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18721/"
] |
Consider these two C++ header cases:
Case 1:
```
class Test {
public:
static int TEST_DATA[];
};
int Test::TEST_DATA[] = { 1, 2, 3, 4 };
```
Case 2:
```
class Test {
public:
static int const TEST_DATA[];
};
int const Test::TEST_DATA[] = { 1, 2, 3, 4 };
```
Is const in the latter case only for self-imposed compile-time checks or does it affect shared library layout on Mac/Linux/Windows?
*Update:* According to the answers, the compiler *may* put the const stuff on a read-only page. *Does* 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.
|
The compiler may put the data into a different section of the binary depending on whether it's const or not - that's entirely at the discretion of the compiler.
|
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": "<p>Consider <a href=\"http://docs.python.org/library/stdtypes.html#dict.pop\" rel=\"noreferrer\">dict.pop</a>:</p>\n\n<pre><code>for key in exclusion:\n a.pop(key, None)\n</code></pre>\n\n<p>The <code>None</code> keeps pop from raising an exception when <code>key</code> isn't a key.</p>\n"
},
{
"answer_id": 167158,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 2,
"selected": false,
"text": "<p>Why not just use the <code>keys</code> method, instead of <code>iterkeys</code>? That way you can do it in one loop because it returns a list, not an iterator.</p>\n"
},
{
"answer_id": 167167,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 2,
"selected": false,
"text": "<pre><code>a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion)\n</code></pre>\n"
},
{
"answer_id": 167335,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "<p>You could change your exclusion list to a set, then just use intersection to get the overlap.</p>\n\n<pre><code>exclusion = set([3, 4, 5])\n\nfor key in exclusion.intersection(a):\n del a[key]\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] |
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:
```
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]
```
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.
This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.
|
Consider [dict.pop](http://docs.python.org/library/stdtypes.html#dict.pop):
```
for key in exclusion:
a.pop(key, None)
```
The `None` keeps pop from raising an exception when `key` isn't a key.
|
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": "<pre><code>string.Join(\", \", string[] enumerable)\n</code></pre>\n"
},
{
"answer_id": 167142,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var delimitedString = string.Join(\",\", checkboxList.Items.Where(i => i.Selected).Select(i => i.Value).ToArray());\n</code></pre>\n"
},
{
"answer_id": 167175,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Well, in this case the functional approach might not be best suited, simply because there isn't a LINQ \"ForEach\", and you don't want to use string concatenation: you want to use StringBuilder. You could use ToArray (an example just appeared above), but I'd be tempted to simply use:</p>\n\n<pre><code> 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</code></pre>\n\n<p>Not functional programming, but it works... of course, if your source is <em>already</em> a string[] then string.Join is perfect.\n(LINQ is a great tool, but not necessarily always the best tool for every job)</p>\n"
},
{
"answer_id": 167178,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 5,
"selected": true,
"text": "<pre><code>var delimitedString = selectedValues.Aggregate((x,y) => x + \", \" + y);\n</code></pre>\n"
},
{
"answer_id": 167188,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a LINQ/functional way of doing it. </p>\n\n<pre><code>\nstring[] toDelimit = CallSomeFunction();\nreturn toDelimit.Aggregate((x, y) => x + \",\" + y);\n</code></pre>\n"
},
{
"answer_id": 167191,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 2,
"selected": false,
"text": "<p>AviewAnew is the best answer, but if what you are looking for is learning how to think in functional, what you should do is use a fold operation (or aggregate as it is called in NET).</p>\n\n<pre><code>items.Aggregate((accum, elem) => accum + \", \" + elem);\n</code></pre>\n"
},
{
"answer_id": 167299,
"author": "Danko Durbić",
"author_id": 19241,
"author_profile": "https://Stackoverflow.com/users/19241",
"pm_score": 5,
"selected": false,
"text": "<p>Here's an example with a <code>StringBuilder</code>. The nice thing is that <code>Append()</code> returns the <code>StringBuilder</code> instance itself.</p>\n\n<pre><code> return list.Aggregate( new StringBuilder(), \n ( sb, s ) => \n ( sb.Length == 0 ? sb : sb.Append( ',' ) ).Append( s ) );\n</code></pre>\n"
},
{
"answer_id": 13726453,
"author": "UNeverNo",
"author_id": 1051614,
"author_profile": "https://Stackoverflow.com/users/1051614",
"pm_score": 0,
"selected": false,
"text": "<p>This is 3.5 compatible:</p>\n\n<pre><code>var selectedValues = String.Join(\",\", (from ListItem item in checkboxList.Items where item.Selected select item.Value).ToArray());\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10693/"
] |
What is the functional programming approach to convert an `IEnumerable<string>` to a delimited string? I know I can use a loop, but I'm trying to wrap my head around functional programming.
Here's my example:
```
var selectedValues =
from ListItem item in checkboxList.Items
where item.Selected
select item.Value;
var delimitedString = ??
```
.. or could I do this in just the first var assignment (append each result to the previous)?
|
```
var delimitedString = selectedValues.Aggregate((x,y) => x + ", " + y);
```
|
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": 167231,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 2,
"selected": false,
"text": "<p>If this is a web application, you could probably get your webserver to use UTF8 as it's default encoding. That way all data back and forth to the browser would be UTF8 which can be inserted into VARCHAR fields. UTF8 is a nice way to make applications that are not aware of Unicode deal with it.</p>\n"
},
{
"answer_id": 167290,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>N</code> syntax is how you specify a unicode string literal in SQL Server.</p>\n\n<pre><code>N'Unicode string'\n'ANSI string'\n</code></pre>\n\n<p>SQL Server will auto convert between the two when possible, using either a column's collation or the database's collation.</p>\n\n<p>So if your string literals don't actually contain unicode characters, you do not need to specify the <code>N</code> prefix.</p>\n\n<p>But if your string literals <strong>do</strong> contain unicode characters then using the <code>N</code> prefix is necessary.</p>\n"
},
{
"answer_id": 312961,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>While you can simply store UTF8 content in a VARCHAR field in MSSQL Server as long as charset translation is not done you should be aware that:</p>\n\n<ol>\n<li><p>No management/reporting/data tools outside of your application will be able to understand your non-english characters.</p></li>\n<li><p>Language specific handling such as sorting a list of names may not be done in the order acceptable for every language.</p></li>\n<li><p>Must be careful about data truncation. Truncating a multi-byte UTF8 character ususally causes data corruption for the character involved. You should always reject input if it exceeds the field length.</p></li>\n<li><p>It may not be as easy as you think to disable charset translation..Even if you turn it off in your client driver it can still be overriden in some cases if there is a significant locale difference between client and RDBMS codepage used which instantly leads to data corruption.</p></li>\n<li><p>If you think this is all you will have to worry about your fooling yourself.</p></li>\n</ol>\n\n<p>In summary while you might be tempted to go down this path its not a good idea. Code change is required when going multi-byte.</p>\n"
},
{
"answer_id": 1677290,
"author": "Preston",
"author_id": 203024,
"author_profile": "https://Stackoverflow.com/users/203024",
"pm_score": 2,
"selected": false,
"text": "<p>They really need a way to turn off the need for the N'' prefix. The \"it's needed for backwards compatibility\" argument makes zero sense to me - sure, make that behavior the default for old apps, but provide an option for me to turn on Unicode strings by default (i.e, no N'' prefix required.) I'm discovering that I need to go and mess with large areas of my app to adapt to Unicode on SQL Server when this is NOT an issue in Oracle and Postgresql. C'mon, Microsoft!</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6244/"
] |
How can you get MSSQL server to accept Unicode data by default into a VARCHAR or NVARCHAR column?
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.
|
The `N` syntax is how you specify a unicode string literal in SQL Server.
```
N'Unicode string'
'ANSI string'
```
SQL Server will auto convert between the two when possible, using either a column's collation or the database's collation.
So if your string literals don't actually contain unicode characters, you do not need to specify the `N` prefix.
But if your string literals **do** contain unicode characters then using the `N` prefix is necessary.
|
167,154 |
<p>This is a specific version of <a href="https://stackoverflow.com/questions/119540/business-logic-database-or-application-layer">this question</a>.<br/>
I want to check if I am inserting a duplicate row. Should I check it programmatically in my application layer:</p>
<pre><code>if (exists(obj))
{
throw new DuplicateObjectException();
}
HibernateSessionFactory.getSession().save(obj);
</code></pre>
<p>or should I catch the exception thrown by the database layer and triggered when I violate the contraint?</p>
<pre><code>try
{
HibernateSessionFactory.getSession().save(obj);
}
catch(ConstraintViolationException e)
{
throw new DuplicateObjectException();
}
</code></pre>
<p><strong>EDIT:</strong> In other words: though the constraint is there to remain (it's good database design anyway, and I can't be sure my app will be the only one accessing the table) shall I rely on the constraint and handle the exception its violation will raise, or I'd better check anyway?</p>
<p><strong>EDIT2:</strong> Of course I do check+insert within a transaction, locking the table to ensure no other process is writing another record in the meantime</p>
|
[
{
"answer_id": 167176,
"author": "wcm",
"author_id": 2173,
"author_profile": "https://Stackoverflow.com/users/2173",
"pm_score": 1,
"selected": false,
"text": "<p>In general, I try to avoid coding that relies on errors being thrown because I did something wrong. Sometimes, though, that's all you can do. In your situation, I think you should check first.</p>\n"
},
{
"answer_id": 167185,
"author": "JPLemme",
"author_id": 1019,
"author_profile": "https://Stackoverflow.com/users/1019",
"pm_score": 2,
"selected": false,
"text": "<p>You need to catch the database exception unless you can guarantee that your application is the only one that ever inserts rows (and ever will insert rows) into your database. </p>\n\n<p><strong>EDIT:</strong> I may have misunderstand the question, but I would still argue that option B (HibernateSessionFactory throws the ConstraintException from the database) is the better option. There's always a small chance that another application could insert something in the sliver of time between your check and the actual function call. In addition, the only way to check for a dupe is to perform an additional query which is just a needless drain on performance.</p>\n\n<p>My original understanding of the question was that in option A the dupe check would be performed internally (i.e. by using only the data structures that the program had already created, and with no query until the INSERT). My original answer was in response to this method.</p>\n"
},
{
"answer_id": 167218,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": true,
"text": "<p>First, you <strong>must</strong> have a primary key or unique constraint on the database to enforce this uniqueness properly - no question.</p>\n\n<p>Given that the constraint exists, which way should you code in the application? My preference would be to try the insert and catch the exceptions. Because presumably most inserts will succeed, only a few will fails as duplicates (that's what \"exception\" implies!): it is inefficient to perform an exists check before every insert, when the database is going to be performing its own constraint checking anyway.</p>\n\n<p>Also, it is theoretically possible for the exists check to be wrong anyway - if someone else manages to commit a record with the same key value in the small interval between your exists check and your insert. Then, if you don't trap the database exception, you will believe the insert succeeded when in fact it didn't.</p>\n"
},
{
"answer_id": 167275,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 1,
"selected": false,
"text": "<p>This will break (allowing duplicate entries) if the constraint gets dropped for some reason (typically maintenance work where the DBA neglects to re-enable it). You should check for this situation within the application.</p>\n\n<p>However, it is good database design to have the database enforce the constraint (as you have quite rightly pointed out) as others may also be using the database. As a generalisation it is best to assume that applications and databases live in a M:M relationship - this will be the case almost all of the time.</p>\n"
},
{
"answer_id": 167334,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>The exceptions thrown by Hibernate (or any ORM component) tend to be hard to interpret. </p>\n\n<p>If the exception has enough information that you can produce an error message that actually helps the user, then just catch the exception, analyze it, and move on.</p>\n\n<p>If the exception doesn't have enough information, then you have to check for the error condition, and produce a helpful error message to the user that they're doing something wrong.</p>\n\n<p>The question is one of \"how opaque is the exception\"? Some are pretty opaque. Others have enough that you can parse the message string and figure out what to say to the user.</p>\n"
},
{
"answer_id": 167340,
"author": "JMM",
"author_id": 1299,
"author_profile": "https://Stackoverflow.com/users/1299",
"pm_score": 0,
"selected": false,
"text": "<p>Once hibernate throws an exception from the session you <a href=\"http://www.hibernate.org/hib_docs/reference/en/html/transactions-demarcation.html\" rel=\"nofollow noreferrer\">must discard the session</a> (see section 11.2.3). So, if you need to check for dups and continue using the same session then you have no choice but to check first in the application. </p>\n\n<p>Also there is a possibility with the code in the 1st snippet that another process could insert a record that would cause the duplicate exception to be thrown between the time you check for the duplicate record and the time it actually gets inserted.</p>\n"
},
{
"answer_id": 167656,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "<p>You check that the object exists solely in application code, and then once satisfied that it does not, blithely save the object. But another concurrent client might insert their own object in the moment between your two lines of code. So you'd get a Duplicate exception anyway, only this time you don't catch it.</p>\n\n<p>You must do the save() and catch the exception. Otherwise you have a race condition with other concurrent clients working on the same database. </p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
] |
This is a specific version of [this question](https://stackoverflow.com/questions/119540/business-logic-database-or-application-layer).
I want to check if I am inserting a duplicate row. Should I check it programmatically in my application layer:
```
if (exists(obj))
{
throw new DuplicateObjectException();
}
HibernateSessionFactory.getSession().save(obj);
```
or should I catch the exception thrown by the database layer and triggered when I violate the contraint?
```
try
{
HibernateSessionFactory.getSession().save(obj);
}
catch(ConstraintViolationException e)
{
throw new DuplicateObjectException();
}
```
**EDIT:** In other words: though the constraint is there to remain (it's good database design anyway, and I can't be sure my app will be the only one accessing the table) shall I rely on the constraint and handle the exception its violation will raise, or I'd better check anyway?
**EDIT2:** Of course I do check+insert within a transaction, locking the table to ensure no other process is writing another record in the meantime
|
First, you **must** have a primary key or unique constraint on the database to enforce this uniqueness properly - no question.
Given that the constraint exists, which way should you code in the application? My preference would be to try the insert and catch the exceptions. Because presumably most inserts will succeed, only a few will fails as duplicates (that's what "exception" implies!): it is inefficient to perform an exists check before every insert, when the database is going to be performing its own constraint checking anyway.
Also, it is theoretically possible for the exists check to be wrong anyway - if someone else manages to commit a record with the same key value in the small interval between your exists check and your insert. Then, if you don't trap the database exception, you will believe the insert succeeded when in fact it didn't.
|
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": 167166,
"author": "MrValdez",
"author_id": 1599,
"author_profile": "https://Stackoverflow.com/users/1599",
"pm_score": 2,
"selected": false,
"text": "<p>Here's some functions that I found that are dangerous:</p>\n\n<ul>\n<li>gets() - It doesn't check the length of the variable and can overwrite memory if the input is bigger than the variable's buffer.</li>\n<li>scanf() - I'm so glad that Visual Studio told me this function is deprecated. This was an easy fix.</li>\n<li>strcpy() - If the source's memory space is bigger than the destination's, the data after the destination is overwritten.</li>\n</ul>\n"
},
{
"answer_id": 167174,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 2,
"selected": false,
"text": "<p>The following link should give you a comprehensive look at security functions in C++ (ones that are post-fixed with '_s' to fix problems like overflows): <a href=\"http://msdn.microsoft.com/en-us/library/8ef0s5kh(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/8ef0s5kh(VS.80).aspx</a> </p>\n\n<p><strong>EDIT:</strong> This link contains the specific functions that have been replaced: <a href=\"http://msdn.microsoft.com/en-us/library/wd3wzwts(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/wd3wzwts(VS.80).aspx</a></p>\n\n<p><strong>EDIT:</strong> I should mention these are Microsoft methods, but the link is still useful for identifying functions that were deemed a red flag.</p>\n"
},
{
"answer_id": 167181,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately any array can result in a buffer overflow:</p>\n\n<pre><code>uint32_t foo[3];\nfoo[3] = WALKED_OFF_END_OF_ARRAY;\n</code></pre>\n\n<p>In terms of functions, sprintf will happily walk off the end of the buffer. It can be replaced by snprintf.</p>\n"
},
{
"answer_id": 167182,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 4,
"selected": false,
"text": "<p>In general, any function that does not check bounds in the arguments. A list would be</p>\n\n<ul>\n<li>gets()</li>\n<li>scanf()</li>\n<li>strcpy()</li>\n<li>strcat()</li>\n</ul>\n\n<p>You should use size limited versions like stncpy, strncat, fgets, etc. Then be careful while giving the size limit; take into consideration the '\\0' terminating the string.</p>\n\n<p>Also, arrays are NOT bound checked in C or C++. The following example would cause errors. See <a href=\"http://en.wikipedia.org/wiki/Off-by-one_error\" rel=\"noreferrer\">off by one error</a></p>\n\n<pre><code>int foo[3];\nfoo[3] = WALKED_OFF_END_OF_ARRAY;\n</code></pre>\n\n<p><strong>edit</strong>: Copied answers of @MrValdez , @Denton Gentry</p>\n"
},
{
"answer_id": 167189,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>Basically, anything which accept a pointer and writes to it, without checking the length. So thing like strcpy(), sprintf() etc.</p>\n"
},
{
"answer_id": 167197,
"author": "Thomas Jones-Low",
"author_id": 23030,
"author_profile": "https://Stackoverflow.com/users/23030",
"pm_score": 2,
"selected": false,
"text": "<p>Memcpy() is another dangerous one. </p>\n\n<p>Any loop accessing an array is a danger point, because there's no stopping going beyond the end of array. </p>\n\n<p>Memory Leaks are caused by allocating memory, and not freeing it. Constructor and destructors should be another strong review point, the latter to make sure any allocated memory is freeded. </p>\n"
},
{
"answer_id": 167214,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 2,
"selected": false,
"text": "<p>Which version of visual studio are you using? In 2008 with all warnings enabled, all the functions you mention (and more) warn you that they are deprecated.</p>\n\n<p>Perhaps you could check that all warnings are turned on and let the compiler do the hard work for you?</p>\n\n<p>As a side note, the excellent <a href=\"http://www.amazon.co.uk/Writing-Secure-Second-Michael-LeBlanc/dp/0735617228/ref=sr_1_1?ie=UTF8&s=books&qid=1223044585&sr=8-1\" rel=\"nofollow noreferrer\">writing secure code</a> does a great job explaining the different the pitfalls of some of the older functions.</p>\n"
},
{
"answer_id": 167215,
"author": "Mark Kegel",
"author_id": 14788,
"author_profile": "https://Stackoverflow.com/users/14788",
"pm_score": 2,
"selected": false,
"text": "<p>I have somewhat the same problem on the code base I work on. My advice: be wary of any C functions that look like str*() and mem*(). Also be wary of anything that takes a pointer to a buffer, without a length. Since it seems like you have the chance to use C++ I would in the most egregious cases try to use C++ containers for things: vector, string, map, etc. These make your life a lot easier.</p>\n\n<p>Also, automated problem detection tools are wonderful to have. If you can use valgrind I would recommend it. Also Rational Purify is extremely powerful, though not cheap.</p>\n"
},
{
"answer_id": 167329,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>The question is starting at the wrong end, I'm afraid. It's presuming that buffer overruns happen in other functions. The most common cause is operator++, in my experience, or alternatively a lack of operator!=.</p>\n\n<p>The best solution to find a batch of those is /GS in Visual Studio 2005/8. It won't find all of them, but it's a cheap way to reduce the amount of manual work needed.</p>\n"
},
{
"answer_id": 167341,
"author": "dicroce",
"author_id": 3886,
"author_profile": "https://Stackoverflow.com/users/3886",
"pm_score": 3,
"selected": false,
"text": "<p>Valgrind is your new best friend.</p>\n\n<p>valgrind --tool=memcheck --leak-check=full ./a.out</p>\n"
},
{
"answer_id": 963089,
"author": "jdkoftinoff",
"author_id": 32198,
"author_profile": "https://Stackoverflow.com/users/32198",
"pm_score": 1,
"selected": false,
"text": "<p>An additional gotcha in C is the \"strncpy()\" function. Many people do not realize that it is free to return a string that is not null terminated.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
] |
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).
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?
For compiler and/or tools used to help look for buffer overrun, I've [created another question that deals with this](https://stackoverflow.com/questions/167199/what-cc-tools-can-check-for-buffer-overflows)
|
In general, any function that does not check bounds in the arguments. A list would be
* gets()
* scanf()
* strcpy()
* strcat()
You should use size limited versions like stncpy, strncat, fgets, etc. Then be careful while giving the size limit; take into consideration the '\0' terminating the string.
Also, arrays are NOT bound checked in C or C++. The following example would cause errors. See [off by one error](http://en.wikipedia.org/wiki/Off-by-one_error)
```
int foo[3];
foo[3] = WALKED_OFF_END_OF_ARRAY;
```
**edit**: Copied answers of @MrValdez , @Denton Gentry
|
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": 167213,
"author": "Paul Whelan",
"author_id": 3050,
"author_profile": "https://Stackoverflow.com/users/3050",
"pm_score": 2,
"selected": false,
"text": "<p>No you do not need a join table for OneToMany. Look at the @mappedBy annoatation</p>\n"
},
{
"answer_id": 167222,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 0,
"selected": false,
"text": "<p>The quick answer is that if you have a Many-to-Many relationship you will need another table. If you have a One-to-Many or a Many-to-One relationship you will not.</p>\n"
},
{
"answer_id": 218612,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": true,
"text": "<p>You do not need a JoinTable for this. If the class B has no reference to class A then the following will suffice</p>\n\n<pre><code>@Entity class A...{ \n@OneToMany(fetch=FetchType.EAGER) \nCollection getB(){...} }\n</code></pre>\n\n<p>In most cases though you may want a bidirectional relationship in which case B has a reference to A. In that case you will need to look up the @mappedBy annotation. mentioned by Paul.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22763/"
] |
I have 2 tables:
```
A
s_id(key) name cli type
B
sa_id(key) s_id user pwd
```
So in Jpa
I have:
```
@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(){...}
}
```
class b is just a basic entity class with no reference to A.
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?
|
You do not need a JoinTable for this. If the class B has no reference to class A then the following will suffice
```
@Entity class A...{
@OneToMany(fetch=FetchType.EAGER)
Collection getB(){...} }
```
In most cases though you may want a bidirectional relationship in which case B has a reference to A. In that case you will need to look up the @mappedBy annotation. mentioned by Paul.
|
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": 167256,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 3,
"selected": false,
"text": "<p>Google comes up with this <a href=\"http://sourceforge.net/projects/torrentflux/\" rel=\"noreferrer\">PHP client</a> on sourceforge and <a href=\"http://www.phpclasses.org/browse/package/3138.html\" rel=\"noreferrer\">this torrent class</a> on PHP classes. Should be all you need.</p>\n"
},
{
"answer_id": 601710,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 3,
"selected": false,
"text": "<p>Torrent files are basically nested dictionaries encoded with <a href=\"http://en.wikipedia.org/wiki/Bencode\" rel=\"noreferrer\">BEncode</a>. BEncode is a simple encoding and there are a few BDecode PHP classes, like <a href=\"http://www.phpclasses.org/browse/package/3473.html\" rel=\"noreferrer\">this one</a>.</p>\n\n<p>Structure of torrent file is described in <a href=\"http://bittorrent.org/beps/bep_0003.html#metainfo-files-are-bencoded-dictionaries-with-the-following-keys\" rel=\"noreferrer\">BEP0003</a>.</p>\n\n<p>Note that torrent files don't contain \"Seeders\" field that you mention. The list of seeders is dynamic and is managed by tracker server. Having torrent's <code>hash_info</code> and <code>tracker_url</code> (both available from torrent file) you can send scrape-request to the tracker and it will return number of seeders in 'complete' field, see <a href=\"http://wiki.theory.org/BitTorrentSpecification#Tracker_.27scrape.27_Convention\" rel=\"noreferrer\">Tracker Scrape Convention</a>.</p>\n"
},
{
"answer_id": 601765,
"author": "Svish",
"author_id": 39321,
"author_profile": "https://Stackoverflow.com/users/39321",
"pm_score": 4,
"selected": false,
"text": "<p>I have used these functions in a small website I made once. Think I found them with a php bittorrent tracker called OpenTracker or something, but can't find the website...</p>\n\n<p>You wont find the seeders in the torrent file though. The torrent file just contain info about the files, hash codes and lengths etc. And some tracker information I believe. How many seeders and such you will have to get from the tracker. You can read about the protocal at <a href=\"http://BitTorrent.org\" rel=\"noreferrer\">BitTorrent.org</a>. The communication is, I believe, bencoded, so you can use these functions for that as well. Which means you just have to figure out what to send to get what you want back.</p>\n\n<p><strong>NOTE:</strong> I did not write these three functions. Like I said, I found them in the source of an open source torrent tracker. The functions are not commented, but the function names together with a print_r on the result of a torrent file you know the info inshould be enough to understand how to use them. I added some example code at the bottom to show how I used them. And they worked. </p>\n\n<pre><code>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</code></pre>\n\n<hr>\n\n<p>Some example usage:</p>\n\n<pre><code># 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</code></pre>\n"
},
{
"answer_id": 5130111,
"author": "gphilip",
"author_id": 397935,
"author_profile": "https://Stackoverflow.com/users/397935",
"pm_score": -1,
"selected": false,
"text": "<p>This library contains a sublibrary which does the job very well:\n<a href=\"http://www.binpress.com/app/phptracker/177\" rel=\"nofollow\">http://www.binpress.com/app/phptracker/177</a></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
Is there a PHP module that you can use to programmatically read a torrent to find out information about it, Seeders for instance?
|
I have used these functions in a small website I made once. Think I found them with a php bittorrent tracker called OpenTracker or something, but can't find the website...
You wont find the seeders in the torrent file though. The torrent file just contain info about the files, hash codes and lengths etc. And some tracker information I believe. How many seeders and such you will have to get from the tracker. You can read about the protocal at [BitTorrent.org](http://BitTorrent.org). The communication is, I believe, bencoded, so you can use these functions for that as well. Which means you just have to figure out what to send to get what you want back.
**NOTE:** I did not write these three functions. Like I said, I found them in the source of an open source torrent tracker. The functions are not commented, but the function names together with a print\_r on the result of a torrent file you know the info inshould be enough to understand how to use them. I added some example code at the bottom to show how I used them. And they worked.
```
function bdecode($str) {
$pos = 0;
return bdecode_r($str, $pos);
}
function bdecode_r($str, &$pos) {
$strlen = strlen($str);
if (($pos < 0) || ($pos >= $strlen)) {
return null;
}
else if ($str{$pos} == 'i') {
$pos++;
$numlen = strspn($str, '-0123456789', $pos);
$spos = $pos;
$pos += $numlen;
if (($pos >= $strlen) || ($str{$pos} != 'e')) {
return null;
}
else {
$pos++;
return intval(substr($str, $spos, $numlen));
}
}
else if ($str{$pos} == 'd') {
$pos++;
$ret = array();
while ($pos < $strlen) {
if ($str{$pos} == 'e') {
$pos++;
return $ret;
}
else {
$key = bdecode_r($str, $pos);
if ($key == null) {
return null;
}
else {
$val = bdecode_r($str, $pos);
if ($val == null) {
return null;
}
else if (!is_array($key)) {
$ret[$key] = $val;
}
}
}
}
return null;
}
else if ($str{$pos} == 'l') {
$pos++;
$ret = array();
while ($pos < $strlen) {
if ($str{$pos} == 'e') {
$pos++;
return $ret;
}
else {
$val = bdecode_r($str, $pos);
if ($val == null) {
return null;
}
else {
$ret[] = $val;
}
}
}
return null;
}
else {
$numlen = strspn($str, '0123456789', $pos);
$spos = $pos;
$pos += $numlen;
if (($pos >= $strlen) || ($str{$pos} != ':')) {
return null;
}
else {
$vallen = intval(substr($str, $spos, $numlen));
$pos++;
$val = substr($str, $pos, $vallen);
if (strlen($val) != $vallen) {
return null;
}
else {
$pos += $vallen;
return $val;
}
}
}
}
function bencode($var) {
if (is_int($var)) {
return 'i' . $var . 'e';
}
else if (is_array($var)) {
if (count($var) == 0) {
return 'de';
}
else {
$assoc = false;
foreach ($var as $key => $val) {
if (!is_int($key)) {
$assoc = true;
break;
}
}
if ($assoc) {
ksort($var, SORT_REGULAR);
$ret = 'd';
foreach ($var as $key => $val) {
$ret .= bencode($key) . bencode($val);
}
return $ret . 'e';
}
else {
$ret = 'l';
foreach ($var as $val) {
$ret .= bencode($val);
}
return $ret . 'e';
}
}
}
else {
return strlen($var) . ':' . $var;
}
}
```
---
Some example usage:
```
# Read a file
$content = file_get_contents("file.torrent");
$content_d = bdecode($content);
# Check if bdecode succeeded
if(empty($content_d)) exit('Something is wrong with the torrent. BDecode failed.');
# Calculate info_hash
$info_hash = sha1(bencode($content_d['info']), true);
# Calculate length
$length = 0;
function add_length($value, $key)
{
global $length;
if($key == 'length') $length += $value;
}
array_walk_recursive($content_d, 'add_length');
```
|
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": "<p>You'll be in trouble if n == 0... how about this:</p>\n\n<pre><code>var sign = n < 0 ? -1 : 1;\n</code></pre>\n"
},
{
"answer_id": 167258,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 2,
"selected": false,
"text": "<p>You could also do this:</p>\n\n<pre><code>var sign = (n>=0)?1:-1;\n</code></pre>\n\n<p>Using what's known as the <a href=\"http://en.wikipedia.org/wiki/%3F:\" rel=\"nofollow noreferrer\">ternary operator</a>.</p>\n"
},
{
"answer_id": 167270,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 3,
"selected": false,
"text": "<p>That will give you an error if n is zero.</p>\n\n<p>The brute force method:</p>\n\n<pre><code>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</code></pre>\n\n<p>Or, for those with a fondness for the conditional operator:</p>\n\n<pre><code>function sign(num) {\n return (num > 0) ? 1 : ((num < 0) ? -1 : 0);\n}\n</code></pre>\n"
},
{
"answer_id": 591768,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If your number fits in 31 bits then you can use:</p>\n\n<pre><code>var sign = 1 + 2*(n >> 31);\n</code></pre>\n\n<p>Would be interesting to know if this is any faster!</p>\n"
},
{
"answer_id": 591798,
"author": "Chetan S",
"author_id": 31284,
"author_profile": "https://Stackoverflow.com/users/31284",
"pm_score": 0,
"selected": false,
"text": "<p>Snippet from the code I inherited:</p>\n\n<pre><code>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</code></pre>\n\n<p>PS: Please don't use this code. It is a joke</p>\n"
},
{
"answer_id": 12235161,
"author": "Dimmduh",
"author_id": 601040,
"author_profile": "https://Stackoverflow.com/users/601040",
"pm_score": 1,
"selected": false,
"text": "<p>I use this:</p>\n\n<pre><code>return (number < 0 && -1) || 1;\n</code></pre>\n"
},
{
"answer_id": 26769701,
"author": "GiantBX",
"author_id": 4220830,
"author_profile": "https://Stackoverflow.com/users/4220830",
"pm_score": 0,
"selected": false,
"text": "<p>//n = your number\n//nSign = sign of your number</p>\n\n<p>nSign = Math.round(Math.sin(n)*-1);</p>\n\n<p>/*\nMath.sin returns a number between -1 and 1. \nYou must round it to get a non-DEC number. \nThat number will be the opposite of what your number is. Multiply it by -1\n*/</p>\n\n<p>// or you could just do this</p>\n\n<p>Math.round(Math.sin(/<em>n</em>/)*-1)</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
] |
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:
```
var sign = Math.abs(n) / n;
```
But, there is any other way? Better than this?
|
You'll be in trouble if n == 0... how about this:
```
var sign = n < 0 ? -1 : 1;
```
|
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": "<p>There is a good article describing custom actions here:\n<a href=\"http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx\" rel=\"nofollow noreferrer\">ScottGu's Blog</a></p>\n\n<p>The question you asked is answered about halfway through the comments by 'Ryan', unfortunately it's in VB, but it shouldn't be hard to translate:</p>\n\n<pre><code>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</code></pre>\n\n<p>...Where APPPOOL is supplied as an argument in the Custom Action.</p>\n"
},
{
"answer_id": 168385,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a CustomAction to modify IIS during deployment, Here is an article how to do it:\n<a href=\"http://msdn.microsoft.com/en-us/library/aa289522.aspx\" rel=\"nofollow noreferrer\">Modifying Internet Information Services During Deployment with Custom Actions</a></p>\n\n<p>The example in the article is in VB.Net, and does not show explicitly how to change the Application Pool, but it should be easy to figure it out.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7872/"
] |
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?
|
There is a good article describing custom actions here:
[ScottGu's Blog](http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx)
The question you asked is answered about halfway through the comments by 'Ryan', unfortunately it's in VB, but it shouldn't be hard to translate:
```
Private Sub assignApplicationPool(ByVal WebSite As String, ByVal Vdir As String, ByVal appPool As String)
Try
Dim IISVdir As New DirectoryEntry(String.Format("IIS://{0}/W3SVC/1/Root/{1}", WebSite, Vdir))
IISVdir.Properties.Item("AppPoolId").Item(0) = appPool
IISVdir.CommitChanges()
Catch ex As Exception
Throw ex
End Try
End Sub
Private strServer As String = "localhost"
Private strRootSubPath As String = "/W3SVC/1/Root"
Private strSchema As String = "IIsWebVirtualDir"
Public Overrides Sub Install(ByVal stateSaver As IDictionary)
MyBase.Install(stateSaver)
Try
Dim webAppName As String = MyBase.Context.Parameters.Item("TARGETVDIR").ToString
Dim vdirName As String = MyBase.Context.Parameters.Item("COMMONVDIR").ToString
Me.assignApplicationPool(Me.strServer, MyBase.Context.Parameters.Item("TARGETVDIR").ToString, MyBase.Context.Parameters.Item("APPPOOL").ToString)
Catch ex As Exception
Throw ex
End Try
End Sub
```
...Where APPPOOL is supplied as an argument in the Custom Action.
|
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": 167248,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "<p>the manual says:</p>\n<blockquote>\n<p>--backup make backups (see --suffix & --backup-dir)</p>\n<p>--backup-dir=DIR make backups into hierarchy based in DIR</p>\n<p>--suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)</p>\n</blockquote>\n<p>so it seems that you can use one or the other, not both (as I guess you want a way to determine what's a backup you use a suffix or a directory).</p>\n<p>As a way to fix this, why don't you keep the suffix and modify the destination to include the backup directory.</p>\n"
},
{
"answer_id": 10918859,
"author": "Paperghost",
"author_id": 1330572,
"author_profile": "https://Stackoverflow.com/users/1330572",
"pm_score": 1,
"selected": false,
"text": "<p>You could also use something like this </p>\n\n<pre><code># 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</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404/"
] |
```
rsync -auve ssh --backup --suffix='2008-10-03-1514539' --backup-dir='/tmp/' module.pm root@web1:/path/to/module.pm
```
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.
There is nothing in the [manual](http://samba.anu.edu.au/ftp/rsync/rsync.html) 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.
Does anyone have a solution to this?
|
the manual says:
>
> --backup make backups (see --suffix & --backup-dir)
>
>
> --backup-dir=DIR make backups into hierarchy based in DIR
>
>
> --suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)
>
>
>
so it seems that you can use one or the other, not both (as I guess you want a way to determine what's a backup you use a suffix or a directory).
As a way to fix this, why don't you keep the suffix and modify the destination to include the backup directory.
|
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": "<p><code>$0</code> is set to <code>\"-e\"</code> if you're running from <code>-e</code>.</p>\n"
},
{
"answer_id": 167300,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": false,
"text": "<p>Why are you trying to find out if the module was included from the command line? Is there some situation you have where it matters? Are you doing something odd with imports? Tell us what you're trying to do and I can probably come up with a better way to do it :)</p>\n\n<hr>\n\n<p>Okay, you're asking about exporting. What's the problem you're trying to solve? Which way do you want it? Extra or less default exports from the command line? Do you know that you can specify an import list with -M, including an export tag (so, something from %EXPORT_TAGS)? And if you want an empty export list, you can use -m (lowercase m) instead. See the entry for -M/-m in <a href=\"http://perldoc.perl.org/perlrun.html\" rel=\"noreferrer\">perlrun</a>.</p>\n\n<p>You might also be interested in the \"modulino\" trick where a module file can be both a module and a script. You can either use it as a regular module, in which case you have access to all of its methods, or call it as a script, in which case it runs. I describe it in my <a href=\"http://www.ddj.com/184416165\" rel=\"noreferrer\">\"Scripts as Modules\"</a> article for <i>The Perl Journal</i> as well as <a href=\"http://www.perlmonks.org/index.pl?node_id=396759\" rel=\"noreferrer\">\"How a Script Becomes a Module\"</a> on Perlmonks.</p>\n"
},
{
"answer_id": 169726,
"author": "Eric Wilhelm",
"author_id": 11580,
"author_profile": "https://Stackoverflow.com/users/11580",
"pm_score": 1,
"selected": false,
"text": "<p>In your <code>import()</code>, the line number returned by <code>caller()</code> will be <code>0</code> if your module was loaded via <code>-M</code>. This is true <em>whenever</em> -M is used (with -e or not) but I think it is the only case where the line number is <code>0</code>.</p>\n"
},
{
"answer_id": 171482,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 1,
"selected": false,
"text": "<p>If you want different export behavior, the \"clean\" way to do it would be using a different module name. If you really expect to do a lot of one-liner use, you can even give it a short name. E.g. MMN.pm:</p>\n\n<pre><code>package MMN;\nuse My::Module::Name '/./';\nuse Exporter ();\n@ISA = 'Exporter';\n@EXPORT = @My::Module::Name::EXPORT_OK;\n1;\n</code></pre>\n\n<p>Note that Exporter has a little known regex feature; you may just want to do</p>\n\n<pre><code>perl -MMy::Module::Name=/./ -e ...\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11289/"
] |
The question is not how to tell in a oneliner. If you're writing the code in a one-liner, *you know* you are. But how does a module, included by `-MMy::Module::Name` know that it all started from a oneliner.
This is mine. It's non-portable though and relies on UNIX standard commands (although, it can be made portable more or less.)
```
my $process_info = `ps $$ | tail -1`;
my $is_oneliner
= $process_info =~ m/perl.*?\s+-[^\P{IsLower}e]*e[^\P{IsLower}e]*\s+/m
;
```
And if you have a snazzier regex, feel free to improve upon mine.
---
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.
This sounds bad, because there's this credo that exporters should respect other packages--sometimes known as "`@EXPORT` is *EVIL*!" 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 (*gasp!*) if it helps.
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.
|
`$0` is set to `"-e"` if you're running from `-e`.
|
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": "<p>The keyword is <code>final</code> as you thought. See <a href=\"http://dn.codegear.com/article/34324\" rel=\"noreferrer\">http://dn.codegear.com/article/34324</a> and <a href=\"http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311\" rel=\"noreferrer\">http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311</a>. Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 167328,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 3,
"selected": false,
"text": "<p>You're right - it's \"final\". This snippet shows it. (from one of <a href=\"http://www.marcocantu.com\" rel=\"nofollow noreferrer\">Marco Cantu</a>'s books)</p>\n\n<pre><code>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</code></pre>\n\n<p>Compiling gives:</p>\n\n<pre><code>[Pascal Error] Unit1.pas(11): E2352 Cannot override a final method\n</code></pre>\n\n<p>One thing that surprised me: This feature is supported in Win32 Delphi, not just Delphi for .NET</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
] |
How do I stop a function/procedure in a superclass from been overridden in a subclass in Delphi (2007)?
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.
|
The keyword is `final` as you thought. See <http://dn.codegear.com/article/34324> and <http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311>. Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7.
```
type
TSomeClass = class
protected
procedure SomeVirtualMethod; virtual;
end;
TOtherClass = class(TSomeClass)
protected
procedure SomeVirtualMethod; override; final;
end;
```
|
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": 168174,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": -1,
"selected": false,
"text": "<p>Of course it'll be lost, where do you think data goes when it dies? To a data h(e)aven from where it can always return?</p>\n\n<p>I'd like to know what you need the data for, but the ultimate answer is probably that the data belongs into the db, unless it's large binary data such as images, where you should save it in the filesystem.</p>\n"
},
{
"answer_id": 168246,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 4,
"selected": true,
"text": "<p>I assume you are asking whether data that is stored in attributes of ActiveRecord objects stemming from Web requests will be available when accessing them via a Rake task?</p>\n\n<p>No. They won't. That data won't even be available to the next web request. That data won't even be there if you load the same record twice.</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 758984,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>It depends on how you are passing your data to the rake task and why. If your trying to do the work out-of-band with the request, meaning not making the user wait until its complete I recommend taking a look at Ryan's excellent screencast here <a href=\"http://railscasts.com/episodes/128-starling-and-workling\" rel=\"nofollow noreferrer\" title=\"Railscasts - Starling and Workling\">http://railscasts.com/episodes/128-starling-and-workling</a> to learn about job queues.</p>\n\n<p>If its some other exotic reason you must use rake like this you could pass the data as command line parameters. This depends on how much data, and its complexity, you need to pass as it might get out of hand quickly.</p>\n\n<p>Using Daniel's example from above:</p>\n\n<p>thing = Thing.find(:first)\nthing.data = \"Something\"</p>\n\n<p><code>rake myraketask thing_id=#{thing.id} data=#{thing.data}</code></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13710/"
] |
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?
|
I assume you are asking whether data that is stored in attributes of ActiveRecord objects stemming from Web requests will be available when accessing them via a Rake task?
No. They won't. That data won't even be available to the next web request. That data won't even be there if you load the same record twice.
```
class Thing < ActiveRecord::Base
attr_accessor :data
end
#try this in script/console
thing = Thing.find(:first)
thing.data = "Something"
thing = Thing.find(:first)
puts thing.data
-> nil
```
|
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": 167331,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": -1,
"selected": false,
"text": "<p>Group your data on month, and then project it into a new datatable with columns for each month. The new table would be your pivot table.</p>\n"
},
{
"answer_id": 167937,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 9,
"selected": true,
"text": "<p>Something like this?</p>\n\n<pre><code>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</code></pre>\n\n<p><code>GroupBy</code> in Linq does not work the same as SQL. In SQL, you get the key and aggregates (row/column shape). In Linq, you get the key and any elements as children of the key (hierarchical shape). To pivot, you must project the hierarchy back into a row/column form of your choosing.</p>\n"
},
{
"answer_id": 6282689,
"author": "Sanjaya.Tio",
"author_id": 683491,
"author_profile": "https://Stackoverflow.com/users/683491",
"pm_score": 4,
"selected": false,
"text": "<p>I answered <a href=\"https://stackoverflow.com/questions/963491/pivot-data-using-linq\">similar question</a> using linq extension method:</p>\n\n<pre><code>// 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</code></pre>\n\n<p>(+) generic implementation<br>\n(-) definitely slower than Amy B's </p>\n\n<p>Can anyone improve my implementation (i.e. the method does the ordering of columns & rows)?</p>\n"
},
{
"answer_id": 32167435,
"author": "Vitaliy Fedorchenko",
"author_id": 2756471,
"author_profile": "https://Stackoverflow.com/users/2756471",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a bit more generic way how to pivot data using LINQ:</p>\n\n<pre><code>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</code></pre>\n\n<p>where ValueKey is a special class that represents multidimensional key:</p>\n\n<pre><code>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</code></pre>\n\n<p>This approach can be used for grouping by N-dimensions (n>2) and will work fine for rather small datasets. For large datasets (up to 1 mln of records and more) or for cases when pivot configuration cannot be hardcoded I've written special <a href=\"http://www.nrecosite.com/pivot_data_library_net.aspx\" rel=\"nofollow\">PivotData</a> library (it is free):</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 43091570,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 3,
"selected": false,
"text": "<p>The neatest approach for this, I think, is to use a lookup:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 52828775,
"author": "Ali Bayat",
"author_id": 3427324,
"author_profile": "https://Stackoverflow.com/users/3427324",
"pm_score": 0,
"selected": false,
"text": "<p>This is most efficient way:</p>\n\n<p>Check the following approach. Instead of iterating through the customers group each time for each month.</p>\n\n<pre><code>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</code></pre>\n\n<p>Or this one :</p>\n\n<pre><code>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</code></pre>\n\n<p>Complete solution:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 70385919,
"author": "Grant Johnson",
"author_id": 2208461,
"author_profile": "https://Stackoverflow.com/users/2208461",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// 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</code></pre>\n<p><a href=\"https://i.stack.imgur.com/zKrmD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zKrmD.png\" alt=\"enter image description here\" /></a></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2833/"
] |
I am wondering if it is possible to use LINQ to pivot data from the following layout:
```
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
```
into something like this:
```
CustID | Jan- 2008 | Feb- 2008 | Mar - 2008 |
1 | 100 | 350 | 250
2 | 200 | 221 | 2150
```
|
Something like this?
```
List<CustData> myList = GetCustData();
var query = myList
.GroupBy(c => c.CustId)
.Select(g => new {
CustId = g.Key,
Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty),
Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty),
March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty)
});
```
`GroupBy` in Linq does not work the same as SQL. In SQL, you get the key and aggregates (row/column shape). In Linq, you get the key and any elements as children of the key (hierarchical shape). To pivot, you must project the hierarchy back into a row/column form of your choosing.
|
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": "<pre><code>SELECT DATEADD(ms, -2, DATEADD(dd, 1, DATEDIFF(dd, 0, GetDate())))\n</code></pre>\n\n<p>I thought you had c# at first.. I will leave this here in case anyone else stumbles across this.</p>\n\n<pre><code>DateTime now = DateTime.Now;\nDateTime endofDay = now.Date.AddDays(1).AddMilliseconds(-1);\n</code></pre>\n\n<p>You can replace the 'now' variable with whatever day you are trying to figure out</p>\n"
},
{
"answer_id": 167350,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": false,
"text": "<p>The answer is <code>SELECT DATEADD(ms, -3, '2008-01-24')</code>, the explanation is below.</p>\n<p>From <a href=\"http://musingmarc.blogspot.com/2006/07/more-on-dates-and-sql.html\" rel=\"nofollow noreferrer\">Marc's blog</a>:</p>\n<blockquote>\n<p>But wait, Marc... you said you like to use <code>BETWEEN</code>, but that query doesn't have one... that's because <code>BETWEEN</code> <a href=\"http://www.techonthenet.com/sql/between.php\" rel=\"nofollow noreferrer\">is inclusive</a>, meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly <strong>NOT</strong> by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server <code>DATETIME</code> columns have <em>at most</em> a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is:</p>\n</blockquote>\n<pre><code> SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0))\n</code></pre>\n<blockquote>\n</blockquote>\n<p>So to do the orders due this month as a <code>BETWEEN</code> query, you can use this:</p>\n<blockquote>\n</blockquote>\n<pre><code> 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</code></pre>\n<blockquote>\n</blockquote>\n<p>Remember, always make sure that you do math against input parameters, <strong>NOT</strong> columns, or you will kill the <a href=\"http://www.databasejournal.com/features/mssql/article.php/1436301\" rel=\"nofollow noreferrer\">SARG</a>-ability of the query, which means indexes that might have been used aren't.</p>\n"
},
{
"answer_id": 167428,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>Add -1 <em>milliseconds</em> to the <em>start</em> of the <em>next</em> day (DateAdd even supports nanoseconds, if you want to get real fine).</p>\n\n<p>But most likely you just want to use this value in a comparison, and in that case it's even simpler.</p>\n\n<p>Rather than something like this:</p>\n\n<pre><code>AND @CompareDate <= [LastTimeforThatday]\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>@compareDate BETWEEN [StartDate] AND [LastTimeforThatday]\n</code></pre>\n\n<p>Do it like this:</p>\n\n<pre><code>AND @CompareDate < [BeginningOfNextDay]\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>AND (@CompareDate >= [StartDate] AND @CompareDate < [BeginningOfNextDay])\n</code></pre>\n"
},
{
"answer_id": 31524964,
"author": "davef",
"author_id": 5136461,
"author_profile": "https://Stackoverflow.com/users/5136461",
"pm_score": 2,
"selected": false,
"text": "<p>Why back into it?</p>\n\n<pre><code>SELECT DATEADD(ms, 86399997, *yourDate*)\n</code></pre>\n"
},
{
"answer_id": 71165518,
"author": "Phil",
"author_id": 18237793,
"author_profile": "https://Stackoverflow.com/users/18237793",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to use:</p>\n<pre><code>select {fn curdate()} + ' 23:59:59.000'\n</code></pre>\n<p>or</p>\n<pre><code>select DATEADD(ss,-1,DATEADD(DAY,1,CAST({fn curdate()} as DATETIME)))\n</code></pre>\n<p>to get the end of a day</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21004/"
] |
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?
|
The answer is `SELECT DATEADD(ms, -3, '2008-01-24')`, the explanation is below.
From [Marc's blog](http://musingmarc.blogspot.com/2006/07/more-on-dates-and-sql.html):
>
> But wait, Marc... you said you like to use `BETWEEN`, but that query doesn't have one... that's because `BETWEEN` [is inclusive](http://www.techonthenet.com/sql/between.php), meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly **NOT** by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server `DATETIME` columns have *at most* a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is:
>
>
>
```
SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0))
```
>
>
So to do the orders due this month as a `BETWEEN` query, you can use this:
>
>
```
SELECT [ID]
FROM [dbo].[Orders]
WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0)
AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0))
```
>
>
Remember, always make sure that you do math against input parameters, **NOT** columns, or you will kill the [SARG](http://www.databasejournal.com/features/mssql/article.php/1436301)-ability of the query, which means indexes that might have been used aren't.
|
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": "<p>On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open.</p>\n\n<p>Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete.</p>\n\n<p>Example:</p>\n\n<pre><code>public void StartUiThread()\n{\n using (Form1 _form = new Form1())\n {\n Application.Run(_form);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 167384,
"author": "Nenad Dobrilovic",
"author_id": 22062,
"author_profile": "https://Stackoverflow.com/users/22062",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot open a GUI form in any thread, because it will be missing a message pump.\nYou have to explicitly start a message pump in that thread by invoking Application.Run() in a thread method. Another option is to call a DoEvents() in a loop, if you need to do something else, because after Application.Run() that thread will wait a user to close a form in that point of execution.</p>\n"
},
{
"answer_id": 167402,
"author": "CheeZe5",
"author_id": 22431,
"author_profile": "https://Stackoverflow.com/users/22431",
"pm_score": 2,
"selected": false,
"text": "<pre><code>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</code></pre>\n"
},
{
"answer_id": 167429,
"author": "rice",
"author_id": 23933,
"author_profile": "https://Stackoverflow.com/users/23933",
"pm_score": 2,
"selected": false,
"text": "<p>I think your problem is with this thought: \"open a form on a separate thread named 'UI thread'\"</p>\n\n<p>The way windows works is like this (plz note Vista may change some of these realities):</p>\n\n<p>There is one important thread called the \"<strong>Main Thread</strong>\" or the \"<strong>UI Thread</strong>\". This thread is the one that processes <a href=\"http://www.geocities.com/practicalvb/vb/windows/messages.html\" rel=\"nofollow noreferrer\">windows messages</a>, like \"hey the mouse clicked on this pixel.\"</p>\n\n<p>These messages go into a queue, and the main thread processes them <strong>when it isn't busy doing something else</strong>.</p>\n\n<p>So if you make a function call foo() on the main thread, if it takes a long time, no windows messages are processed during that time, and so no user interaction can occur.</p>\n\n<p>The main thread also paints the UI on the screen, so long-running foo() will also stop your app from painting.</p>\n\n<p>All other threads besides this holy and special main thread are grunt worker threads. These worker threads can do things, but they can never interact directly with the user interface.</p>\n\n<p>This reality causes two problems:</p>\n\n<ol>\n<li><p>GETTING OFF THE MAIN THREAD: Since you don't want long-running foo() to halt all user interaction, you need to ship that work off to a worker thread.</p></li>\n<li><p>GETTING BACK TO THE MAIN THREAD: When long-running foo() completes, you probably want to notify the user by doing something in the UI, but you cannot do that in a worker thread, so you need to \"get back\" to the main thread.</p></li>\n</ol>\n\n<p>So I believe your problem in the above program is very general: Your very goal is incorrect, because it is not supposed to be possible to call _form.Show() in any thread but the holy main thread.</p>\n"
},
{
"answer_id": 167445,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>I think just calling ShowDialog instead of Show will help. The problem seems to be that the thread finishes just after calling Show, after that the Form get's garbage collected. ShowDialog will halt the thread but still run form-events on it so the thread will keep running until the form is closed.</p>\n\n<p>Normally i would do it the other way around. Run the form on the starting thread and start background threads when you want to start long-running background tasks.</p>\n\n<p>I also read your other question but couldn't figure out what you're trying to do. MVP-architecture doesn't require you to run your business logic on different threads. Multi threading is hard to do right so I'd only use multiple threads if I really needed them.</p>\n"
},
{
"answer_id": 34018093,
"author": "Oli4",
"author_id": 1799272,
"author_profile": "https://Stackoverflow.com/users/1799272",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of calling show() on the form which will execute on the form and then just close at the end of the thread execution within function StartUiThread(), you can lock the thread until the form is stopped within the method as you are simply locking the other thread. Ex:</p>\n\n<pre><code>public void StartUiThread() {\n _form = new Form1();\n _form.ShowDialog(); //Change Show() to ShowDialog() to wait in thread\n }\n</code></pre>\n\n<p>This will cause the new thread to wait until the dialog is closed. I do not know if this will solve your problems, but it solved mine.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed [here](https://stackoverflow.com/questions/164789/winforms-implementation-question-for-having-my-ui-run-independently-of-my-bll-l).
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.
```
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();
}
}
}
```
|
On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open.
Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete.
Example:
```
public void StartUiThread()
{
using (Form1 _form = new Form1())
{
Application.Run(_form);
}
}
```
|
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": 167359,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>A lot of the times, you are only using the functionality in one place, so making a method just clutters up the class.</p>\n"
},
{
"answer_id": 167360,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 4,
"selected": false,
"text": "<p>It saves having to have methods that are only used once in a specific place from being defined far away from the place they are used. Good uses are as comparators for generic algorithms such as sorting, where you can then define a custom sort function where you are invoking the sort rather than further away forcing you to look elsewhere to see what you are sorting on.</p>\n\n<p>And it's not really an innovation. LISP has had lambda functions for about 30 years or more.</p>\n"
},
{
"answer_id": 167363,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 7,
"selected": false,
"text": "<p>Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method.</p>\n<p>Consider this example:</p>\n<pre><code> List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" };\n string person = people.Find(person => person.Contains("Joe"));\n</code></pre>\n<p>versus</p>\n<pre><code> 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</code></pre>\n<p>These are functionally equivalent.</p>\n"
},
{
"answer_id": 167381,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "<p>It's a way of taking small operation and putting it very close to where it is used (not unlike declaring a variable close to its use point). This is supposed to make your code more readable. By anonymizing the expression, you're also making it a lot harder for someone to break your client code if it the function is used somewhere else and modified to \"enhance\" it.</p>\n\n<p>Similarly, why do you need to use foreach? You can do everything in foreach with a plain for loop or just using IEnumerable directly. Answer: you don't <em>need</em> it but it makes your code more readable.</p>\n"
},
{
"answer_id": 167382,
"author": "Vijesh VP",
"author_id": 22016,
"author_profile": "https://Stackoverflow.com/users/22016",
"pm_score": 3,
"selected": false,
"text": "<p>Lambda expression is a concise way to represent an anonymous method. Both anonymous methods and Lambda expressions allow you define the method implementation inline, however, an anonymous method explicitly requires you to define the parameter types and the return type for a method. Lambda expression uses the type inference feature of C# 3.0 which allows the compiler to infer the type of the variable based on the context. It’s is very convenient because that saves us a lot of typing!</p>\n"
},
{
"answer_id": 167391,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 5,
"selected": false,
"text": "<p>This is just one way of using a lambda expression. You can use a lambda expression <strong>anywhere</strong> you can use a delegate. This allows you to do things like this:</p>\n\n<pre><code>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</code></pre>\n\n<p>This code will search the list for an entry that matches the word \"hello\". The other way to do this is to actually pass a delegate to the Find method, like this:</p>\n\n<pre><code>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</code></pre>\n\n<p><strong>EDIT</strong>:</p>\n\n<p>In C# 2.0, this could be done using the anonymous delegate syntax:</p>\n\n<pre><code> strings.Find(delegate(String s) { return s == \"hello\"; });\n</code></pre>\n\n<p>Lambda's significantly cleaned up that syntax.</p>\n"
},
{
"answer_id": 167392,
"author": "Neil Williams",
"author_id": 9617,
"author_profile": "https://Stackoverflow.com/users/9617",
"pm_score": 9,
"selected": true,
"text": "<p><a href=\"http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx\" rel=\"noreferrer\">Lambda expressions</a> are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL. </p>\n\n<p>The following is an example of a <a href=\"http://msdn.microsoft.com/en-us/library/bb397919.aspx\" rel=\"noreferrer\">LINQ to Objects</a> expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:</p>\n\n<pre><code>// 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</code></pre>\n\n<p>Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement <a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"noreferrer\">closures</a> which can allow you to <a href=\"http://www.srtsolutions.com/Looking-Inside-C-Closures\" rel=\"noreferrer\">pass local state to the function without adding parameters</a> to the function or creating one-time-use objects.</p>\n\n<p><a href=\"http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees\" rel=\"noreferrer\">Expression trees</a> are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an <code>Expression<T></code> parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:</p>\n\n<pre><code>void Example(Predicate<int> aDelegate);\n</code></pre>\n\n<p>called like:</p>\n\n<pre><code>Example(x => x > 5);\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>void Example(Expression<Predicate<int>> expressionTree);\n</code></pre>\n\n<p>The latter will get passed a representation of the <a href=\"http://en.wikipedia.org/wiki/Abstract_syntax_tree\" rel=\"noreferrer\">abstract syntax tree</a> that describes the expression <code>x > 5</code>. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.</p>\n"
},
{
"answer_id": 167425,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "<p>Lambda's cleaned up C# 2.0's anonymous delegate syntax...for example</p>\n\n<pre><code>Strings.Find(s => s == \"hello\");\n</code></pre>\n\n<p>Was done in C# 2.0 like this:</p>\n\n<pre><code>Strings.Find(delegate(String s) { return s == \"hello\"; });\n</code></pre>\n\n<p>Functionally, they do the exact same thing, its just a much more concise syntax.</p>\n"
},
{
"answer_id": 187497,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 5,
"selected": false,
"text": "<p>Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the <strong>expressions</strong> portion of this statement. Microsoft released a entire namespace, <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx\" rel=\"noreferrer\">System.Linq.Expressions</a>, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:</p>\n\n<pre><code>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</code></pre>\n\n<p>This example is trivial. And I am sure you are thinking, \"This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime\". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for <a href=\"http://en.wikipedia.org/wiki/Bayesian_probability\" rel=\"noreferrer\">Bayesian</a> systems, or for <a href=\"http://en.wikipedia.org/wiki/Genetic_programming\" rel=\"noreferrer\">genetic programming</a> (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees. </p>\n"
},
{
"answer_id": 378726,
"author": "agnieszka",
"author_id": 40872,
"author_profile": "https://Stackoverflow.com/users/40872",
"pm_score": 6,
"selected": false,
"text": "<p>I found them useful in a situation when I wanted to declare a handler for some control's event, using another control.\nTo do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.</p>\n\n<pre><code>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</code></pre>\n\n<p>thanks to lambda expressions you can use it like this:</p>\n\n<pre><code>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</code></pre>\n\n<p>Much easier.</p>\n"
},
{
"answer_id": 20704196,
"author": "LCJ",
"author_id": 696627,
"author_profile": "https://Stackoverflow.com/users/696627",
"pm_score": 3,
"selected": false,
"text": "<p>A lambda expression is like an anonymous method written in place of a delegate instance.</p>\n<pre><code>delegate int MyDelagate (int i);\nMyDelagate delSquareFunction = x => x * x;\n</code></pre>\n<p>Consider the lambda expression <code>x => x * x;</code></p>\n<blockquote>\n<p>The input parameter value is x (on the left side of =>)</p>\n<p>The function logic is x * x (on the right side of =>)</p>\n</blockquote>\n<p>A lambda expression's code can be a statement block instead of an expression.</p>\n<pre><code>x => {return x * x;};\n</code></pre>\n<p><strong>Example</strong></p>\n<p>Note: <code>Func</code> is a predefined generic delegate.</p>\n<pre><code> Console.WriteLine(MyMethod(x => "Hi " + x));\n\n public static string MyMethod(Func<string, string> strategy)\n {\n return strategy("Lijo").ToString();\n }\n</code></pre>\n<p><strong>References</strong></p>\n<ol>\n<li><a href=\"https://stackoverflow.com/questions/2012095/c-sharp-how-can-a-delegate-interface-method-interchangable/20703787#20703787\">How can a delegate & interface be used interchangeably?</a></li>\n</ol>\n"
},
{
"answer_id": 20969202,
"author": "Gunasekaran",
"author_id": 1377919,
"author_profile": "https://Stackoverflow.com/users/1377919",
"pm_score": 3,
"selected": false,
"text": "<p>You can also find the use of lambda expressions in writing generic codes to act on your methods.</p>\n\n<p>For example: Generic function to calculate the time taken by a method call. (i.e. <code>Action</code> in here)</p>\n\n<pre><code>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</code></pre>\n\n<p>And you can call the above method using the lambda expression as follows,</p>\n\n<pre><code>var timeTaken = Measure(() => yourMethod(param));\n</code></pre>\n\n<p>Expression allows you to get return value from your method and out param as well</p>\n\n<pre><code>var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));\n</code></pre>\n"
},
{
"answer_id": 39065547,
"author": "battlmonstr",
"author_id": 1009546,
"author_profile": "https://Stackoverflow.com/users/1009546",
"pm_score": 0,
"selected": false,
"text": "<p>The innovation is in the type safety and transparency. Although you don't declare types of lambda expressions, they are inferred, and can be used by code search, static analysis, refactoring tools, and runtime reflection.</p>\n\n<p>For example, before you might have used SQL and could get an SQL injection attack, because a hacker passed a string where a number was normally expected. Now you would use a LINQ lambda expression, which is protected from that.</p>\n\n<p>Building a LINQ API on pure delegates is not possible, because it requires combining expression trees together before evaluating them.</p>\n\n<p>In 2016 most of the popular languages have <a href=\"http://dobegin.com/lambda-functions-everywhere/\" rel=\"nofollow\">lambda expression</a> support, and C# was one of the pioneers in this evolution among the mainstream imperative languages.</p>\n"
},
{
"answer_id": 42893168,
"author": "coffeeeee",
"author_id": 7663109,
"author_profile": "https://Stackoverflow.com/users/7663109",
"pm_score": -1,
"selected": false,
"text": "<p>This is perhaps the best explanations on why to use lambda expressions -> <a href=\"https://youtu.be/j9nj5dTo54Q\" rel=\"nofollow noreferrer\">https://youtu.be/j9nj5dTo54Q</a> </p>\n\n<p>In summary, it's to improve code readability, reduce chances of errors by reusing rather than replicating code, and leverage optimization happening behind the scenes. </p>\n"
},
{
"answer_id": 60353592,
"author": "Grigoris Dimitroulakos",
"author_id": 5415291,
"author_profile": "https://Stackoverflow.com/users/5415291",
"pm_score": 0,
"selected": false,
"text": "<p>The biggest benefit of lambda expressions and anonymous functions is the fact that they allow the client (programmer) of a library/framework to inject functionality by means of code in the given library/framework ( as it is the LINQ, ASP.NET Core and many others ) in a way that the regular methods cannot. However, their strength is not obvious for a single application programmer but to the one that creates libraries that will be later used by others who will want to configure the behaviour of the library code or the one that uses libraries. So the context of effectively using a lambda expression is the usage/creation of a library/framework.</p>\n\n<p>Also since they describe one-time usage code they don't have to be members of a class where that will led to more code complexity. Imagine to have to declare a class with unclear focus every time we wanted to configure the operation of a class object.</p>\n"
},
{
"answer_id": 74125532,
"author": "neena",
"author_id": 20211089,
"author_profile": "https://Stackoverflow.com/users/20211089",
"pm_score": 0,
"selected": false,
"text": "<p>Lambda expression makes tasks much simpler, for example</p>\n<pre><code>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</code></pre>\n<p>In the above code, because we are using lambda, we are getting odd number and sum of even numbers in single line of code.</p>\n<p>Without lambda, we will have to use if/else or for loop.</p>\n<p>So it is good to use lambda to simplify code in C#.</p>\n<p>Some articles on it:</p>\n<p><a href=\"https://qawithexperts.com/article/c-sharp/lambda-expression-in-c-with-examples/470\" rel=\"nofollow noreferrer\">https://qawithexperts.com/article/c-sharp/lambda-expression-in-c-with-examples/470</a></p>\n<p><a href=\"https://exceptionnotfound.net/csharp-in-simple-terms-18-expressions-lambdas-and-delegates\" rel=\"nofollow noreferrer\">https://exceptionnotfound.net/csharp-in-simple-terms-18-expressions-lambdas-and-delegates</a></p>\n<p><a href=\"http://dontcodetired.com/blog/post/Whats-New-in-C-10-Easier-Lambda-Expressions\" rel=\"nofollow noreferrer\">http://dontcodetired.com/blog/post/Whats-New-in-C-10-Easier-Lambda-Expressions</a></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
I have quickly read over the [Microsoft Lambda Expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx) documentation.
This kind of example has helped me to understand better, though:
```
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
```
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?
|
[Lambda expressions](http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx) are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL.
The following is an example of a [LINQ to Objects](http://msdn.microsoft.com/en-us/library/bb397919.aspx) expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:
```
// anonymous delegate
var evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList();
// lambda expression
var evens = Enumerable
.Range(1, 100)
.Where(x => (x % 2) == 0)
.ToList();
```
Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement [closures](http://en.wikipedia.org/wiki/Closure_(computer_science)) which can allow you to [pass local state to the function without adding parameters](http://www.srtsolutions.com/Looking-Inside-C-Closures) to the function or creating one-time-use objects.
[Expression trees](http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees) are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an `Expression<T>` parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:
```
void Example(Predicate<int> aDelegate);
```
called like:
```
Example(x => x > 5);
```
becomes:
```
void Example(Expression<Predicate<int>> expressionTree);
```
The latter will get passed a representation of the [abstract syntax tree](http://en.wikipedia.org/wiki/Abstract_syntax_tree) that describes the expression `x > 5`. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.
|
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": "<pre><code>svn log -v -rX:Y .\n</code></pre>\n\n<p>The -v for \"verbose\" switch will give you detailed output on which files were affected on that revision.</p>\n\n<p>Note that \".\" assumes you are currently in a working copy directory, but you can also use a URL such as \"<a href=\"http://svn.myawesomesoftwareproject.com/trunk/lib/foo.c\" rel=\"noreferrer\">http://svn.myawesomesoftwareproject.com/trunk/lib/foo.c</a>\".</p>\n\n<p>This information can be found by typing \"svn help log\", or by reading the <a href=\"http://svnbook.red-bean.com/\" rel=\"noreferrer\">SVN Book</a>, available free online. Don't forget to <strong>R</strong>ead <strong>T</strong>he <strong>F</strong>riendly <strong>M</strong>anual!</p>\n"
},
{
"answer_id": 167380,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": false,
"text": "<p>Right click the directory containing your repo. Choose SVN Show Log. Control+Click the two revisions. Right click on one and choose Compare Revisions.</p>\n"
},
{
"answer_id": 167383,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-diff.html#tsvn-dug-compare-revs\" rel=\"nofollow noreferrer\">Like this</a>.</p>\n"
},
{
"answer_id": 167404,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 1,
"selected": false,
"text": "<p>If you are new to source control and SVN you may want to pick up <a href=\"http://www.pragprog.com/titles/svn/pragmatic-version-control-using-subversion\" rel=\"nofollow noreferrer\">Pragmatic Version Control</a> with SVN. It explains many of the concepts and commands.</p>\n"
},
{
"answer_id": 529760,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>svn diff -r \"start_revision_number\":\"end_revision_number\" \"url_of_svn_repo\" --summarize</p>\n\n<p>then just pipe it to grep ^A D or M</p>\n"
},
{
"answer_id": 5736542,
"author": "Elias Zamaria",
"author_id": 28324,
"author_profile": "https://Stackoverflow.com/users/28324",
"pm_score": 5,
"selected": false,
"text": "<p>If you want a concise list of files without the times and commit messages, you can do it like this:</p>\n\n<pre><code>svn diff -r X:Y --summarize\n</code></pre>\n"
},
{
"answer_id": 41143303,
"author": "Dipendra Gurung",
"author_id": 4828076,
"author_profile": "https://Stackoverflow.com/users/4828076",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me on windows</p>\n\n<ol>\n<li>Go to your folder where you have the repository,</li>\n<li>right click and select SVN Show log,</li>\n<li>In the dialog box there is a \"Show Range\" button, click it and fill <em>Start Revision</em> = {your revision} and <em>End Revision</em> = {your revision}</li>\n<li>Select the Start and Date range as per your need</li>\n</ol>\n\n<p>Note: {your revision}=provide the revision number for atleast one of your file changes. All files associated with that revision should get listed.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
I just want to see what files were modded/added/deleted between 2 arbitrary revisions. How do I do this?
Can I do this in tortoise as well?
|
```
svn log -v -rX:Y .
```
The -v for "verbose" switch will give you detailed output on which files were affected on that revision.
Note that "." assumes you are currently in a working copy directory, but you can also use a URL such as "<http://svn.myawesomesoftwareproject.com/trunk/lib/foo.c>".
This information can be found by typing "svn help log", or by reading the [SVN Book](http://svnbook.red-bean.com/), available free online. Don't forget to **R**ead **T**he **F**riendly **M**anual!
|
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": 167997,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": 0,
"selected": false,
"text": "<p>I would recommend using a JS/Ajax library on the client-side just to eliminate the possibility of cross-browser issues with your code. For the same reason I would recommend using a python http server library like <a href=\"http://docs.python.org/library/simplehttpserver.html\" rel=\"nofollow noreferrer\">SimpleHTTPServer</a> or something from <a href=\"http://twistedmatrix.com/trac/wiki/Documentation\" rel=\"nofollow noreferrer\">Twisted</a> if the former does not allow low-level control.</p>\n\n<p>Another idea - use something like Wireshark to check what's been sent by the browsers.</p>\n"
},
{
"answer_id": 170005,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": false,
"text": "<p>The problem you have is that</p>\n\n<ul>\n<li>your tcp socket handling isn't reading as much as it should</li>\n<li>your http handling is not complete</li>\n</ul>\n\n<p>I recommend the following lectures:</p>\n\n<ul>\n<li><a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616.html\" rel=\"nofollow noreferrer\">rfc2616</a></li>\n<li><a href=\"http://www.kohala.com/start/unpv12e.html\" rel=\"nofollow noreferrer\">The sockets Networking API</a> by Stevens</li>\n</ul>\n\n<p>See the example below for a working http server that can process posts</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 170354,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you very much Florian, your code is working!!!!<br/>\nI reuse the template and complete the <strong>main</strong> with my COMET mecanism and it is working much better<br/>\nChrome and Firefox are working perfectly well<br/>\nIE has still a problem with the \"long GET\" system<br/>\nWhen it received the answer to the GET it does not stop to re executing the loop to print the messages.<br/>\nInvestigating right now the question<br/></p>\n\n<p>Here is my updated code for very basic JQuery+Python cross browser system.<br/></p>\n\n<p>The Python program, based on Florian's code:<br/></p>\n\n<pre><code>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</code></pre>\n\n<p>And the HTML with Jquery compacted:</p>\n\n<pre><code> <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</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I wrote small Python+Ajax programs (listed at the end) with socket module to study the COMET concept of asynchronous communications.
The idea is to allow browsers to send messages real time each others via my python program.
The trick is to let the "GET messages/..." connection opened waiting for a message to answer back.
My problem is mainly on the reliability of what I have via socket.recv...
When I POST from Firefox, it is working well.
When I POST from Chrome or IE, the "data" I get in Python is empty.
Does anybody know about this problem between browsers?
Are some browsers injecting some EOF or else characters killing the receiving of "recv"?
Is there any solution known to this problem?
The server.py in Python:
```
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'
```
The client.html in HTML+Javascript:
```
<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>
```
|
The problem you have is that
* your tcp socket handling isn't reading as much as it should
* your http handling is not complete
I recommend the following lectures:
* [rfc2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
* [The sockets Networking API](http://www.kohala.com/start/unpv12e.html) by Stevens
See the example below for a working http server that can process posts
```
index = '''
<html>
<head>
</head>
<body>
<form action="/" method="POST">
<textarea name="foo"></textarea>
<button type="submit">post</button>
</form>
<h3>data posted</h3>
<div>
%s
</div>
</body>
</html>
'''
bufsize = 4048
import socket
import re
from urlparse import urlparse
class Headers(object):
def __init__(self, headers):
self.__dict__.update(headers)
def __getitem__(self, name):
return getattr(self, name)
def get(self, name, default=None):
return getattr(self, name, default)
class Request(object):
header_re = re.compile(r'([a-zA-Z-]+):? ([^\r]+)', re.M)
def __init__(self, sock):
header_off = -1
data = ''
while header_off == -1:
data += sock.recv(bufsize)
header_off = data.find('\r\n\r\n')
header_string = data[:header_off]
self.content = data[header_off+4:]
lines = self.header_re.findall(header_string)
self.method, path = lines.pop(0)
path, protocol = path.split(' ')
self.headers = Headers(
(name.lower().replace('-', '_'), value)
for name, value in lines
)
if self.method in ['POST', 'PUT']:
content_length = int(self.headers.get('content_length', 0))
while len(self.content) < content_length:
self.content += sock.recv(bufsize)
self.query = urlparse(path)[4]
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(
socket.SOL_SOCKET,
socket.SO_REUSEADDR,
1,
)
acceptor.bind(('', 2501 ))
acceptor.listen(10)
if __name__ == '__main__':
while True:
sock, info = acceptor.accept()
request = Request(sock)
sock.send('HTTP/1.1 200 OK\n\n' + (index % request.content) )
sock.close()
```
|
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": "<p><pre><code><code>Set RegEx = New RegExp\nRegEx.Global = True\nRegEx.Pattern = \"([IJKCXY]\\d+)([^\\.]|$)\"\nnewVar = RegEx.Replace (oldString, \"$1.$2\")\n</code></pre></code></p>\n\n<p>Where oldString is the original string, and newVar is the string with the decimals added.</p>\n"
},
{
"answer_id": 167651,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 0,
"selected": false,
"text": "<pre><code>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</code></pre>\n"
},
{
"answer_id": 167953,
"author": "user24912",
"author_id": 24912,
"author_profile": "https://Stackoverflow.com/users/24912",
"pm_score": 0,
"selected": false,
"text": "<p>tloach still answer doesn't work</p>\n\n<p>Waynes works but also puts a . after every occurrence of IJKCXY</p>\n\n<p>I changed if instr(Match.value, \".\") = 0 then</p>\n\n<p>To be like if instr(Match.value, \".\") = 0 and len(Match.value) > 1 then</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Example
G76 I0.4779 J270 K7 C90
X20 Y30
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:
G76 I0.4779 J270 K7. C90.
X20. Y30.
Purpose of this code is to convert CNC code for an older Fanuc OPC controller
|
```
`Set RegEx = New RegExp
RegEx.Global = True
RegEx.Pattern = "([IJKCXY]\d+)([^\.]|$)"
newVar = RegEx.Replace (oldString, "$1.$2")`
```
Where oldString is the original string, and newVar is the string with the decimals added.
|
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": 167465,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 0,
"selected": false,
"text": "<p>Must be your setup, I can use the £ (Also european keyboard) under IDLE or the python command line just fine. (python 2.5).</p>\n\n<p>edit: I'm using windows, so mayby its a problem with the how python works under the mac OS?</p>\n"
},
{
"answer_id": 167466,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 2,
"selected": false,
"text": "<p>In unicode it is 00A003. With the Unicode escape it would be u'\\u00a003'. </p>\n\n<p>Edit:\n@ Patrick McElhaney said you might need to use 00A3.</p>\n"
},
{
"answer_id": 167472,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 2,
"selected": true,
"text": "<p>I'd imagine that the terminal emulator is eating the keystroke as a control code. Maybe see if it has a config file you can mess around with?</p>\n"
},
{
"answer_id": 167515,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 3,
"selected": false,
"text": "<p>Not the best solution, but you could type:</p>\n\n<pre><code> pound = u'\\u00A3'\n</code></pre>\n\n<p>Then you have it in a variable you can use in the rest of your session.</p>\n"
},
{
"answer_id": 167998,
"author": "indentation",
"author_id": 7706,
"author_profile": "https://Stackoverflow.com/users/7706",
"pm_score": 2,
"selected": false,
"text": "<p><code>u'\\N{pound sign}'</code></p>\n\n<p>If you are using ipython, put</p>\n\n<p><code>execute pound = u'\\N{pound sign}'</code></p>\n\n<p>in your ipythonrc file (in \"Section: Python code to execute\") this way you will always have \"pound\" defined as the pound symbol in the interactive shell.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578/"
] |
**Update:** Thanks for the suggestions guys. After further research, I’ve reformulated the question here: [Python/editline on OS X: £ sign seems to be bound to ed-prev-word](https://stackoverflow.com/questions/217020/pythoneditline-on-os-x-163-sign-seems-to-be-bound-to-ed-prev-word)
On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell.
* Mac OS X 10.5.5
* Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)
* European keyboard (£ is shift-3)
When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears.
If I’ve already typed some characters, e.g.
```
>>> 1234567890 1234567890 1234567890
```
... 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.
In a normal bash shell, pressing shift-3 types a “£” as expected.
Any idea how I can type a literal “£” in the Python interactive shell?
|
I'd imagine that the terminal emulator is eating the keystroke as a control code. Maybe see if it has a config file you can mess around with?
|
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": "<p>Templates, Includes.</p>\n\n<p>Xsl is very different from any other programming language. <code>Its rule based.</code></p>\n\n<p>I recommend you to read <a href=\"http://www.topxml.com/xsl/tutorials/intro/default.asp\" rel=\"nofollow noreferrer\">something</a> about Xslt and then ask a bit more spedific.</p>\n"
},
{
"answer_id": 167499,
"author": "mspmsp",
"author_id": 21724,
"author_profile": "https://Stackoverflow.com/users/21724",
"pm_score": 2,
"selected": false,
"text": "<p>There are both xsl Include and Import statements that you can use to abstract away portions of the page. XSLT itself is very much the kind of thing that can reproduce tag file type behavior. You edit your xml data files with the tags you want. Meanwhile, your xsl templates are going to know what do to with those tags then they encounter them.</p>\n"
},
{
"answer_id": 167534,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 2,
"selected": false,
"text": "<p>You can give templates names and then call them via 'call-template'</p>\n\n<p>In XSLT 2.0 you can create your own functions (although I find the syntax tortuous)</p>\n\n<p>A wonderful area to explore is using XSLT to generate XSLT stylesheets. This lets you automate common conversion scenarios where 90% of the stylesheet is boilerplate. In order to do this you need to become familiar with 'namespace-alias'. Its a great way to expand your knowlege of the language.</p>\n"
},
{
"answer_id": 167545,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 5,
"selected": true,
"text": "<p>For my own project, this is how I divided up my pages. There was a template.xsl file which was imported\nby each of my XSLs. Most pages just had template.xsl, but some pages such as cart, etc. needed their own\nbecause of the different kind of data they were parsing. </p>\n\n<pre><code><page title=\"Home\">\n <navigation>\n <!-- something here -->\n </navigation>\n <main>\n <!-- something here -->\n </main>\n</page>\n</code></pre>\n\n<p>This is a snippet from my template.xsl. I threw in all the common stuff in here, and then gave the opportunity\nfor my pages to add their own information through <code>call-template</code>.</p>\n\n<pre><code><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</code></pre>\n\n<p>An example of how my css tag would respond. Note that it calls <code>css-extended.</code> css only\nhad the the common css' that would apply across all pages. Some pages needed more. Those\ncould override css-extended. Note that is needed because <code>call-template</code> will fail if a \npage calls a template but doesn't define it anywhere.</p>\n\n<pre><code> <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</code></pre>\n\n<p>My container would work in a similar manner-- common stuff was defined and then each page\ncould just provide an implementation. A default implementation was in the XSL. (in <code>content</code>)</p>\n\n<pre><code> <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</code></pre>\n\n<p>It worked quite beautifully for me. If there are any questions I can answer for you, let me know.</p>\n"
},
{
"answer_id": 167706,
"author": "glenatron",
"author_id": 15394,
"author_profile": "https://Stackoverflow.com/users/15394",
"pm_score": 1,
"selected": false,
"text": "<p>XSLT is powerful, but it is very different from most programming languages and it is quite limited in what it makes available to you, so things that you have built-in with another language may need some quite complex xsl manipulation to work with. I found <a href=\"http://www.mulberrytech.com/quickref/\" rel=\"nofollow noreferrer\">the cheatsheet from here</a> useful when I was going through a lot of XSLT work a couple of weeks back.</p>\n\n<p>Don't expect that XSLT will do things in a particular way and you probably can find good ways of doing those things, but if you have too much of a set idea about how something should work it's easy to get stuck.</p>\n"
},
{
"answer_id": 171923,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>XSL is <strong>based</strong> on templating. </p>\n\n<p>XML data can be \"re-used\" at three-levels. At the most basic level you can <code><xsl:for-each /></code> through XML.</p>\n\n<p>Note: For-each in XSL is not looping through the data, it's just matching the data. Also when your \"inside\" a for-each your inside that \"context\" of the XML (which is like the concept of \"scope\" in programming)</p>\n\n<p>An example of using and re-using a for-each</p>\n\n<pre><code><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</code></pre>\n\n<p>The for-each nodes are contained within template nodes (2nd level of reuse). There are two types of template nodes: Match and Named. <strong>Match template</strong> nodes, act like the for-each node mentioned above, but are automatically called by the template engine if any nodes are matched when XSL processing starts. Match template nodes can also be explicitly applied. On the other hand <strong>Named template</strong> nodes are always explicitly applied and can be thought of as like functions.</p>\n\n<p>Example of a Match template which will <em>Always</em> be called (because a root node will always exist)</p>\n\n<pre><code><xsl:template match=\"/\">\n ... do some stuff ...\n</xsl:template>\n</code></pre>\n\n<p>A Match template calling another match template explicitly</p>\n\n<pre><code><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</code></pre>\n\n<p>Note: In order for the Match template to work, the XML Node it is matching needs to exist. If it doesn't there is no match, so that template is <strong>not</strong> called. </p>\n\n<p>Example of a Named template</p>\n\n<pre><code><xsl:template name=\"WriteOut\">\n ... data with NO Context Here ...\n</xsl:template>\n</code></pre>\n\n<p>Or calling a Named template from a Matched template</p>\n\n<pre><code><xsl:template match=\"/\">\n <xsl:call-template name=\"WriteOut\" />\n<xsl:template>\n</code></pre>\n\n<p>Note: You can mix and match where you call matched and named templates from, you just have to watch what context you are in. </p>\n\n<p>All of template nodes are held in <strong>XSL Stylesheets</strong>, and you can <strong>include</strong> and <strong>import</strong> various stylesheets. For example you can hold all of the templates dealing with HTML header nodes in one template and all of the templates dealing with the HTML body nodes in another. Then you can create one stylesheet that includes both Header and Body stylesheets.</p>\n\n<p>Example of an include node</p>\n\n<pre><code><xsl:include href=\"header.xsl\" />\n</code></pre>\n\n<p>In conclusion there are three ways to abstracting chunks of data, through for-eaching, through templating or through including stylesheets.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13663/"
] |
I'm exploring the XML -> XSLT -> HTML meme for producing web content. I have very little XSLT experience.
I'm curious what mechanisms are available in XSLT to handle abstractions or "refactoring".
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.
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).
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.
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?
|
For my own project, this is how I divided up my pages. There was a template.xsl file which was imported
by each of my XSLs. Most pages just had template.xsl, but some pages such as cart, etc. needed their own
because of the different kind of data they were parsing.
```
<page title="Home">
<navigation>
<!-- something here -->
</navigation>
<main>
<!-- something here -->
</main>
</page>
```
This is a snippet from my template.xsl. I threw in all the common stuff in here, and then gave the opportunity
for my pages to add their own information through `call-template`.
```
<xsl:template match="/page" name="page">
<html>
<head>
<title><xsl:value-of select="(@title)" /></title>
<xsl:call-template name="css" />
<xsl:call-template name="script" />
</head>
<body>
<xsl:call-template name="container" />
</body>
</html>
</xsl:template>
```
An example of how my css tag would respond. Note that it calls `css-extended.` css only
had the the common css' that would apply across all pages. Some pages needed more. Those
could override css-extended. Note that is needed because `call-template` will fail if a
page calls a template but doesn't define it anywhere.
```
<xsl:template name="css">
<link rel="stylesheet" type="text/css" href="{$cssPath}reset.css" />
<link rel="stylesheet" type="text/css" href="{$cssPath}style.css" />
<link rel="stylesheet" type="text/css" href="{$cssPath}layout.css" />
<xsl:call-template name="css-extended" />
</xsl:template>
<!-- This is meant to be blank. It gets overriden by implementing stylesheets -->
<xsl:template name="css-extended" />
```
My container would work in a similar manner-- common stuff was defined and then each page
could just provide an implementation. A default implementation was in the XSL. (in `content`)
```
<xsl:template name="container">
<div id="container">
<xsl:call-template name="header" />
<xsl:call-template name="content" />
<xsl:call-template name="footer" />
</div>
</xsl:template>
<xsl:template name="content">
<div id="content">
<div id="content-inner">
<xsl:call-template name="sideBar" />
<xsl:call-template name="main" />
</div>
</div>
</xsl:template>
<xsl:template name="main">
<div id="main">
<xsl:apply-templates select="main" />
<xsl:call-template name="main-extended" />
</div>
</xsl:template>
<!-- This is meant to be blank. It gets overriden by implementing stylesheets -->
<xsl:template name="main-extended" />
<xsl:template name="footer">
<div id="footer">
<div id="footer-inner">
<!-- Footer content here -->
</div>
</div>
</xsl:template>
```
It worked quite beautifully for me. If there are any questions I can answer for you, let me know.
|
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": 171038,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 3,
"selected": false,
"text": "<p>Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.</p>\n\n<p>Instead, use the <a href=\"http://jtds.sourceforge.net/\" rel=\"noreferrer\">jtds jdbc driver</a>. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.</p>\n"
},
{
"answer_id": 356456,
"author": "Jerome Delattre",
"author_id": 27762,
"author_profile": "https://Stackoverflow.com/users/27762",
"pm_score": 7,
"selected": true,
"text": "<p>I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)</p>\n\n<p>But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver.\nJust build your JDBC URL like this:</p>\n\n<pre><code>jdbc:sqlserver://localhost;integratedSecurity=true;\n</code></pre>\n\n<p>And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms378428.aspx\" rel=\"noreferrer\">MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL</a></p>\n"
},
{
"answer_id": 801113,
"author": "opensas",
"author_id": 47633,
"author_profile": "https://Stackoverflow.com/users/47633",
"pm_score": 5,
"selected": false,
"text": "<p>look at</p>\n\n<p><a href=\"http://jtds.sourceforge.net/faq.html#driverImplementation\" rel=\"noreferrer\">http://jtds.sourceforge.net/faq.html#driverImplementation</a></p>\n\n<p>What is the URL format used by jTDS?</p>\n\n<p>The URL format for jTDS is:</p>\n\n<pre><code>jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]\n</code></pre>\n\n<p>...\ndomain\nSpecifies the Windows domain to authenticate in. If present and the user name and password are provided, jTDS uses Windows (NTLM) authentication instead of the usual SQL Server authentication (i.e. the user and password provided are the domain user and password). This allows non-Windows clients to log in to servers which are only configured to accept Windows authentication.</p>\n\n<p>If the domain parameter is present but no user name and password are provided, jTDS uses its native Single-Sign-On library and logs in with the logged Windows user's credentials (for this to work one would obviously need to be on Windows, logged into a domain, and also have the SSO library installed -- consult README.SSO in the distribution on how to do this).</p>\n"
},
{
"answer_id": 1918854,
"author": "nathan",
"author_id": 233439,
"author_profile": "https://Stackoverflow.com/users/233439",
"pm_score": 2,
"selected": false,
"text": "<p>I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did:</p>\n\n<ol>\n<li>Install the JTDS driver</li>\n<li>Do not use the \"domain= \" property in the jdbc:jtds:://[:][/][;=[;...]] string</li>\n<li>Install the ntlmauth.dll in c:\\windows\\system32 directory (registration of the dll was not required) on the web server machine.</li>\n<li>Change the logon identity for the Apache Tomcat service to a domain User with access to the SQL database server (it was not necessary for the user to have access to the dbo.master).</li>\n</ol>\n\n<p>My environment:\nWindows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003</p>\n"
},
{
"answer_id": 8836885,
"author": "Andy",
"author_id": 1145683,
"author_profile": "https://Stackoverflow.com/users/1145683",
"pm_score": 3,
"selected": false,
"text": "<p>This actually works for me:</p>\n\n<p>Per the README.SSO that comes with the jtdsd distribution:</p>\n\n<p>In order for Single Sign On to work, jTDS must be able to load the native SPPI library <code>ntlmauth.dll</code>. Place this DLL anywhere in the system path (defined by the <code>PATH</code> system variable) and you're all set.</p>\n\n<p>I placed it in my jre/bin folder</p>\n\n<p>I configured a port dedicated the sql server instance (2302) to alleviate the need for an instance name - just something I do. lportal is my database name.</p>\n\n<pre><code>jdbc.default.url=jdbc:jtds:sqlserver://192.168.0.147:2302/lportal;useNTLMv2=true;domain=mydomain.local\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318/"
] |
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:
```
dbDriver = com.microsoft.sqlserver.jdbc.SQLServerDriver
dbUser = user
dbPass = password
dbServer = localhost:1433;databaseName=testDb
dbUrl = jdbc:sqlserver://localhost:1433
```
I have zero problems with connecting to a SQL Server database in this fashion when using SQL Server authentication.
Is there any way I can retrieve the credentials of the user's Windows Authentication and use **that** authentication for SQL Server?
**UPDATE**: 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.
|
I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)
But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver.
Just build your JDBC URL like this:
```
jdbc:sqlserver://localhost;integratedSecurity=true;
```
And copy the appropriate DLL to Tomcat's bin directory (sqljdbc\_auth.dll provided with the driver)
[MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL](http://msdn.microsoft.com/en-us/library/ms378428.aspx)
|
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": "<p>I would hide the MERGE inside a PL/SQL API and then call that via JDBC:</p>\n\n<pre><code>data_pkg.merge_data ('someid', 'testKey', 'someValue');\n</code></pre>\n\n<p>As an alternative to MERGE, the API could do:</p>\n\n<pre><code>begin\n insert into data (...) values (...);\nexception\n when dup_val_on_index then\n update data\n set ...\n where ...;\nend;\n</code></pre>\n"
},
{
"answer_id": 167754,
"author": "Craig",
"author_id": 55922,
"author_profile": "https://Stackoverflow.com/users/55922",
"pm_score": 6,
"selected": true,
"text": "<p>I don't consider using dual to be a hack. To get rid of binding/typing twice, I would do something like:</p>\n\n<pre><code>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</code></pre>\n"
},
{
"answer_id": 168573,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer to try the update before the insert to save having to check for an exception.</p>\n\n<pre><code>update data set ...=... where ...=...;\n\nif sql%notfound then\n\n insert into data (...) values (...);\n\nend if;\n</code></pre>\n\n<p>Even now we have the merge statement, I still tend to do single-row updates this way - just seems more a more natural syntax. Of course, <strong>merge</strong> really comes into its own when dealing with larger data sets.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309/"
] |
In Oracle, given a simple data table:
```
create table data (
id VARCHAR2(255),
key VARCHAR2(255),
value VARCHAR2(511));
```
suppose I want to "insert or update" a value. I have something like:
```
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');
```
Is there a better way than this? This command seems to have the following drawbacks:
* Every literal needs to be typed twice (or added twice via parameter setting)
* The "using dual" syntax seems hacky
If this is the best way, is there any way around having to set each parameter twice in JDBC?
|
I don't consider using dual to be a hack. To get rid of binding/typing twice, I would do something like:
```
merge into data
using (
select
'someid' id,
'testKey' key,
'someValue' value
from
dual
) val on (
data.id=val.id
and data.key=val.key
)
when matched then
update set data.value = val.value
when not matched then
insert (id, key, value) values (val.id, val.key, val.value);
```
|
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": "<p>In ActiveRecord, your types map to a record in a table (by default). It seems like you are confusing how this type should map to your table.</p>\n\n<p>The MyClass type should have a definition something like this (excluding the PK settings):</p>\n\n<pre><code>[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</code></pre>\n\n<p>Then, to load the list:</p>\n\n<pre><code>public void LoadMyClasses()\n{\n MyClass[] results = MyClass.FindAll();\n}\n</code></pre>\n\n<p>I'd suggest you spend some time with the <a href=\"http://www.castleproject.org/activerecord/documentation/index.html\" rel=\"nofollow noreferrer\">ActiveRecord documentation</a> (or <a href=\"http://www.castleproject.org/activerecord/gettingstarted/index.html\" rel=\"nofollow noreferrer\">tutorial</a>) as that should also help clear up any confusion.</p>\n"
},
{
"answer_id": 176807,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, you can do this. You can map a one-to-many relation to a built-in or simple type (value type or string) rather than a persisted type. </p>\n\n<p>You'll need to specify the <code>ColumnKey</code>, <code>Table</code> and <code>Element</code> params in the <code>HasMany</code> attribute declaration to get it to wire up properly. You have to have a surrogate key column so the AR can handle updates and cascades, and then <code>Element</code> tells AR which column in the table holds the simple value it will use to make the list. </p>\n\n<pre><code>[HasMany(typeof(string), Table=\"ToDoList_Items\", \n ColumnKey = \"ListItemID\", Element = \"Item\")]\npublic IList<string> Items { get; set; }\n</code></pre>\n\n<p>(or something similar - I haven't got a compiler handy on this box to check it; but per the API docs it ought to work.)</p>\n\n<p>Speaking of which, if you haven't already had a look, <a href=\"http://api.castleproject.org\" rel=\"nofollow noreferrer\">http://api.castleproject.org</a> is kinda indispensible for any work with the Castle stack.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4642/"
] |
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.
```
[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; }
}
}
```
Can anyone help?
|
Yes, you can do this. You can map a one-to-many relation to a built-in or simple type (value type or string) rather than a persisted type.
You'll need to specify the `ColumnKey`, `Table` and `Element` params in the `HasMany` attribute declaration to get it to wire up properly. You have to have a surrogate key column so the AR can handle updates and cascades, and then `Element` tells AR which column in the table holds the simple value it will use to make the list.
```
[HasMany(typeof(string), Table="ToDoList_Items",
ColumnKey = "ListItemID", Element = "Item")]
public IList<string> Items { get; set; }
```
(or something similar - I haven't got a compiler handy on this box to check it; but per the API docs it ought to work.)
Speaking of which, if you haven't already had a look, <http://api.castleproject.org> is kinda indispensible for any work with the Castle stack.
|
167,487 |
<p>If I spawn a new thread, and then within it I push a new controller onto my UINavigationController, using code like this...</p>
<p>(a) not working</p>
<pre><code>-(void)myCallbackInThread
{
// move on...
UIApplication* app = [UIApplication sharedApplication];
[app changeView];
}
</code></pre>
<p>then I find that the view appears, but does not respond to user input.</p>
<p>If I change the code like this</p>
<p>(b) working</p>
<pre><code>-(void)myCallbackInThread
{
// move on...
UIApplication* app = [UIApplication sharedApplication];
[app performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];
}
</code></pre>
<p>Then everything works just fine.</p>
<p>Any hints as to why?</p>
|
[
{
"answer_id": 167493,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 2,
"selected": false,
"text": "<p>Just found this in the iPhone threading docs</p>\n\n<blockquote>\n <p>If your application has a graphical\n user interface, it is recommended that\n you receive user-related events and\n initiate interface updates from your\n application’s main thread. This\n approach helps avoid synchronization\n issues associated with handling user\n events and drawing window content.\n Some frameworks, such as Cocoa,\n generally require this behavior, but\n it also has the advantage of\n simplifying the logic for managing\n your user interface.</p>\n</blockquote>\n\n<p>I still don't see what would actually cause something to display but not be able to receive user input, but I'll follow that guideline in future.</p>\n"
},
{
"answer_id": 167644,
"author": "Evan DiBiase",
"author_id": 2399475,
"author_profile": "https://Stackoverflow.com/users/2399475",
"pm_score": 2,
"selected": false,
"text": "<p>As the documentation says, \"If you’re not sure about a particular graphical operation, plan on doing it from your main thread.\"</p>\n\n<p>A good rule of thumb to follow is that, if a class isn't explicitly documented as being thread-safe, then it's probably not. Additionally, code that's not documented as being thread-safe may not fail fast when used by multiple threads, but may simply exhibit undefined behavior, as you saw.</p>\n"
},
{
"answer_id": 274098,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 3,
"selected": true,
"text": "<p>In your case, it really depends on what's happening in [app changeView], but the reason it stops responding is most likely that you have no run loop dispatching events on your new, secondary thread (more on this below). In general, however, it is a very bad idea to update the GUI from a secondary thread. As you've already discovered, all of these events should go through the main thread.</p>\n\n<p>The main reason that your second example works and not your first is that UIApplication sets up and handles the run loop and event dispatcher for you on the main thread. So, when you call performSelectorInMainThread, the selector gets dispatched to the main run loop which is able to then handle your gui input and other events. The event dispatcher is also run and managed by UIApplication on the main thread.</p>\n\n<p>So basically, don't perform any GUI management activities on a secondary thread. Dispatch those to the main thread. And if you need processing on a secondary thread (for things like timers or asynch calls, etc.) then you have to start and manage your own run loop on that thread (see <a href=\"http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html\" rel=\"nofollow noreferrer\">NSRunLoop</a> for more on managing your on run loop).</p>\n"
},
{
"answer_id": 274147,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 0,
"selected": false,
"text": "<p>Almost none of the UI code in UIKit or AppKit is threadsafe. How it fails is irrelevent, because if you are worrying about how it fails you are doing something that is going to result in all sorts of weird bugs that will subtly change between different OS release anyway.</p>\n\n<p>My best advice is to not use things from background threads unless the docs say it is safe.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18017/"
] |
If I spawn a new thread, and then within it I push a new controller onto my UINavigationController, using code like this...
(a) not working
```
-(void)myCallbackInThread
{
// move on...
UIApplication* app = [UIApplication sharedApplication];
[app changeView];
}
```
then I find that the view appears, but does not respond to user input.
If I change the code like this
(b) working
```
-(void)myCallbackInThread
{
// move on...
UIApplication* app = [UIApplication sharedApplication];
[app performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];
}
```
Then everything works just fine.
Any hints as to why?
|
In your case, it really depends on what's happening in [app changeView], but the reason it stops responding is most likely that you have no run loop dispatching events on your new, secondary thread (more on this below). In general, however, it is a very bad idea to update the GUI from a secondary thread. As you've already discovered, all of these events should go through the main thread.
The main reason that your second example works and not your first is that UIApplication sets up and handles the run loop and event dispatcher for you on the main thread. So, when you call performSelectorInMainThread, the selector gets dispatched to the main run loop which is able to then handle your gui input and other events. The event dispatcher is also run and managed by UIApplication on the main thread.
So basically, don't perform any GUI management activities on a secondary thread. Dispatch those to the main thread. And if you need processing on a secondary thread (for things like timers or asynch calls, etc.) then you have to start and manage your own run loop on that thread (see [NSRunLoop](http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html) for more on managing your on run loop).
|
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": "<pre><code>DECLARE @MyDate datetime\n\n-- ... set your datetime's initial value ...'\n\nDATEADD(d, 1, @MyDate)\n</code></pre>\n"
},
{
"answer_id": 167507,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 2,
"selected": false,
"text": "<pre><code>DECLARE @date DateTime\nSET @date = GetDate()\nSET @date = DateAdd(day, 1, @date)\n\nSELECT @date\n</code></pre>\n"
},
{
"answer_id": 167539,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 7,
"selected": false,
"text": "<p>Use the following function:</p>\n<pre><code>DATEADD(type, value, date)\n</code></pre>\n<ul>\n<li><p><strong>date</strong> is the date you want to manipulate</p>\n</li>\n<li><p><strong>value</strong> is the integere value you want to add (or subtract if you provide a negative number)</p>\n</li>\n<li><p><strong>type</strong> is one of:</p>\n</li>\n<li><p>yy, yyyy: year</p>\n</li>\n<li><p>qq, q: quarter</p>\n</li>\n<li><p>mm, m: month</p>\n</li>\n<li><p>dy, y: day of year</p>\n</li>\n<li><p>dd, d: day</p>\n</li>\n<li><p>wk, ww: week</p>\n</li>\n<li><p>dw, w: weekday</p>\n</li>\n<li><p>hh: hour</p>\n</li>\n<li><p>mi, n: minute</p>\n</li>\n<li><p>ss or s: second</p>\n</li>\n<li><p>ms: millisecond</p>\n</li>\n<li><p>mcs: microsecond</p>\n</li>\n<li><p>ns: nanosecond</p>\n</li>\n</ul>\n<pre><code>SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day\n</code></pre>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms186819.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms186819.aspx</a></p>\n"
},
{
"answer_id": 2204720,
"author": "Lakshmanan From INDIA",
"author_id": 266740,
"author_profile": "https://Stackoverflow.com/users/266740",
"pm_score": 2,
"selected": false,
"text": "<pre><code>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</code></pre>\n"
},
{
"answer_id": 19590482,
"author": "Dilip Kr Singh",
"author_id": 1501276,
"author_profile": "https://Stackoverflow.com/users/1501276",
"pm_score": 3,
"selected": false,
"text": "<p>The following query I have used in SQL Server 2008, it may be help you.</p>\n<p>For add day</p>\n<pre><code>DATEADD(DAY,20,GETDATE())\n</code></pre>\n<p>*20 is the day quantity</p>\n"
},
{
"answer_id": 22148005,
"author": "BJ Patel",
"author_id": 2683759,
"author_profile": "https://Stackoverflow.com/users/2683759",
"pm_score": 4,
"selected": false,
"text": "<p>Try following code will Add one day to current date</p>\n\n<pre><code>select DateAdd(day, 1, GetDate())\n</code></pre>\n\n<p>And in the same way can use Year, Month, Hour, Second etc. instead of day in the same function </p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21004/"
] |
How do I in SQL Server 2005 use the DateAdd function to add a day to a date
|
Use the following function:
```
DATEADD(type, value, date)
```
* **date** is the date you want to manipulate
* **value** is the integere value you want to add (or subtract if you provide a negative number)
* **type** is one of:
* yy, yyyy: year
* qq, q: quarter
* mm, m: month
* dy, y: day of year
* dd, d: day
* wk, ww: week
* dw, w: weekday
* hh: hour
* mi, n: minute
* ss or s: second
* ms: millisecond
* mcs: microsecond
* ns: nanosecond
```
SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day
```
<http://msdn.microsoft.com/en-us/library/ms186819.aspx>
|
167,502 |
<p>This is the page that I'm having. But the resize part in the section does not seem to be working. I copied most of the code from the <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/UpdatePanelAnimation/UpdatePanelAnimation.aspx" rel="nofollow noreferrer">Ajax site</a>. I placed a alert() in the tag (line 108) to find the value of 'b._originalHeight' and it shows up as '44'. I have also tried the code in the above-said tutorial (line 132) and that did not work either. (I'm not sure where it is getting this value from. But I need it to show all the controls on the form.</p>
<pre><code><%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddEditContest.ascx.cs" Inherits="TMPInternational.Spawn2DotComAdmin.Contest.UserControls.AddEditContest" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="uc" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<%@ Register TagPrefix="ew" Assembly="eWorld.UI, Version=1.9.0.0, Culture=neutral, PublicKeyToken=24d65337282035f2" Namespace="eWorld.UI" %>
<h1 style="margin-left:8px">Add/Edit Contest</h1>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<div style="text-align:left;width:500px; margin-left:8px">
<div id="PanelContainer">
<asp:UpdatePanel ID="AddEditContestUpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<div id="background" style="text-align:left; height: 44px;">
<asp:Panel ID="ContestList" runat="server">
<asp:datagrid AllowSorting="false" id="ContestGrid" GridLines="None" CellPadding="5"
Width="100%" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#cccccc"
HeaderStyle-Font-Size="15px" HeaderStyle-Font-Bold="true" HeaderStyle-BackColor="#888f9b"
Runat="server" AllowPaging="True" PageSize="10"
PagerStyle-NextPageText="Next >>" PagerStyle-PrevPageText="<< Back" >
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="ContestID" DataNavigateUrlFormatString="../?Load=AddEditContest&Type=Edit&ContestID={0}"
DataTextField="Title" ItemStyle-width="30%" headertext="Contest Title" />
<asp:BoundColumn DataField="StartDate" ItemStyle-Width="35%" HeaderText="Start Date" />
<asp:BoundColumn DataField="EndDate" ItemStyle-Width="35%" HeaderText="End Date" />
</Columns>
</asp:datagrid>
<div style="text-align:right;">
<asp:ImageButton ID="AddContest" runat="server"
ImageUrl="~/Contest/Images/Add.png" AlternateText="Add Contest"
onclick="AddContest_Click" />
</div>
</asp:Panel>
<asp:Panel ID="FieldsPanel" runat="server">
<p /><b>Title</b>
<br />
<asp:TextBox Runat="server" id="TitleText" />
<asp:RequiredFieldValidator id="TitleValidator" runat="server" ForeColor="Red"
ErrorMessage="Please add a title" ControlToValidate="TitleText">*</asp:RequiredFieldValidator>
<p /><b>Contest Description</b>
<br />
Use HTML tags to format this area. Start paragraphs with
&lt;p /&gt; tag, bold items with &lt;b&gt;&lt;/b&gt; tags. Create a
line-break between lines with one &lt;br /&gt; tag.<br />
<asp:TextBox Runat="server" ID="DescriptionText" TextMode="MultiLine" Width="400" Height="200" />
<asp:RequiredFieldValidator id="DescriptionValidator" runat="server" ErrorMessage="Please add a description"
ControlToValidate="DescriptionText" ForeColor="Red">*</asp:RequiredFieldValidator>
<p />
<b>Contest Start Date</b>
<br />
<ew:CalendarPopup id="StartDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif"
CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select"
CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False">
<WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" />
<MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" />
<OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" />
<GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/>
<TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" />
<DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" />
<WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" />
<SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/>
<HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" />
</ew:CalendarPopup>
&nbsp;
<ew:TimePicker id="StartTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time"
ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px">
<TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" />
<SelectedTimeStyle ForeColor="Blue" BackColor="Gray" />
</ew:TimePicker>
<p/><b>Contest End Date</b>
<br />
<ew:CalendarPopup id="EndDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif"
CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select"
CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False">
<WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" />
<MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" />
<OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" />
<GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/>
<TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" />
<DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" />
<WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" />
<SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/>
<HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" />
</ew:CalendarPopup>
&nbsp;
<ew:TimePicker id="EndTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time"
ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px">
<TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" />
<SelectedTimeStyle ForeColor="Blue" BackColor="Gray" />
</ew:TimePicker>
<p />
<asp:ImageButton ID="SaveContestButton" runat="server" AlternateText="Confirm"
ImageUrl="~/Contest/Images/Confirm.png" onclick="SaveContestButton_Click" />
</asp:Panel>
<br />
<asp:Label ID="MessageLabel" runat="server" />
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="SaveContestButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
<uc:UpdatePanelAnimationExtender ID="upae" BehaviorID="animation" runat="server" TargetControlID="AddEditContestUpdatePanel">
<Animations>
<OnUpdating>
<Sequence>
<%-- Store the original height of the panel --%>
<ScriptAction Script="var b = $find('animation'); b._originalHeight = b._element.offsetHeight;" />
<%-- Disable all the controls --%>
<Parallel duration="0">
<EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="false" />
</Parallel>
<StyleAction Attribute="overflow" Value="hidden" />
<%-- Do each of the selected effects --%>
<Parallel duration=".25" Fps="30">
<FadeOut AnimationTarget="PanelContainer" minimumOpacity=".2" />
<Resize Height="0px" />
</Parallel>
</Sequence>
</OnUpdating>
<OnUpdated>
<Sequence>
<%-- Do each of the selected effects --%>
<Parallel duration=".25" Fps="30">
<FadeIn AnimationTarget="PanelContainer" minimumOpacity=".2" />
<Length duration="2" fps="40" Property="style" PropertyKey="height"
StartValue="10" EndValueScript="$get('animation').offsetHeight"
AnimationTarget="animation" />
<%--Also tried the below
<Resize HeightScript="$find('animation')._originalHeight" />
--%>
</Parallel>
<%-- Enable all the controls --%>
<Parallel duration="0">
<EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="true" />
</Parallel>
</Sequence>
</OnUpdated>
</Animations>
</uc:UpdatePanelAnimationExtender>
</div>
</code></pre>
|
[
{
"answer_id": 167501,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<pre><code>DECLARE @MyDate datetime\n\n-- ... set your datetime's initial value ...'\n\nDATEADD(d, 1, @MyDate)\n</code></pre>\n"
},
{
"answer_id": 167507,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 2,
"selected": false,
"text": "<pre><code>DECLARE @date DateTime\nSET @date = GetDate()\nSET @date = DateAdd(day, 1, @date)\n\nSELECT @date\n</code></pre>\n"
},
{
"answer_id": 167539,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 7,
"selected": false,
"text": "<p>Use the following function:</p>\n<pre><code>DATEADD(type, value, date)\n</code></pre>\n<ul>\n<li><p><strong>date</strong> is the date you want to manipulate</p>\n</li>\n<li><p><strong>value</strong> is the integere value you want to add (or subtract if you provide a negative number)</p>\n</li>\n<li><p><strong>type</strong> is one of:</p>\n</li>\n<li><p>yy, yyyy: year</p>\n</li>\n<li><p>qq, q: quarter</p>\n</li>\n<li><p>mm, m: month</p>\n</li>\n<li><p>dy, y: day of year</p>\n</li>\n<li><p>dd, d: day</p>\n</li>\n<li><p>wk, ww: week</p>\n</li>\n<li><p>dw, w: weekday</p>\n</li>\n<li><p>hh: hour</p>\n</li>\n<li><p>mi, n: minute</p>\n</li>\n<li><p>ss or s: second</p>\n</li>\n<li><p>ms: millisecond</p>\n</li>\n<li><p>mcs: microsecond</p>\n</li>\n<li><p>ns: nanosecond</p>\n</li>\n</ul>\n<pre><code>SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day\n</code></pre>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms186819.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms186819.aspx</a></p>\n"
},
{
"answer_id": 2204720,
"author": "Lakshmanan From INDIA",
"author_id": 266740,
"author_profile": "https://Stackoverflow.com/users/266740",
"pm_score": 2,
"selected": false,
"text": "<pre><code>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</code></pre>\n"
},
{
"answer_id": 19590482,
"author": "Dilip Kr Singh",
"author_id": 1501276,
"author_profile": "https://Stackoverflow.com/users/1501276",
"pm_score": 3,
"selected": false,
"text": "<p>The following query I have used in SQL Server 2008, it may be help you.</p>\n<p>For add day</p>\n<pre><code>DATEADD(DAY,20,GETDATE())\n</code></pre>\n<p>*20 is the day quantity</p>\n"
},
{
"answer_id": 22148005,
"author": "BJ Patel",
"author_id": 2683759,
"author_profile": "https://Stackoverflow.com/users/2683759",
"pm_score": 4,
"selected": false,
"text": "<p>Try following code will Add one day to current date</p>\n\n<pre><code>select DateAdd(day, 1, GetDate())\n</code></pre>\n\n<p>And in the same way can use Year, Month, Hour, Second etc. instead of day in the same function </p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] |
This is the page that I'm having. But the resize part in the section does not seem to be working. I copied most of the code from the [Ajax site](http://www.asp.net/ajax/ajaxcontroltoolkit/samples/UpdatePanelAnimation/UpdatePanelAnimation.aspx). I placed a alert() in the tag (line 108) to find the value of 'b.\_originalHeight' and it shows up as '44'. I have also tried the code in the above-said tutorial (line 132) and that did not work either. (I'm not sure where it is getting this value from. But I need it to show all the controls on the form.
```
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddEditContest.ascx.cs" Inherits="TMPInternational.Spawn2DotComAdmin.Contest.UserControls.AddEditContest" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="uc" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<%@ Register TagPrefix="ew" Assembly="eWorld.UI, Version=1.9.0.0, Culture=neutral, PublicKeyToken=24d65337282035f2" Namespace="eWorld.UI" %>
<h1 style="margin-left:8px">Add/Edit Contest</h1>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<div style="text-align:left;width:500px; margin-left:8px">
<div id="PanelContainer">
<asp:UpdatePanel ID="AddEditContestUpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<div id="background" style="text-align:left; height: 44px;">
<asp:Panel ID="ContestList" runat="server">
<asp:datagrid AllowSorting="false" id="ContestGrid" GridLines="None" CellPadding="5"
Width="100%" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#cccccc"
HeaderStyle-Font-Size="15px" HeaderStyle-Font-Bold="true" HeaderStyle-BackColor="#888f9b"
Runat="server" AllowPaging="True" PageSize="10"
PagerStyle-NextPageText="Next >>" PagerStyle-PrevPageText="<< Back" >
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="ContestID" DataNavigateUrlFormatString="../?Load=AddEditContest&Type=Edit&ContestID={0}"
DataTextField="Title" ItemStyle-width="30%" headertext="Contest Title" />
<asp:BoundColumn DataField="StartDate" ItemStyle-Width="35%" HeaderText="Start Date" />
<asp:BoundColumn DataField="EndDate" ItemStyle-Width="35%" HeaderText="End Date" />
</Columns>
</asp:datagrid>
<div style="text-align:right;">
<asp:ImageButton ID="AddContest" runat="server"
ImageUrl="~/Contest/Images/Add.png" AlternateText="Add Contest"
onclick="AddContest_Click" />
</div>
</asp:Panel>
<asp:Panel ID="FieldsPanel" runat="server">
<p /><b>Title</b>
<br />
<asp:TextBox Runat="server" id="TitleText" />
<asp:RequiredFieldValidator id="TitleValidator" runat="server" ForeColor="Red"
ErrorMessage="Please add a title" ControlToValidate="TitleText">*</asp:RequiredFieldValidator>
<p /><b>Contest Description</b>
<br />
Use HTML tags to format this area. Start paragraphs with
<p /> tag, bold items with <b></b> tags. Create a
line-break between lines with one <br /> tag.<br />
<asp:TextBox Runat="server" ID="DescriptionText" TextMode="MultiLine" Width="400" Height="200" />
<asp:RequiredFieldValidator id="DescriptionValidator" runat="server" ErrorMessage="Please add a description"
ControlToValidate="DescriptionText" ForeColor="Red">*</asp:RequiredFieldValidator>
<p />
<b>Contest Start Date</b>
<br />
<ew:CalendarPopup id="StartDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif"
CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select"
CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False">
<WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" />
<MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" />
<OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" />
<GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/>
<TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" />
<DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" />
<WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" />
<SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/>
<HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" />
</ew:CalendarPopup>
<ew:TimePicker id="StartTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time"
ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px">
<TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" />
<SelectedTimeStyle ForeColor="Blue" BackColor="Gray" />
</ew:TimePicker>
<p/><b>Contest End Date</b>
<br />
<ew:CalendarPopup id="EndDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif"
CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select"
CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False">
<WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" />
<MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" />
<OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" />
<GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/>
<TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" />
<DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" />
<WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" />
<SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/>
<HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" />
</ew:CalendarPopup>
<ew:TimePicker id="EndTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time"
ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px">
<TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" />
<SelectedTimeStyle ForeColor="Blue" BackColor="Gray" />
</ew:TimePicker>
<p />
<asp:ImageButton ID="SaveContestButton" runat="server" AlternateText="Confirm"
ImageUrl="~/Contest/Images/Confirm.png" onclick="SaveContestButton_Click" />
</asp:Panel>
<br />
<asp:Label ID="MessageLabel" runat="server" />
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="SaveContestButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
<uc:UpdatePanelAnimationExtender ID="upae" BehaviorID="animation" runat="server" TargetControlID="AddEditContestUpdatePanel">
<Animations>
<OnUpdating>
<Sequence>
<%-- Store the original height of the panel --%>
<ScriptAction Script="var b = $find('animation'); b._originalHeight = b._element.offsetHeight;" />
<%-- Disable all the controls --%>
<Parallel duration="0">
<EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="false" />
</Parallel>
<StyleAction Attribute="overflow" Value="hidden" />
<%-- Do each of the selected effects --%>
<Parallel duration=".25" Fps="30">
<FadeOut AnimationTarget="PanelContainer" minimumOpacity=".2" />
<Resize Height="0px" />
</Parallel>
</Sequence>
</OnUpdating>
<OnUpdated>
<Sequence>
<%-- Do each of the selected effects --%>
<Parallel duration=".25" Fps="30">
<FadeIn AnimationTarget="PanelContainer" minimumOpacity=".2" />
<Length duration="2" fps="40" Property="style" PropertyKey="height"
StartValue="10" EndValueScript="$get('animation').offsetHeight"
AnimationTarget="animation" />
<%--Also tried the below
<Resize HeightScript="$find('animation')._originalHeight" />
--%>
</Parallel>
<%-- Enable all the controls --%>
<Parallel duration="0">
<EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="true" />
</Parallel>
</Sequence>
</OnUpdated>
</Animations>
</uc:UpdatePanelAnimationExtender>
</div>
```
|
Use the following function:
```
DATEADD(type, value, date)
```
* **date** is the date you want to manipulate
* **value** is the integere value you want to add (or subtract if you provide a negative number)
* **type** is one of:
* yy, yyyy: year
* qq, q: quarter
* mm, m: month
* dy, y: day of year
* dd, d: day
* wk, ww: week
* dw, w: weekday
* hh: hour
* mi, n: minute
* ss or s: second
* ms: millisecond
* mcs: microsecond
* ns: nanosecond
```
SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day
```
<http://msdn.microsoft.com/en-us/library/ms186819.aspx>
|
167,509 |
<p>I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception:</p>
<p>System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.</p>
<p>How do I customize the sorting or comparison logic to handle the null case?</p>
|
[
{
"answer_id": 167519,
"author": "Seth Petry-Johnson",
"author_id": 23632,
"author_profile": "https://Stackoverflow.com/users/23632",
"pm_score": 3,
"selected": true,
"text": "<p>The Nullable type exposes a comparison method for comparing nullable types, so the solution is to override the gridview sorting logic and manually specify a comparison:</p>\n\n<pre><code>gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting);\n\nprotected void gridView_Sorting(object sender, GridViewSortEventArgs e)\n{\n // Only add custom handling for the sort expression on the \n // Nullable<int> column\n if (e.SortExpression == \"MySortExpression\")\n {\n // Convert datasource to a List<T>\n list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2)\n {\n return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp);\n }));\n\n // Bind the sorted list back to the gridview\n }\n else\n {\n // delegate to the gridview to handle its own sorting\n }\n}\n</code></pre>\n"
},
{
"answer_id": 167565,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 0,
"selected": false,
"text": "<p>You could also override the null when you bind the data, placing a 0 instead. Your answer is far better. :)</p>\n\n<p>You could also make a custom type that overrides the Compare operator. But that would just duplicate (and complicate) what you have above.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23632/"
] |
I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception:
System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.
How do I customize the sorting or comparison logic to handle the null case?
|
The Nullable type exposes a comparison method for comparing nullable types, so the solution is to override the gridview sorting logic and manually specify a comparison:
```
gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting);
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
// Only add custom handling for the sort expression on the
// Nullable<int> column
if (e.SortExpression == "MySortExpression")
{
// Convert datasource to a List<T>
list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2)
{
return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp);
}));
// Bind the sorted list back to the gridview
}
else
{
// delegate to the gridview to handle its own sorting
}
}
```
|
167,542 |
<p>I'm trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax. I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns.</p>
|
[
{
"answer_id": 167553,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 1,
"selected": false,
"text": "<p>Example:</p>\n\n<pre><code> CREATE TABLE `synthesis`.`INV_MasterItemList` (\n `MasterItemList_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,\n `Customer_ID` INTEGER UNSIGNED NOT NULL,\n `Model_ID` INTEGER UNSIGNED NOT NULL,\n `Serial` VARCHAR(45) NOT NULL,\n PRIMARY KEY (`MasterItemList_ID`),\n UNIQUE INDEX `INDEX_UNIQUE`(`Customer_ID`, `Model_ID`, `Serial`)\n )\n</code></pre>\n"
},
{
"answer_id": 167561,
"author": "Neil Williams",
"author_id": 9617,
"author_profile": "https://Stackoverflow.com/users/9617",
"pm_score": 4,
"selected": true,
"text": "<pre><code>CREATE TABLE table_name \n(\n c1 INT NOT NULL,\n c2 INT NOT NULL,\n PRIMARY KEY (c1, c2)\n)\n</code></pre>\n"
},
{
"answer_id": 167566,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>create table .....\n\n\nprimary key (`id1`, `id2`)\n)\n</code></pre>\n"
},
{
"answer_id": 167568,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 1,
"selected": false,
"text": "<p>An example (from osCommerce) :</p>\n\n<pre><code>CREATE TABLE categories_description (\n categories_id int DEFAULT '0' NOT NULL,\n language_id int DEFAULT '1' NOT NULL,\n categories_name varchar(32) NOT NULL,\n PRIMARY KEY (categories_id, language_id),\n KEY idx_categories_name (categories_name)\n);\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266/"
] |
I'm trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax. I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns.
|
```
CREATE TABLE table_name
(
c1 INT NOT NULL,
c2 INT NOT NULL,
PRIMARY KEY (c1, c2)
)
```
|
167,562 |
<p>How can I know if a device is supported on a running Linux and if so, which device driver controls it?
For instance, <code>lspci</code> on a server (PowerEdge 2900) gives:</p>
<pre class="lang-none prettyprint-override"><code>00:00.0 Host bridge: Intel Corporation 5000X Chipset Memory Controller Hub (rev 12)
00:02.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 2 (rev 12)
00:03.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 3 (rev 12)
00:04.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 4 (rev 12)
00:05.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 5 (rev 12)
00:06.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x8 Port 6-7 (rev 12)
00:07.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 7 (rev 12)
00:08.0 System peripheral: Intel Corporation 5000 Series Chipset DMA Engine (rev 12)
00:10.0 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12)
00:10.1 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12)
00:10.2 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12)
00:11.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12)
00:13.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12)
00:15.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12)
00:16.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12)
00:1c.0 PCI bridge: Intel Corporation 631xESB/632xESB/3100 Chipset PCI Express Root Port 1 (rev 09)
00:1d.0 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #1 (rev 09)
00:1d.1 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #2 (rev 09)
00:1d.2 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #3 (rev 09)
00:1d.3 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #4 (rev 09)
00:1d.7 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset EHCI USB2 Controller (rev 09)
00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev d9)
00:1f.0 ISA bridge: Intel Corporation 631xESB/632xESB/3100 Chipset LPC Interface Controller (rev 09)
00:1f.1 IDE interface: Intel Corporation 631xESB/632xESB IDE Controller (rev 09)
00:1f.2 IDE interface: Intel Corporation 631xESB/632xESB/3100 Chipset SATA IDE Controller (rev 09)
01:00.0 PCI bridge: Intel Corporation 80333 Segment-A PCI Express-to-PCI Express Bridge
01:00.2 PCI bridge: Intel Corporation 80333 Segment-B PCI Express-to-PCI Express Bridge
02:0e.0 RAID bus controller: Dell PowerEdge Expandable RAID controller 5
04:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3)
05:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12)
06:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Upstream Port (rev 01)
06:00.3 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express to PCI-X Bridge (rev 01)
07:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E1 (rev 01)
07:01.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E2 (rev 01)
08:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3)
09:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12)
0b:02.0 Multimedia audio controller: Creative Labs SB Audigy (rev 03)
0b:02.1 Input device controller: Creative Labs SB Audigy Game Port (rev 03)
0b:02.2 FireWire (IEEE 1394): Creative Labs SB Audigy FireWire Port
10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02)
</code></pre>
<p>How can I find:</p>
<ol>
<li>which device driver (kernel module) controls each device?</li>
<li>which device is controlled by a device driver compiled <em>in</em> the kernel (and not as a module)</li>
<li>which device doesn't have a device driver (compiled in or as a module)?</li>
</ol>
<p>This script (adapted from another in "Linux Kernel in a Nutshell") partially resolves #1:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/bash
for i in $(find /sys/ -name modalias); do
echo "----------------------------------"
modalias=$(cat $i)
echo "$(dirname $i) --> $modalias"
/sbin/modprobe --config /dev/null --show-depends $(cat $i) 2>&1
done
</code></pre>
<p>But there are some problems with it:</p>
<ol>
<li><p>I don't know of an <em>automated way</em> to convert
<code>/sys/devices/pci0000:00/0000:00:1e.0/0000:10:0d.0 --> pci:v00001002d0000515Esv00001028sd000001B1bc03sc00i00</code>
to
<code>10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02)</code></p></li>
<li><p>In some cases the devices are internal to the MB and I don't even know a way to find the real name of the device. For example:</p></li>
</ol>
<pre class="lang-none prettyprint-override"><code>/sys/devices/platform/dcdbas --> platform:dcdbas
/sys/devices/platform/iTCO_wdt --> platform:iTCO_wdt
/sys/devices/LNXSYSTM:00 --> acpi:LNXSYSTM:
/sys/devices/LNXSYSTM:00/device:00/PNP0C33:00 --> acpi:PNP0C33:PNP0C01:
/sys/devices/LNXSYSTM:00/device:00/PNP0A08:00 --> acpi:PNP0A08:PNP0A03:
/sys/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:0d/PNP0200:00 --> acpi:PNP0200:
</code></pre>
<p>and many others.</p>
<ol start="3">
<li>When the device driver is <em>compiled in</em> (or doesn't exist) the response is <code>FATAL: Module _XXXX_ not found.</code> Indicating there is no module for the device.</li>
</ol>
<p>In some cases the driver is compiled in (e.g.)</p>
<pre><code>/sys/devices/platform/serial8250 --> platform:serial8250
FATAL: Module platform:serial8250 not found.
/sys/devices/platform/i8042 --> platform:i8042
FATAL: Module platform:i8042 not found.
</code></pre>
<p>In other cases, the driver just doesn't exist. But I don't know a way to tell the difference.</p>
<p>Does anyone know?</p>
|
[
{
"answer_id": 167606,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think you can get a 100% clear-cut answer that you can get in Windows device manager.</p>\n\n<ul>\n<li>A device may be controlled by several kernel modules (say <code>nvidia</code> + <code>agpgart</code>).</li>\n<li>A kernel module may control more than one device (<code>usbhid</code>).</li>\n<li>You can also have many-to-many relationship (<code>usbcore</code> + <code>usbhid</code>).</li>\n</ul>\n"
},
{
"answer_id": 168731,
"author": "ypnos",
"author_id": 21974,
"author_profile": "https://Stackoverflow.com/users/21974",
"pm_score": 2,
"selected": false,
"text": "<p>Try <strong>HAL device manager</strong>, which is also available as \"KDE HAL device manager\" and \"gnome-device-manager\". Basically, these are frontends to the Hardware Abstraction Layer (HAL), which reads <code>/sysfs/</code> et al.</p>\n\n<p>It gives information like \"info.linux.driver\", see the screenshot below:</p>\n\n<p><a href=\"https://i3.photobucket.com/albums/y69/kagesenshi/blog-uploads/060728-1.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i3.photobucket.com/albums/y69/kagesenshi/blog-uploads/060728-1.jpg\" width=\"300\"></a></p>\n\n<p>I'm sorry I don't know how to fiddle out this information yourself in sysfs, but it must be somewhere if HAL is able to find it :-)</p>\n"
},
{
"answer_id": 171372,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 1,
"selected": false,
"text": "<p>lspci -n will give you PCI ids that you can search for on the <a href=\"http://cateee.net/lkddb/\" rel=\"nofollow noreferrer\">linux kernel driver database</a>. This will tell you which kernel options to enable.</p>\n"
},
{
"answer_id": 999853,
"author": "Robert S. Barnes",
"author_id": 71074,
"author_profile": "https://Stackoverflow.com/users/71074",
"pm_score": 0,
"selected": false,
"text": "<p>The following script will tell you which dynamically loaded drivers are running, although I would also like an automated way of figuring out which compiled in modules are actually in use also so I could de-bloat my kernel some more.</p>\n\n<pre><code>#!/bin/bash\n/sbin/lsmod | tail -n+2 | cut -d\" \" -f1 | xargs /sbin/modinfo -n | sort ; \n</code></pre>\n\n<p>I'm not sure how relevent the rest of this is to your question but thought you or others might find it useful. </p>\n\n<p>The following code will figure out which .config options control each of the dynamically loaded kernel modules, although I haven't figured out a way to do the same for dynamic modules in the ubuntu lum package yet ( this script is still a work in progress ):</p>\n\n<pre><code>#!/usr/bin/perl -w\n\nuse strict;\nuse Getopt::Long;\n\nmy ($kernConfigIn, $kernConfigOut, $kernSourceDir, $lumSourceDir, $lumConfigIn, $lumConfigOut, $help);\n\nGetOptions(\n 'ksd=s' => \\$kernSourceDir,\n 'lsd=s' => \\$lumSourceDir,\n 'kci=s' => \\$kernConfigIn,\n 'lci=s' => \\$lumConfigIn,\n 'kco=s' => \\$kernConfigOut,\n 'lco=s' => \\$lumConfigOut,\n 'help' => \\$help);\n\nif ($help || !$kernSourceDir || !$lumSourceDir ) { Usage($0); }\n\nsub Usage { print \"usage error\\n\"; exit; };\n\nmy @modules = `/sbin/lsmod | tail -n+2 | cut -d\" \" -f1 | xargs /sbin/modinfo -n | sort ;`;\nmy @kconfig;\n\nforeach my $module (@modules) {\n my ($package, $path, $modName) = ( $module =~ m/\\/((?:kernel)|(?:ubuntu))\\/(.*)\\/(.*)\\.ko/) ;\n $package eq 'kernel' ? push @kconfig, kernel($package, $path, $modName) : ubuntu($package, $path, $modName); \n}\n\n# kernel package\nsub kernel {\n my ($package, $path, $modName) = @_;\n my $makefile = $kernSourceDir.$path.\"/Makefile\"; \n# print \"$package, $path, $modName\\n\";\n# print \"$makefile\\n\";\n my $option;\n chomp($option = `cat $makefile | sed -n \"s/^obj-\\\\\\$(CONFIG_\\\\([A-Z0-9_]*\\\\))\\\\W*+=.*\"$modName\"\\\\.o.*/CONFIG_\\\\1/p\"`);\n print \"$option\\n\";\n return $option;\n}\n\n# deal with lum configs\nsub ubuntu {\n\n}\n</code></pre>\n\n<p>There is a script by Andreas Goelzer which with slight modification will turn off all unused kernel modules in your .config which significantly speeds up your compiles.</p>\n\n<p>You can find it here:</p>\n\n<p><a href=\"http://andreas.goelzer.de/kernel-config-based-on-lsmod-output\" rel=\"nofollow noreferrer\">http://andreas.goelzer.de/kernel-config-based-on-lsmod-output</a></p>\n"
},
{
"answer_id": 3172162,
"author": "anders",
"author_id": 319241,
"author_profile": "https://Stackoverflow.com/users/319241",
"pm_score": 1,
"selected": false,
"text": "<p>Well this is a little late, and maybe at that time (2008) didn't even exists, but lspci -n or better lspci -k should fix the problem; for instance:</p>\n<blockquote>\n<p>04:00.0 Network controller: Broadcom Corporation BCM4312 802.11b/g (rev 01)</p>\n<pre><code> Kernel driver in use: wl\n Kernel modules: wl, ssb\n</code></pre>\n</blockquote>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8013/"
] |
How can I know if a device is supported on a running Linux and if so, which device driver controls it?
For instance, `lspci` on a server (PowerEdge 2900) gives:
```none
00:00.0 Host bridge: Intel Corporation 5000X Chipset Memory Controller Hub (rev 12)
00:02.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 2 (rev 12)
00:03.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 3 (rev 12)
00:04.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 4 (rev 12)
00:05.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 5 (rev 12)
00:06.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x8 Port 6-7 (rev 12)
00:07.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 7 (rev 12)
00:08.0 System peripheral: Intel Corporation 5000 Series Chipset DMA Engine (rev 12)
00:10.0 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12)
00:10.1 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12)
00:10.2 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12)
00:11.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12)
00:13.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12)
00:15.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12)
00:16.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12)
00:1c.0 PCI bridge: Intel Corporation 631xESB/632xESB/3100 Chipset PCI Express Root Port 1 (rev 09)
00:1d.0 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #1 (rev 09)
00:1d.1 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #2 (rev 09)
00:1d.2 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #3 (rev 09)
00:1d.3 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #4 (rev 09)
00:1d.7 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset EHCI USB2 Controller (rev 09)
00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev d9)
00:1f.0 ISA bridge: Intel Corporation 631xESB/632xESB/3100 Chipset LPC Interface Controller (rev 09)
00:1f.1 IDE interface: Intel Corporation 631xESB/632xESB IDE Controller (rev 09)
00:1f.2 IDE interface: Intel Corporation 631xESB/632xESB/3100 Chipset SATA IDE Controller (rev 09)
01:00.0 PCI bridge: Intel Corporation 80333 Segment-A PCI Express-to-PCI Express Bridge
01:00.2 PCI bridge: Intel Corporation 80333 Segment-B PCI Express-to-PCI Express Bridge
02:0e.0 RAID bus controller: Dell PowerEdge Expandable RAID controller 5
04:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3)
05:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12)
06:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Upstream Port (rev 01)
06:00.3 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express to PCI-X Bridge (rev 01)
07:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E1 (rev 01)
07:01.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E2 (rev 01)
08:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3)
09:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12)
0b:02.0 Multimedia audio controller: Creative Labs SB Audigy (rev 03)
0b:02.1 Input device controller: Creative Labs SB Audigy Game Port (rev 03)
0b:02.2 FireWire (IEEE 1394): Creative Labs SB Audigy FireWire Port
10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02)
```
How can I find:
1. which device driver (kernel module) controls each device?
2. which device is controlled by a device driver compiled *in* the kernel (and not as a module)
3. which device doesn't have a device driver (compiled in or as a module)?
This script (adapted from another in "Linux Kernel in a Nutshell") partially resolves #1:
```bash
#!/bin/bash
for i in $(find /sys/ -name modalias); do
echo "----------------------------------"
modalias=$(cat $i)
echo "$(dirname $i) --> $modalias"
/sbin/modprobe --config /dev/null --show-depends $(cat $i) 2>&1
done
```
But there are some problems with it:
1. I don't know of an *automated way* to convert
`/sys/devices/pci0000:00/0000:00:1e.0/0000:10:0d.0 --> pci:v00001002d0000515Esv00001028sd000001B1bc03sc00i00`
to
`10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02)`
2. In some cases the devices are internal to the MB and I don't even know a way to find the real name of the device. For example:
```none
/sys/devices/platform/dcdbas --> platform:dcdbas
/sys/devices/platform/iTCO_wdt --> platform:iTCO_wdt
/sys/devices/LNXSYSTM:00 --> acpi:LNXSYSTM:
/sys/devices/LNXSYSTM:00/device:00/PNP0C33:00 --> acpi:PNP0C33:PNP0C01:
/sys/devices/LNXSYSTM:00/device:00/PNP0A08:00 --> acpi:PNP0A08:PNP0A03:
/sys/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:0d/PNP0200:00 --> acpi:PNP0200:
```
and many others.
3. When the device driver is *compiled in* (or doesn't exist) the response is `FATAL: Module _XXXX_ not found.` Indicating there is no module for the device.
In some cases the driver is compiled in (e.g.)
```
/sys/devices/platform/serial8250 --> platform:serial8250
FATAL: Module platform:serial8250 not found.
/sys/devices/platform/i8042 --> platform:i8042
FATAL: Module platform:i8042 not found.
```
In other cases, the driver just doesn't exist. But I don't know a way to tell the difference.
Does anyone know?
|
I don't think you can get a 100% clear-cut answer that you can get in Windows device manager.
* A device may be controlled by several kernel modules (say `nvidia` + `agpgart`).
* A kernel module may control more than one device (`usbhid`).
* You can also have many-to-many relationship (`usbcore` + `usbhid`).
|
167,567 |
<p>I have been asked to write a testing application that needs to test a new stored procedure on multiple rows in a database, in essence I want to do something like this:</p>
<pre><code>[Test]
public void TestSelect()
{
foreach(id in ids)
{
DataTable old = Database.call("old_stored_proc",id);
DataTable new_ = Database.call("new_stored_proc",id);
Assert.AreEqual(old.Rows[0]["column"],ne_.Rows[0]["column"]);
}
}
</code></pre>
<p>When I run this test, if 1 row doesn't match the other, the entire test fails; instead I would like to count how many times the assertion was passed and how many times it has failed. Is there a way to do this with NUnit?</p>
<p>I realize that NUnit might be overkill and this is a simple task without it...I just wanted to learn it. ;)</p>
|
[
{
"answer_id": 167579,
"author": "DKATDT",
"author_id": 678,
"author_profile": "https://Stackoverflow.com/users/678",
"pm_score": 0,
"selected": false,
"text": "<p>Well you could declare a counter and then assert the value of the counter to determine pass/fail</p>\n\n<p>Also, you could do the bulk of the work in the test setup, and then just create multiple tests. </p>\n\n<p>I'm not clear as to why you need all the assert stmts in the same test.</p>\n"
},
{
"answer_id": 167598,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 1,
"selected": false,
"text": "<p>I would count the number of rows which do not match and then would write an assertion which will compare this number with 0 and would return the number of non matching strings in the message.</p>\n\n<p>you could also use <code>Assert.Greater</code> for this.</p>\n\n<p>P.S. In principal you should try to do one assertion per unit test. That's the gist of it.</p>\n"
},
{
"answer_id": 167619,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 3,
"selected": false,
"text": "<p>Seems like you are just Asserting the wrong thing. If you want to check all the values and then assert that there are no errors (or show the number of errors) then try this:</p>\n\n<pre><code>[Test]\npublic void TestSelect()\n{\n int errors = 0;\n foreach(id in ids)\n {\n DataTable old = Database.call(\"old_stored_proc\",id);\n DataTable new_ = Database.call(\"new_stored_proc\",id);\n\n if (old.Rows[0][\"column\"] != new_.Rows[0][\"column\"])\n {\n errors++;\n } \n }\n\n Assert.AreEqual(0, errors, \"There were \" + errors + \" errors.\");\n}\n</code></pre>\n"
},
{
"answer_id": 167713,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 4,
"selected": true,
"text": "<p>1) If the id's are constant and not looked up at test run time, create a separate unit test fixture for each id. That way you will know which id's are actually failing. See here for a write up on the problems with data driven tests:<br>\n<a href=\"http://googletesting.blogspot.com/2008/09/tott-data-driven-traps.html\" rel=\"noreferrer\">http://googletesting.blogspot.com/2008/09/tott-data-driven-traps.html</a></p>\n\n<p>2) If you need to dynamically look up the id's making it impossible to create a fixture for each id, use akmad's suggestion with one change. Keep a list of id's where the values are not equal and add the list to the error message. It will be extremely difficult to diagnose a failing test that only states the number of errors, as you won't know what id's cause the errors.</p>\n\n<p>3) I don't know how difficult it would be to do in NUnit, but in PyUnit, when we need to run tests on dynamically generated data, we dynamically create tests fixtures and attach them to the TestCase class so that we have a failed test for each piece of data that does not pass. Though I imagine this would be much more difficult without python's dynamic abilities.</p>\n"
},
{
"answer_id": 187302,
"author": "Scott Lawrence",
"author_id": 3475,
"author_profile": "https://Stackoverflow.com/users/3475",
"pm_score": 0,
"selected": false,
"text": "<p>Based on the objective you laid out, the entire test <strong>should</strong> fail if one row doesn't match another. Counting the number of times an assertion passes or fails gives you less information than a comparison of the outcome you expected with the outcome you actually got.</p>\n"
},
{
"answer_id": 2926985,
"author": "Yann Trevin",
"author_id": 563,
"author_profile": "https://Stackoverflow.com/users/563",
"pm_score": 2,
"selected": false,
"text": "<p>I know that the question is specifically about NUnit, but interestingly enough, <a href=\"http://gallio.org\" rel=\"nofollow noreferrer\">Gallio/MbUnit</a> has a feature which allows to run and catch several assertions at once.</p>\n\n<pre><code>[Test]\npublic void MultipleTest()\n{\n Assert.Multiple(() =>\n {\n Assert.IsTrue(blabla);\n Assert.AreEqual(pik, pok);\n // etc.\n }\n}\n</code></pre>\n\n<p>The <code>Assert.Multiple</code> is catching <strong>all</strong> the failing assertions and is going to report them at the end of the test.</p>\n"
},
{
"answer_id": 23570997,
"author": "yoyo",
"author_id": 503688,
"author_profile": "https://Stackoverflow.com/users/503688",
"pm_score": 0,
"selected": false,
"text": "<p>I recently had the same issue. I combined the idea of counting errors with Yann Trevin's mention of Assert.Multiple into an extension method for IEnumberable that lets me do things like:</p>\n\n<pre><code>[Test]\npublic void TestEvenNumbers()\n{\n int[] numbers = new int[] { 2, 4, 12, 22, 13, 42 };\n numbers.AssertAll((num) => Assert.That((num % 2) == 0, \"{0} is an odd number\", num));\n}\n</code></pre>\n\n<p>Which results in the NUnit output:</p>\n\n<pre><code>TestEvenNumbers:\n 5 of 6 tests passed; 0 inconclusive\nFAILED: 13: 13 is an odd number\n Expected: True\n But was: False\n\n Expected: 6\n But was: 5\n</code></pre>\n\n<p>And the solution to the OP's problem would be:</p>\n\n<pre><code>[Test]\npublic void TestSelect()\n{\n ids.AssertAll(CheckStoredProcedures);\n}\n\nprivate void CheckStoredProcedures(Id id)\n{\n DataTable old = Database.call(\"old_stored_proc\",id);\n DataTable new_ = Database.call(\"new_stored_proc\",id);\n\n Assert.AreEqual(old.Rows[0][\"column\"], new_.Rows[0][\"column\"]);\n}\n</code></pre>\n\n<p>Here is the extension method (note that I used \"All\" instead of \"Multiple\" for consistency with Linq terminology):</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing NUnit.Framework;\n\npublic static class NUnitExtensions\n{\n public static void AssertAll<T>(this IEnumerable<T> objects, Action<T> test)\n {\n int total = 0;\n int passed = 0;\n int failed = 0;\n int inconclusive = 0;\n var sb = new StringBuilder();\n foreach (var obj in objects)\n {\n total++;\n try\n {\n test(obj);\n passed++;\n }\n catch (InconclusiveException assertion)\n {\n inconclusive++;\n string message = string.Format(\"INCONCLUSIVE: {0}: {1}\", obj.ToString(), assertion.Message);\n Console.WriteLine(message);\n sb.AppendLine(message);\n }\n catch (AssertionException assertion)\n {\n failed++;\n string message = string.Format(\"FAILED: {0}: {1}\", obj.ToString(), assertion.Message);\n Console.WriteLine(message);\n sb.AppendLine(message);\n }\n }\n\n if (passed != total)\n {\n string details = sb.ToString();\n string message = string.Format(\"{0} of {1} tests passed; {2} inconclusive\\n{3}\", passed, total, inconclusive, details);\n if (failed == 0)\n {\n Assert.Inconclusive(message);\n }\n else\n {\n Assert.AreEqual(total, passed, message);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 50951617,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"https://github.com/nunit/docs/wiki/TestCase-Attribute\" rel=\"nofollow noreferrer\"><code>[TestCase()]</code> attribute</a> if a simple hard coded list of IDs.</p>\n\n<pre><code>[Test]\n[TestCase(1234)]\n[TestCase(5678)]\n[TestCase(7654)]\npublic void TestSelect(int id)\n{\n DataTable old = Database.call(\"old_stored_proc\", id);\n DataTable new_ = Database.call(\"new_stored_proc\", id);\n\n Assert.AreEqual(old.Rows[0][\"column\"], new_.Rows[0][\"column\"]);\n}\n</code></pre>\n\n<p>This will generate three separate tests for each ID and whatever nunit test runner you use will display pass/fail counts.</p>\n\n<p>If need to generate a dynamic list of IDs then recommend using <a href=\"https://github.com/nunit/docs/wiki/TestCaseSource-Attribute\" rel=\"nofollow noreferrer\"><code>[TestCaseSource()]</code> attribute</a>.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
I have been asked to write a testing application that needs to test a new stored procedure on multiple rows in a database, in essence I want to do something like this:
```
[Test]
public void TestSelect()
{
foreach(id in ids)
{
DataTable old = Database.call("old_stored_proc",id);
DataTable new_ = Database.call("new_stored_proc",id);
Assert.AreEqual(old.Rows[0]["column"],ne_.Rows[0]["column"]);
}
}
```
When I run this test, if 1 row doesn't match the other, the entire test fails; instead I would like to count how many times the assertion was passed and how many times it has failed. Is there a way to do this with NUnit?
I realize that NUnit might be overkill and this is a simple task without it...I just wanted to learn it. ;)
|
1) If the id's are constant and not looked up at test run time, create a separate unit test fixture for each id. That way you will know which id's are actually failing. See here for a write up on the problems with data driven tests:
<http://googletesting.blogspot.com/2008/09/tott-data-driven-traps.html>
2) If you need to dynamically look up the id's making it impossible to create a fixture for each id, use akmad's suggestion with one change. Keep a list of id's where the values are not equal and add the list to the error message. It will be extremely difficult to diagnose a failing test that only states the number of errors, as you won't know what id's cause the errors.
3) I don't know how difficult it would be to do in NUnit, but in PyUnit, when we need to run tests on dynamically generated data, we dynamically create tests fixtures and attach them to the TestCase class so that we have a failed test for each piece of data that does not pass. Though I imagine this would be much more difficult without python's dynamic abilities.
|
167,576 |
<p>I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.</p>
<p>Here are two possible ways of doing it. Which one is the standard/best way of doing it?</p>
<p>First way:</p>
<pre><code>IF EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='mytablename')
SELECT 1 AS res ELSE SELECT 0 AS res;
</code></pre>
<p>Second way:</p>
<pre><code>IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL
SELECT 1 AS res ELSE SELECT 0 AS res;
</code></pre>
<p><strong>MySQL</strong> provides the simple</p>
<pre><code>SHOW TABLES LIKE '%tablename%';
</code></pre>
<p>statement. I am looking for something similar.</p>
|
[
{
"answer_id": 167599,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it. See Approach 1 in <a href=\"https://stackoverflow.com/a/27602349/270155\">this answer</a>.</p>\n"
},
{
"answer_id": 167610,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 8,
"selected": false,
"text": "<p>We always use the <code>OBJECT_ID</code> style for as long as I remember</p>\n\n<pre><code>IF OBJECT_ID('*objectName*', 'U') IS NOT NULL \n</code></pre>\n"
},
{
"answer_id": 167680,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 12,
"selected": true,
"text": "<p>For queries like this it is always best to use an <code>INFORMATION_SCHEMA</code> view. These views are (mostly) standard across many different databases and rarely change from version to version.</p>\n\n<p>To check if a table exists use:</p>\n\n<pre><code>IF (EXISTS (SELECT * \n FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_SCHEMA = 'TheSchema' \n AND TABLE_NAME = 'TheTable'))\nBEGIN\n --Do Stuff\nEND\n</code></pre>\n"
},
{
"answer_id": 1601406,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 3,
"selected": false,
"text": "<p>If you need to work on different databases:</p>\n\n<pre><code>DECLARE @Catalog VARCHAR(255)\nSET @Catalog = 'MyDatabase'\n\nDECLARE @Schema VARCHAR(255)\nSET @Schema = 'dbo'\n\nDECLARE @Table VARCHAR(255)\nSET @Table = 'MyTable'\n\nIF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_CATALOG = @Catalog \n AND TABLE_SCHEMA = @Schema \n AND TABLE_NAME = @Table))\nBEGIN\n --do stuff\nEND\n</code></pre>\n"
},
{
"answer_id": 2155299,
"author": "James Bloomer",
"author_id": 38249,
"author_profile": "https://Stackoverflow.com/users/38249",
"pm_score": 8,
"selected": false,
"text": "<p>Also note that if for any reason you need to check for a temporary table you can do this:</p>\n\n<pre><code>if OBJECT_ID('tempdb..#test') is not null\n --- temp table exists\n</code></pre>\n"
},
{
"answer_id": 4760619,
"author": "dko",
"author_id": 528537,
"author_profile": "https://Stackoverflow.com/users/528537",
"pm_score": 3,
"selected": false,
"text": "<p>I know it is an old question but I have found this possibility if you plan to call it often.</p>\n\n<pre><code>create procedure Table_Exists\n@tbl varchar(50)\nas\nreturn (select count(*) from sysobjects where type = 'U' and name = @tbl)\ngo\n</code></pre>\n"
},
{
"answer_id": 5579755,
"author": "dilip kumar singh",
"author_id": 696619,
"author_profile": "https://Stackoverflow.com/users/696619",
"pm_score": 4,
"selected": false,
"text": "<pre class=\"lang-sql prettyprint-override\"><code>IF EXISTS \n(\n SELECT * \n FROM sys.objects \n WHERE object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]') \n AND \n type in (N'U')\n)\nBEGIN\n\n -- Do whatever you need to here.\n\nEND\n</code></pre>\n\n<p>Here in the above code, the table name is <code>Mapping_APCToFANavigator</code>.</p>\n"
},
{
"answer_id": 9724871,
"author": "Larry Leonard",
"author_id": 1272181,
"author_profile": "https://Stackoverflow.com/users/1272181",
"pm_score": 5,
"selected": false,
"text": "<p>Looking for a table on a different database:</p>\n\n<pre><code>if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')\n print 'Exists'\n</code></pre>\n"
},
{
"answer_id": 15933669,
"author": "sumon",
"author_id": 2162651,
"author_profile": "https://Stackoverflow.com/users/2162651",
"pm_score": -1,
"selected": false,
"text": "<p>consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1. \nTo do this open visual studio and do the following:</p>\n\n<p>Right click on t1, then Script table as, then DROP and Create To, then New Query Editor </p>\n\n<p>you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one. </p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 19564163,
"author": "Moccassin",
"author_id": 2854813,
"author_profile": "https://Stackoverflow.com/users/2854813",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-sql prettyprint-override\"><code>IF EXISTS \n(\n SELECT * \n\n FROM INFORMATION_SCHEMA.TABLES \n\n WHERE TABLE_SCHEMA = 'PutSchemaHere' \n AND \n TABLE_NAME = 'PutTableNameHere'\n)\n</code></pre>\n"
},
{
"answer_id": 20141958,
"author": "sansalk",
"author_id": 1403070,
"author_profile": "https://Stackoverflow.com/users/1403070",
"pm_score": 5,
"selected": false,
"text": "<pre><code>IF OBJECT_ID('mytablename') IS NOT NULL \n</code></pre>\n"
},
{
"answer_id": 21635500,
"author": "Maslow",
"author_id": 57883,
"author_profile": "https://Stackoverflow.com/users/57883",
"pm_score": 0,
"selected": false,
"text": "<p>If anyone is trying to do this same thing in linq to sql (or especially linqpad) turn on option to include system tables and views and do this code:</p>\n\n<pre><code>let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema )\nwhere oSchema !=null\nlet o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null\nwhere o!=null\n</code></pre>\n\n<p>given that you have an object with the name in a property called item, and the schema in a property called schema where the source variable name is <code>a</code></p>\n"
},
{
"answer_id": 21685540,
"author": "MarceloMadnezz",
"author_id": 2611146,
"author_profile": "https://Stackoverflow.com/users/2611146",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select name from SysObjects where xType='U' and name like '%xxx%' order by name\n</code></pre>\n"
},
{
"answer_id": 24912436,
"author": "phil294",
"author_id": 3779853,
"author_profile": "https://Stackoverflow.com/users/3779853",
"pm_score": 2,
"selected": false,
"text": "<p>Something important to know for anybody who hasn't found their solution yet:\n<strong>SQL server != MYSQL</strong>.\nIf you want to do it with <strong>MYSQL</strong>, it is quite simple</p>\n\n<pre><code> $sql = \"SELECT 1 FROM `db_name`.`table_name` LIMIT 1;\";\n $result = mysql_query($sql);\n if( $result == false )\n echo \"table DOES NOT EXIST\";\n else\n echo \"table exists\";\n</code></pre>\n\n<p>Posting this here because it's the top hit at Google.</p>\n"
},
{
"answer_id": 25372822,
"author": "user3651072",
"author_id": 3651072,
"author_profile": "https://Stackoverflow.com/users/3651072",
"pm_score": -1,
"selected": false,
"text": "<p>If this is to be the 'ultimate' discussion, then it should be noted that Larry Leonard's script can query a remote server as well if the servers are linked.</p>\n\n<pre><code>if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')\n print 'Exists'\n</code></pre>\n"
},
{
"answer_id": 26996845,
"author": "Biniam Eyakem",
"author_id": 946931,
"author_profile": "https://Stackoverflow.com/users/946931",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this :</p>\n\n<pre><code> IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL \n BEGIN \n print 'deleted table';\n drop table t \n END\n else \n begin \n print 'table not found' \n end\n\n Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)\n insert into t( name, lastname) values('john','doe');\n insert into t( name, lastname) values('rose',NULL);\n\n Select * from t\n1 john doe\n2 rose NULL\n\n -- clean\n drop table t\n</code></pre>\n"
},
{
"answer_id": 27602349,
"author": "BrainCoder",
"author_id": 1245631,
"author_profile": "https://Stackoverflow.com/users/1245631",
"pm_score": 8,
"selected": false,
"text": "<p>Please see the below approaches,</p>\n\n<p><strong>Approach 1: Using INFORMATION_SCHEMA.TABLES view</strong></p>\n\n<p>We can write a query like below to check if a Customers Table exists in the current database.</p>\n\n<pre><code>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')\nBEGIN\n PRINT 'Table Exists'\nEND\n</code></pre>\n\n<p><strong>Approach 2: Using OBJECT_ID() function</strong></p>\n\n<p>We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.</p>\n\n<pre><code>IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL\nBEGIN\n PRINT 'Table Exists'\nEND\n</code></pre>\n\n<p><strong>Approach 3: Using sys.Objects Catalog View</strong></p>\n\n<p>We can use the Sys.Objects catalog view to check the existence of the Table as shown below:</p>\n\n<pre><code>IF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')\nBEGIN\n PRINT 'Table Exists'\nEND\n</code></pre>\n\n<p><strong>Approach 4: Using sys.Tables Catalog View</strong></p>\n\n<p>We can use the Sys.Tables catalog view to check the existence of the Table as shown below:</p>\n\n<pre><code> IF EXISTS(SELECT 1 FROM sys.Tables WHERE Name = N'Customers' AND Type = N'U')\n BEGIN\n PRINT 'Table Exists'\n END\n</code></pre>\n\n<p><strong>Approach 5: Avoid Using sys.sysobjects System table</strong></p>\n\n<p>We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.</p>\n\n<pre><code> IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')\n BEGIN\n PRINT 'Table Exists'\n END\n</code></pre>\n\n<p>referred from: <a href=\"http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/\" rel=\"noreferrer\">http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/</a></p>\n"
},
{
"answer_id": 28115618,
"author": "Marcello Miorelli",
"author_id": 1501497,
"author_profile": "https://Stackoverflow.com/users/1501497",
"pm_score": 3,
"selected": false,
"text": "<p>Just adding here, for the benefit of developers and fellow DBAs</p>\n\n<p>a script that receives @Tablename as a parameter </p>\n\n<p>(which may or may not contain the schemaname) and returns the info below if the schema.table exists:</p>\n\n<pre><code>the_name object_id the_schema the_table the_type\n[Facts].[FactBackOrder] 758293761 Facts FactBackOrder Table\n</code></pre>\n\n<p>I produced this script to be used inside other scripts every time I need to test whether or not a table or view exists, and when it does, get its object_id to be used for other purposes.</p>\n\n<p>It raises an error when either you passed an empty string, wrong schema name or wrong table name.</p>\n\n<p>this could be inside a procedure and return -1 for example.</p>\n\n<p>As an example, I have a table called \"Facts.FactBackOrder\" in one of my Data Warehouse databases.</p>\n\n<p>This is how I achieved this:</p>\n\n<pre><code>PRINT 'THE SERVER IS ' + @@SERVERNAME\n--select db_name()\nPRINT 'THE DATABASE IS ' + db_NAME() \nPRINT ''\nGO\n\nSET NOCOUNT ON\nGO\n\n--===================================================================================\n-- @TableName is the parameter\n-- the object we want to deal with (it might be an indexed view or a table)\n-- the schema might or might not be specified\n-- when not specified it is DBO\n--===================================================================================\n\nDECLARE @TableName SYSNAME\n\nSELECT @TableName = 'Facts.FactBackOrder'\n--===================================================================================\n--===================================================================================\nDECLARE @Schema SYSNAME\nDECLARE @I INT\nDECLARE @Z INT \n\nSELECT @TableName = LTRIM(RTRIM(@TableName))\nSELECT @Z = LEN(@TableName)\n\nIF (@Z = 0) BEGIN\n\n RAISERROR('Invalid @Tablename passed.',16,1)\n\nEND \n\nSELECT @I = CHARINDEX('.',@TableName )\n--SELECT @TableName ,@I\n\nIF @I > 0 BEGIN\n\n --===================================================================================\n -- a schema and table name have been passed\n -- example Facts.FactBackOrder \n -- @Schema = Fact\n -- @TableName = FactBackOrder\n --===================================================================================\n\n SELECT @Schema = SUBSTRING(@TABLENAME,1,@I-1)\n SELECT @TableName = SUBSTRING(@TABLENAME,@I+1,@Z-@I)\n\n\n\nEND\nELSE BEGIN\n\n --===================================================================================\n -- just a table name have been passed\n -- so the schema will be dbo\n -- example Orders\n -- @Schema = dbo\n -- @TableName = Orders\n --===================================================================================\n\n SELECT @Schema = 'DBO' \n\n\nEND\n\n --===================================================================================\n -- Check whether the @SchemaName is valid in the current database\n --===================================================================================\n\nIF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.SCHEMATA K WHERE K.[SCHEMA_NAME] = @Schema ) BEGIN\n\n RAISERROR('Invalid Schema Name.',16,1)\n\nEND \n\n--SELECT @Schema as [@Schema]\n-- ,@TableName as [@TableName]\n\n\nDECLARE @R1 TABLE (\n\n THE_NAME SYSNAME\n ,THE_SCHEMA SYSNAME\n ,THE_TABLE SYSNAME\n ,OBJECT_ID INT\n ,THE_TYPE SYSNAME\n ,PRIMARY KEY CLUSTERED (THE_SCHEMA,THE_NAME)\n\n)\n\n;WITH RADHE_01 AS (\nSELECT QUOTENAME(SCHEMA_NAME(O.schema_id)) + '.' + QUOTENAME(O.NAME) AS [the_name]\n ,the_schema=SCHEMA_NAME(O.schema_id)\n ,the_table=O.NAME\n ,object_id =o.object_id \n ,[the_type]= CASE WHEN O.TYPE = 'U' THEN 'Table' ELSE 'View' END \nfrom sys.objects O\nwhere O.is_ms_shipped = 0\nAND O.TYPE IN ('U','V')\n)\nINSERT INTO @R1 (\n THE_NAME \n ,THE_SCHEMA \n ,THE_TABLE \n ,OBJECT_ID\n ,THE_TYPE \n)\nSELECT the_name\n ,the_schema\n ,the_table\n ,object_id\n ,the_type\nFROM RADHE_01\nWHERE the_schema = @Schema \n AND the_table = @TableName\n\nIF (@@ROWCOUNT = 0) BEGIN \n\n RAISERROR('Invalid Table Name.',16,1)\n\nEND \nELSE BEGIN\n\n SELECT THE_NAME \n ,THE_SCHEMA \n ,THE_TABLE \n ,OBJECT_ID\n ,THE_TYPE \n\n FROM @R1\n\nEND \n</code></pre>\n"
},
{
"answer_id": 29676582,
"author": "dipi evil",
"author_id": 1016406,
"author_profile": "https://Stackoverflow.com/users/1016406",
"pm_score": 3,
"selected": false,
"text": "<p>In <strong>SQL Server 2000</strong> you can try:</p>\n\n<pre><code>IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')\nBEGIN\n SELECT 1 AS 'res' \nEND\n</code></pre>\n"
},
{
"answer_id": 37974532,
"author": "John Smith",
"author_id": 3739391,
"author_profile": "https://Stackoverflow.com/users/3739391",
"pm_score": 5,
"selected": false,
"text": "<p>Just wanted to mention one situation where it would probably be a little easier to use the <code>OBJECT_ID</code> method. The <code>INFORMATION_SCHEMA</code> views are objects under each database-</p>\n\n<blockquote>\n <p>The information schema views are defined in a special schema named\n INFORMATION_SCHEMA. This schema is contained in each database.</p>\n</blockquote>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms186778.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/ms186778.aspx</a></p>\n\n<p>Therefore all tables you access using </p>\n\n<pre><code>IF EXISTS (SELECT 1 \n FROM [database].INFORMATION_SCHEMA.TABLES \n WHERE TABLE_TYPE='BASE TABLE' \n AND TABLE_NAME='mytablename') \n SELECT 1 AS res ELSE SELECT 0 AS res;\n</code></pre>\n\n<p>will only reflect what is in <code>[database]</code>. If you wanted to check if tables in <em>another</em> database exist, without dynamically changing the <code>[database]</code> each time, <code>OBJECT_ID</code> will let you do this out of the box. Ex-</p>\n\n<pre><code>IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL \n SELECT 1 AS res ELSE SELECT 0 AS res;\n</code></pre>\n\n<p>works just as well as</p>\n\n<pre><code>IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL \n SELECT 1 AS res ELSE SELECT 0 AS res;\n</code></pre>\n\n<p><strong>SQL SERVER 2016 Edit</strong>:</p>\n\n<p>Starting with 2016, Microsoft simplified the ability to check for non-existent objects prior to dropping, by adding the <code>if exists</code> keywords to <code>drop</code> statements. For example,</p>\n\n<pre><code>drop table if exists mytablename\n</code></pre>\n\n<p>will do the same thing as <code>OBJECT_ID</code> / <code>INFORMATION_SCHEMA</code> wrappers, in 1 line of code.</p>\n\n<p><a href=\"https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/\" rel=\"noreferrer\">https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/</a></p>\n"
},
{
"answer_id": 46071815,
"author": "Mathieu Dierckx",
"author_id": 4300486,
"author_profile": "https://Stackoverflow.com/users/4300486",
"pm_score": 0,
"selected": false,
"text": "<hr>\n\n<p>-- -- create procedure to check if a table exists </p>\n\n<hr>\n\n<pre><code>DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `checkIfTableExists`;\n\nCREATE PROCEDURE checkIfTableExists(\n IN databaseName CHAR(255),\n IN tableName CHAR(255),\n OUT boolExistsOrNot CHAR(40)\n)\n\n BEGIN\n SELECT count(*) INTO boolExistsOrNot FROM information_schema.TABLES\n WHERE (TABLE_SCHEMA = databaseName)\n AND (TABLE_NAME = tableName);\n END $$\n\nDELIMITER ;\n</code></pre>\n\n<hr>\n\n<p>-- -- how to use : check if table migrations exists </p>\n\n<hr>\n\n<pre><code> CALL checkIfTableExists('muDbName', 'migrations', @output);\n</code></pre>\n"
},
{
"answer_id": 50924306,
"author": "Krishnaraj Barvathaya",
"author_id": 84979,
"author_profile": "https://Stackoverflow.com/users/84979",
"pm_score": 1,
"selected": false,
"text": "<pre><code>IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.TableName') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 )\nBEGIN\n SELECT * FROM dbo.TableName;\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 55293422,
"author": "Michael Quad",
"author_id": 7128889,
"author_profile": "https://Stackoverflow.com/users/7128889",
"pm_score": 2,
"selected": false,
"text": "<p>I've had some problems either with selecting from INFORMATIONAL_SCHEME and OBJECT_ID. I don't know if it's an issue of ODBC driver or something.. Queries from SQL management studio, both, were okay.</p>\n\n<p>Here is the solution:</p>\n\n<pre><code>SELECT COUNT(*) FROM <yourTableNameHere>\n</code></pre>\n\n<p>So, if the query fails, there is, probably, no such table in the database (or you don't have access permissions to it).</p>\n\n<p>The check is done by comparing the value (integer in my case) returned by SQL executor which deals with ODBC driver..</p>\n\n<pre><code>if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {\n // myTable doesn't exist..\n}\n</code></pre>\n"
},
{
"answer_id": 56361971,
"author": "S Krishna",
"author_id": 5850848,
"author_profile": "https://Stackoverflow.com/users/5850848",
"pm_score": -1,
"selected": false,
"text": "<p>Run this query to check if the table exists in the database:</p>\n\n<pre><code>IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL\nPRINT 'Table Exists';\n</code></pre>\n"
},
{
"answer_id": 56867605,
"author": "Mohammad Reza Shahrestani",
"author_id": 6174449,
"author_profile": "https://Stackoverflow.com/users/6174449",
"pm_score": 2,
"selected": false,
"text": "<pre><code>IF EXISTS (\nSELECT *\nFROM INFORMATION_SCHEMA.TABLES\nWHERE \nTABLE_CATALOG = 'Database Name' and\nTABLE_NAME = 'Table Name' and \nTABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted\n\nBEGIN\n--TABLE EXISTS\nEND\n\nELSE BEGIN\n--TABLE DOES NOT EXISTS\nEND\n</code></pre>\n"
},
{
"answer_id": 57941500,
"author": "Reza Jenabi",
"author_id": 9549856,
"author_profile": "https://Stackoverflow.com/users/9549856",
"pm_score": 4,
"selected": false,
"text": "<p>You can use below code</p>\n\n<pre><code>IF (OBJECT_ID('TableName') IS NOT NULL )\nBEGIN\n PRINT 'Table Exists'\nEND\nELSE\nBEGIN \n PRINT 'Table NOT Exists'\nEND\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName'))\nBEGIN\n PRINT 'Table Exists'\nEND\nELSE\nBEGIN \n PRINT 'Table NOT Exists'\nEND\n</code></pre>\n"
},
{
"answer_id": 59608790,
"author": "Kelum Sampath Edirisinghe",
"author_id": 9976255,
"author_profile": "https://Stackoverflow.com/users/9976255",
"pm_score": 0,
"selected": false,
"text": "<p>i taking here <strong>creating a view as example</strong>.</p>\n\n<p>Because ALTER/CREATE commands can't be within BEGIN/END blocks. You need to test for existence and the drop it before doing a create</p>\n\n<pre><code>IF Object_ID('TestView') IS NOT NULL\nDROP VIEW TestView\n\nGO\n\nCREATE VIEW TestView\n as\n . . .\n\nGO\n</code></pre>\n\n<p>If you are woried about the permissions being lost you can script the GRANT statements as well and re-run those at the end.</p>\n\n<p>You could wrap the create/alter into a string and do an EXEC - that might get ugly for large views</p>\n\n<pre><code>DECLARE @SQL as varchar(4000)\n\n-- set to body of view\nSET @SQL = 'SELECT X, Y, Z FROM TABLE' \n\nIF Object_ID('TestView') IS NULL\n SET @SQL = 'CREATE VIEW TestView AS ' + @SQL\nELSE \n SET @SQL = 'ALTER VIEW TestView AS ' + @SQL\n</code></pre>\n"
},
{
"answer_id": 60426669,
"author": "Jitan Gupta",
"author_id": 8178474,
"author_profile": "https://Stackoverflow.com/users/8178474",
"pm_score": 1,
"selected": false,
"text": "<p>There is one more option to check if the table exists across databases</p>\n\n<pre><code>IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name')\nBEGIN\n -- do whatever you want\nEND\n</code></pre>\n"
},
{
"answer_id": 73935575,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I think the following query works:</p>\n<pre><code>IF EXISTS (select * from sys.tables \nWHERE name='mytablename' )\nBEGIN\n print 'table exists in the database'\nEND\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] |
I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.
Here are two possible ways of doing it. Which one is the standard/best way of doing it?
First way:
```
IF EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='mytablename')
SELECT 1 AS res ELSE SELECT 0 AS res;
```
Second way:
```
IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL
SELECT 1 AS res ELSE SELECT 0 AS res;
```
**MySQL** provides the simple
```
SHOW TABLES LIKE '%tablename%';
```
statement. I am looking for something similar.
|
For queries like this it is always best to use an `INFORMATION_SCHEMA` view. These views are (mostly) standard across many different databases and rarely change from version to version.
To check if a table exists use:
```
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
```
|
167,577 |
<p>I am working on a project that requires reliable access to historic feed entries which are not necessarily available in the current feed of the website. I have found several ways to access such data, but none of them give me all the characteristics I need.</p>
<p>Look at this as a brainstorm. I will tell you how much I have found and you can contribute if you have any other ideas.</p>
<ol>
<li><p><a href="http://code.google.com/apis/ajaxfeeds/" rel="nofollow noreferrer">Google AJAX Feed API</a> - will limit you to 250 items</p></li>
<li><p><a href="http://www.niallkennedy.com/blog/2005/12/google-reader-api.html" rel="nofollow noreferrer">Unofficial Google Reader API</a> - Perfect but unofficial and therefore unreliable (and perhaps quasi-illegal?). Also, the authentication seems to be tricky.</p></li>
<li><p><a href="http://spinn3r.com/" rel="nofollow noreferrer">Spinn3r</a> - Costs a lot of money</p></li>
<li><p>Spidering the <a href="http://www.archive.org" rel="nofollow noreferrer">internet archive</a> at the site of the feed - Lots of complexity, spotty coverage, only useful as a last resort</p></li>
<li><p><a href="http://www.niallkennedy.com/blog/2005/12/my-yahoo-feed-a.html" rel="nofollow noreferrer">Yahoo! Feed API</a> or <a href="http://developer.yahoo.com/search/boss/" rel="nofollow noreferrer">Yahoo! Search BOSS</a> - The first looks more like an aggregator, meaning I'd need a different registration for each feed and the second should give more access to Yahoo's data but I can find no mention of feeds.</p></li>
<li><p>(thanks to Lou Franco) <a href="http://www.bloglines.com/services/api/sync" rel="nofollow noreferrer">Bloglines Sync API</a> - Besides the problem of needing an account and being designed more as an aggregator, it does not have a way to add feeds to the account. So no retrieval of arbitrary feeds. You need to manually add them through the reader first.</p></li>
<li><p>Other search engines/blog search/whatever?</p></li>
</ol>
<p>This is a really irritating problem as we are talking about semantic information that was once out there, is still (usually) valid, yet is difficult to access reliably, freely and without limits. Anybody know any alternative sources for feed entry goodness?</p>
|
[
{
"answer_id": 167599,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it. See Approach 1 in <a href=\"https://stackoverflow.com/a/27602349/270155\">this answer</a>.</p>\n"
},
{
"answer_id": 167610,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 8,
"selected": false,
"text": "<p>We always use the <code>OBJECT_ID</code> style for as long as I remember</p>\n\n<pre><code>IF OBJECT_ID('*objectName*', 'U') IS NOT NULL \n</code></pre>\n"
},
{
"answer_id": 167680,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 12,
"selected": true,
"text": "<p>For queries like this it is always best to use an <code>INFORMATION_SCHEMA</code> view. These views are (mostly) standard across many different databases and rarely change from version to version.</p>\n\n<p>To check if a table exists use:</p>\n\n<pre><code>IF (EXISTS (SELECT * \n FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_SCHEMA = 'TheSchema' \n AND TABLE_NAME = 'TheTable'))\nBEGIN\n --Do Stuff\nEND\n</code></pre>\n"
},
{
"answer_id": 1601406,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 3,
"selected": false,
"text": "<p>If you need to work on different databases:</p>\n\n<pre><code>DECLARE @Catalog VARCHAR(255)\nSET @Catalog = 'MyDatabase'\n\nDECLARE @Schema VARCHAR(255)\nSET @Schema = 'dbo'\n\nDECLARE @Table VARCHAR(255)\nSET @Table = 'MyTable'\n\nIF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_CATALOG = @Catalog \n AND TABLE_SCHEMA = @Schema \n AND TABLE_NAME = @Table))\nBEGIN\n --do stuff\nEND\n</code></pre>\n"
},
{
"answer_id": 2155299,
"author": "James Bloomer",
"author_id": 38249,
"author_profile": "https://Stackoverflow.com/users/38249",
"pm_score": 8,
"selected": false,
"text": "<p>Also note that if for any reason you need to check for a temporary table you can do this:</p>\n\n<pre><code>if OBJECT_ID('tempdb..#test') is not null\n --- temp table exists\n</code></pre>\n"
},
{
"answer_id": 4760619,
"author": "dko",
"author_id": 528537,
"author_profile": "https://Stackoverflow.com/users/528537",
"pm_score": 3,
"selected": false,
"text": "<p>I know it is an old question but I have found this possibility if you plan to call it often.</p>\n\n<pre><code>create procedure Table_Exists\n@tbl varchar(50)\nas\nreturn (select count(*) from sysobjects where type = 'U' and name = @tbl)\ngo\n</code></pre>\n"
},
{
"answer_id": 5579755,
"author": "dilip kumar singh",
"author_id": 696619,
"author_profile": "https://Stackoverflow.com/users/696619",
"pm_score": 4,
"selected": false,
"text": "<pre class=\"lang-sql prettyprint-override\"><code>IF EXISTS \n(\n SELECT * \n FROM sys.objects \n WHERE object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]') \n AND \n type in (N'U')\n)\nBEGIN\n\n -- Do whatever you need to here.\n\nEND\n</code></pre>\n\n<p>Here in the above code, the table name is <code>Mapping_APCToFANavigator</code>.</p>\n"
},
{
"answer_id": 9724871,
"author": "Larry Leonard",
"author_id": 1272181,
"author_profile": "https://Stackoverflow.com/users/1272181",
"pm_score": 5,
"selected": false,
"text": "<p>Looking for a table on a different database:</p>\n\n<pre><code>if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')\n print 'Exists'\n</code></pre>\n"
},
{
"answer_id": 15933669,
"author": "sumon",
"author_id": 2162651,
"author_profile": "https://Stackoverflow.com/users/2162651",
"pm_score": -1,
"selected": false,
"text": "<p>consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1. \nTo do this open visual studio and do the following:</p>\n\n<p>Right click on t1, then Script table as, then DROP and Create To, then New Query Editor </p>\n\n<p>you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one. </p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 19564163,
"author": "Moccassin",
"author_id": 2854813,
"author_profile": "https://Stackoverflow.com/users/2854813",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-sql prettyprint-override\"><code>IF EXISTS \n(\n SELECT * \n\n FROM INFORMATION_SCHEMA.TABLES \n\n WHERE TABLE_SCHEMA = 'PutSchemaHere' \n AND \n TABLE_NAME = 'PutTableNameHere'\n)\n</code></pre>\n"
},
{
"answer_id": 20141958,
"author": "sansalk",
"author_id": 1403070,
"author_profile": "https://Stackoverflow.com/users/1403070",
"pm_score": 5,
"selected": false,
"text": "<pre><code>IF OBJECT_ID('mytablename') IS NOT NULL \n</code></pre>\n"
},
{
"answer_id": 21635500,
"author": "Maslow",
"author_id": 57883,
"author_profile": "https://Stackoverflow.com/users/57883",
"pm_score": 0,
"selected": false,
"text": "<p>If anyone is trying to do this same thing in linq to sql (or especially linqpad) turn on option to include system tables and views and do this code:</p>\n\n<pre><code>let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema )\nwhere oSchema !=null\nlet o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null\nwhere o!=null\n</code></pre>\n\n<p>given that you have an object with the name in a property called item, and the schema in a property called schema where the source variable name is <code>a</code></p>\n"
},
{
"answer_id": 21685540,
"author": "MarceloMadnezz",
"author_id": 2611146,
"author_profile": "https://Stackoverflow.com/users/2611146",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select name from SysObjects where xType='U' and name like '%xxx%' order by name\n</code></pre>\n"
},
{
"answer_id": 24912436,
"author": "phil294",
"author_id": 3779853,
"author_profile": "https://Stackoverflow.com/users/3779853",
"pm_score": 2,
"selected": false,
"text": "<p>Something important to know for anybody who hasn't found their solution yet:\n<strong>SQL server != MYSQL</strong>.\nIf you want to do it with <strong>MYSQL</strong>, it is quite simple</p>\n\n<pre><code> $sql = \"SELECT 1 FROM `db_name`.`table_name` LIMIT 1;\";\n $result = mysql_query($sql);\n if( $result == false )\n echo \"table DOES NOT EXIST\";\n else\n echo \"table exists\";\n</code></pre>\n\n<p>Posting this here because it's the top hit at Google.</p>\n"
},
{
"answer_id": 25372822,
"author": "user3651072",
"author_id": 3651072,
"author_profile": "https://Stackoverflow.com/users/3651072",
"pm_score": -1,
"selected": false,
"text": "<p>If this is to be the 'ultimate' discussion, then it should be noted that Larry Leonard's script can query a remote server as well if the servers are linked.</p>\n\n<pre><code>if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')\n print 'Exists'\n</code></pre>\n"
},
{
"answer_id": 26996845,
"author": "Biniam Eyakem",
"author_id": 946931,
"author_profile": "https://Stackoverflow.com/users/946931",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this :</p>\n\n<pre><code> IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL \n BEGIN \n print 'deleted table';\n drop table t \n END\n else \n begin \n print 'table not found' \n end\n\n Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)\n insert into t( name, lastname) values('john','doe');\n insert into t( name, lastname) values('rose',NULL);\n\n Select * from t\n1 john doe\n2 rose NULL\n\n -- clean\n drop table t\n</code></pre>\n"
},
{
"answer_id": 27602349,
"author": "BrainCoder",
"author_id": 1245631,
"author_profile": "https://Stackoverflow.com/users/1245631",
"pm_score": 8,
"selected": false,
"text": "<p>Please see the below approaches,</p>\n\n<p><strong>Approach 1: Using INFORMATION_SCHEMA.TABLES view</strong></p>\n\n<p>We can write a query like below to check if a Customers Table exists in the current database.</p>\n\n<pre><code>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')\nBEGIN\n PRINT 'Table Exists'\nEND\n</code></pre>\n\n<p><strong>Approach 2: Using OBJECT_ID() function</strong></p>\n\n<p>We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.</p>\n\n<pre><code>IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL\nBEGIN\n PRINT 'Table Exists'\nEND\n</code></pre>\n\n<p><strong>Approach 3: Using sys.Objects Catalog View</strong></p>\n\n<p>We can use the Sys.Objects catalog view to check the existence of the Table as shown below:</p>\n\n<pre><code>IF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')\nBEGIN\n PRINT 'Table Exists'\nEND\n</code></pre>\n\n<p><strong>Approach 4: Using sys.Tables Catalog View</strong></p>\n\n<p>We can use the Sys.Tables catalog view to check the existence of the Table as shown below:</p>\n\n<pre><code> IF EXISTS(SELECT 1 FROM sys.Tables WHERE Name = N'Customers' AND Type = N'U')\n BEGIN\n PRINT 'Table Exists'\n END\n</code></pre>\n\n<p><strong>Approach 5: Avoid Using sys.sysobjects System table</strong></p>\n\n<p>We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.</p>\n\n<pre><code> IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')\n BEGIN\n PRINT 'Table Exists'\n END\n</code></pre>\n\n<p>referred from: <a href=\"http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/\" rel=\"noreferrer\">http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/</a></p>\n"
},
{
"answer_id": 28115618,
"author": "Marcello Miorelli",
"author_id": 1501497,
"author_profile": "https://Stackoverflow.com/users/1501497",
"pm_score": 3,
"selected": false,
"text": "<p>Just adding here, for the benefit of developers and fellow DBAs</p>\n\n<p>a script that receives @Tablename as a parameter </p>\n\n<p>(which may or may not contain the schemaname) and returns the info below if the schema.table exists:</p>\n\n<pre><code>the_name object_id the_schema the_table the_type\n[Facts].[FactBackOrder] 758293761 Facts FactBackOrder Table\n</code></pre>\n\n<p>I produced this script to be used inside other scripts every time I need to test whether or not a table or view exists, and when it does, get its object_id to be used for other purposes.</p>\n\n<p>It raises an error when either you passed an empty string, wrong schema name or wrong table name.</p>\n\n<p>this could be inside a procedure and return -1 for example.</p>\n\n<p>As an example, I have a table called \"Facts.FactBackOrder\" in one of my Data Warehouse databases.</p>\n\n<p>This is how I achieved this:</p>\n\n<pre><code>PRINT 'THE SERVER IS ' + @@SERVERNAME\n--select db_name()\nPRINT 'THE DATABASE IS ' + db_NAME() \nPRINT ''\nGO\n\nSET NOCOUNT ON\nGO\n\n--===================================================================================\n-- @TableName is the parameter\n-- the object we want to deal with (it might be an indexed view or a table)\n-- the schema might or might not be specified\n-- when not specified it is DBO\n--===================================================================================\n\nDECLARE @TableName SYSNAME\n\nSELECT @TableName = 'Facts.FactBackOrder'\n--===================================================================================\n--===================================================================================\nDECLARE @Schema SYSNAME\nDECLARE @I INT\nDECLARE @Z INT \n\nSELECT @TableName = LTRIM(RTRIM(@TableName))\nSELECT @Z = LEN(@TableName)\n\nIF (@Z = 0) BEGIN\n\n RAISERROR('Invalid @Tablename passed.',16,1)\n\nEND \n\nSELECT @I = CHARINDEX('.',@TableName )\n--SELECT @TableName ,@I\n\nIF @I > 0 BEGIN\n\n --===================================================================================\n -- a schema and table name have been passed\n -- example Facts.FactBackOrder \n -- @Schema = Fact\n -- @TableName = FactBackOrder\n --===================================================================================\n\n SELECT @Schema = SUBSTRING(@TABLENAME,1,@I-1)\n SELECT @TableName = SUBSTRING(@TABLENAME,@I+1,@Z-@I)\n\n\n\nEND\nELSE BEGIN\n\n --===================================================================================\n -- just a table name have been passed\n -- so the schema will be dbo\n -- example Orders\n -- @Schema = dbo\n -- @TableName = Orders\n --===================================================================================\n\n SELECT @Schema = 'DBO' \n\n\nEND\n\n --===================================================================================\n -- Check whether the @SchemaName is valid in the current database\n --===================================================================================\n\nIF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.SCHEMATA K WHERE K.[SCHEMA_NAME] = @Schema ) BEGIN\n\n RAISERROR('Invalid Schema Name.',16,1)\n\nEND \n\n--SELECT @Schema as [@Schema]\n-- ,@TableName as [@TableName]\n\n\nDECLARE @R1 TABLE (\n\n THE_NAME SYSNAME\n ,THE_SCHEMA SYSNAME\n ,THE_TABLE SYSNAME\n ,OBJECT_ID INT\n ,THE_TYPE SYSNAME\n ,PRIMARY KEY CLUSTERED (THE_SCHEMA,THE_NAME)\n\n)\n\n;WITH RADHE_01 AS (\nSELECT QUOTENAME(SCHEMA_NAME(O.schema_id)) + '.' + QUOTENAME(O.NAME) AS [the_name]\n ,the_schema=SCHEMA_NAME(O.schema_id)\n ,the_table=O.NAME\n ,object_id =o.object_id \n ,[the_type]= CASE WHEN O.TYPE = 'U' THEN 'Table' ELSE 'View' END \nfrom sys.objects O\nwhere O.is_ms_shipped = 0\nAND O.TYPE IN ('U','V')\n)\nINSERT INTO @R1 (\n THE_NAME \n ,THE_SCHEMA \n ,THE_TABLE \n ,OBJECT_ID\n ,THE_TYPE \n)\nSELECT the_name\n ,the_schema\n ,the_table\n ,object_id\n ,the_type\nFROM RADHE_01\nWHERE the_schema = @Schema \n AND the_table = @TableName\n\nIF (@@ROWCOUNT = 0) BEGIN \n\n RAISERROR('Invalid Table Name.',16,1)\n\nEND \nELSE BEGIN\n\n SELECT THE_NAME \n ,THE_SCHEMA \n ,THE_TABLE \n ,OBJECT_ID\n ,THE_TYPE \n\n FROM @R1\n\nEND \n</code></pre>\n"
},
{
"answer_id": 29676582,
"author": "dipi evil",
"author_id": 1016406,
"author_profile": "https://Stackoverflow.com/users/1016406",
"pm_score": 3,
"selected": false,
"text": "<p>In <strong>SQL Server 2000</strong> you can try:</p>\n\n<pre><code>IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')\nBEGIN\n SELECT 1 AS 'res' \nEND\n</code></pre>\n"
},
{
"answer_id": 37974532,
"author": "John Smith",
"author_id": 3739391,
"author_profile": "https://Stackoverflow.com/users/3739391",
"pm_score": 5,
"selected": false,
"text": "<p>Just wanted to mention one situation where it would probably be a little easier to use the <code>OBJECT_ID</code> method. The <code>INFORMATION_SCHEMA</code> views are objects under each database-</p>\n\n<blockquote>\n <p>The information schema views are defined in a special schema named\n INFORMATION_SCHEMA. This schema is contained in each database.</p>\n</blockquote>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms186778.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/ms186778.aspx</a></p>\n\n<p>Therefore all tables you access using </p>\n\n<pre><code>IF EXISTS (SELECT 1 \n FROM [database].INFORMATION_SCHEMA.TABLES \n WHERE TABLE_TYPE='BASE TABLE' \n AND TABLE_NAME='mytablename') \n SELECT 1 AS res ELSE SELECT 0 AS res;\n</code></pre>\n\n<p>will only reflect what is in <code>[database]</code>. If you wanted to check if tables in <em>another</em> database exist, without dynamically changing the <code>[database]</code> each time, <code>OBJECT_ID</code> will let you do this out of the box. Ex-</p>\n\n<pre><code>IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL \n SELECT 1 AS res ELSE SELECT 0 AS res;\n</code></pre>\n\n<p>works just as well as</p>\n\n<pre><code>IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL \n SELECT 1 AS res ELSE SELECT 0 AS res;\n</code></pre>\n\n<p><strong>SQL SERVER 2016 Edit</strong>:</p>\n\n<p>Starting with 2016, Microsoft simplified the ability to check for non-existent objects prior to dropping, by adding the <code>if exists</code> keywords to <code>drop</code> statements. For example,</p>\n\n<pre><code>drop table if exists mytablename\n</code></pre>\n\n<p>will do the same thing as <code>OBJECT_ID</code> / <code>INFORMATION_SCHEMA</code> wrappers, in 1 line of code.</p>\n\n<p><a href=\"https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/\" rel=\"noreferrer\">https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/</a></p>\n"
},
{
"answer_id": 46071815,
"author": "Mathieu Dierckx",
"author_id": 4300486,
"author_profile": "https://Stackoverflow.com/users/4300486",
"pm_score": 0,
"selected": false,
"text": "<hr>\n\n<p>-- -- create procedure to check if a table exists </p>\n\n<hr>\n\n<pre><code>DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `checkIfTableExists`;\n\nCREATE PROCEDURE checkIfTableExists(\n IN databaseName CHAR(255),\n IN tableName CHAR(255),\n OUT boolExistsOrNot CHAR(40)\n)\n\n BEGIN\n SELECT count(*) INTO boolExistsOrNot FROM information_schema.TABLES\n WHERE (TABLE_SCHEMA = databaseName)\n AND (TABLE_NAME = tableName);\n END $$\n\nDELIMITER ;\n</code></pre>\n\n<hr>\n\n<p>-- -- how to use : check if table migrations exists </p>\n\n<hr>\n\n<pre><code> CALL checkIfTableExists('muDbName', 'migrations', @output);\n</code></pre>\n"
},
{
"answer_id": 50924306,
"author": "Krishnaraj Barvathaya",
"author_id": 84979,
"author_profile": "https://Stackoverflow.com/users/84979",
"pm_score": 1,
"selected": false,
"text": "<pre><code>IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.TableName') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 )\nBEGIN\n SELECT * FROM dbo.TableName;\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 55293422,
"author": "Michael Quad",
"author_id": 7128889,
"author_profile": "https://Stackoverflow.com/users/7128889",
"pm_score": 2,
"selected": false,
"text": "<p>I've had some problems either with selecting from INFORMATIONAL_SCHEME and OBJECT_ID. I don't know if it's an issue of ODBC driver or something.. Queries from SQL management studio, both, were okay.</p>\n\n<p>Here is the solution:</p>\n\n<pre><code>SELECT COUNT(*) FROM <yourTableNameHere>\n</code></pre>\n\n<p>So, if the query fails, there is, probably, no such table in the database (or you don't have access permissions to it).</p>\n\n<p>The check is done by comparing the value (integer in my case) returned by SQL executor which deals with ODBC driver..</p>\n\n<pre><code>if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {\n // myTable doesn't exist..\n}\n</code></pre>\n"
},
{
"answer_id": 56361971,
"author": "S Krishna",
"author_id": 5850848,
"author_profile": "https://Stackoverflow.com/users/5850848",
"pm_score": -1,
"selected": false,
"text": "<p>Run this query to check if the table exists in the database:</p>\n\n<pre><code>IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL\nPRINT 'Table Exists';\n</code></pre>\n"
},
{
"answer_id": 56867605,
"author": "Mohammad Reza Shahrestani",
"author_id": 6174449,
"author_profile": "https://Stackoverflow.com/users/6174449",
"pm_score": 2,
"selected": false,
"text": "<pre><code>IF EXISTS (\nSELECT *\nFROM INFORMATION_SCHEMA.TABLES\nWHERE \nTABLE_CATALOG = 'Database Name' and\nTABLE_NAME = 'Table Name' and \nTABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted\n\nBEGIN\n--TABLE EXISTS\nEND\n\nELSE BEGIN\n--TABLE DOES NOT EXISTS\nEND\n</code></pre>\n"
},
{
"answer_id": 57941500,
"author": "Reza Jenabi",
"author_id": 9549856,
"author_profile": "https://Stackoverflow.com/users/9549856",
"pm_score": 4,
"selected": false,
"text": "<p>You can use below code</p>\n\n<pre><code>IF (OBJECT_ID('TableName') IS NOT NULL )\nBEGIN\n PRINT 'Table Exists'\nEND\nELSE\nBEGIN \n PRINT 'Table NOT Exists'\nEND\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName'))\nBEGIN\n PRINT 'Table Exists'\nEND\nELSE\nBEGIN \n PRINT 'Table NOT Exists'\nEND\n</code></pre>\n"
},
{
"answer_id": 59608790,
"author": "Kelum Sampath Edirisinghe",
"author_id": 9976255,
"author_profile": "https://Stackoverflow.com/users/9976255",
"pm_score": 0,
"selected": false,
"text": "<p>i taking here <strong>creating a view as example</strong>.</p>\n\n<p>Because ALTER/CREATE commands can't be within BEGIN/END blocks. You need to test for existence and the drop it before doing a create</p>\n\n<pre><code>IF Object_ID('TestView') IS NOT NULL\nDROP VIEW TestView\n\nGO\n\nCREATE VIEW TestView\n as\n . . .\n\nGO\n</code></pre>\n\n<p>If you are woried about the permissions being lost you can script the GRANT statements as well and re-run those at the end.</p>\n\n<p>You could wrap the create/alter into a string and do an EXEC - that might get ugly for large views</p>\n\n<pre><code>DECLARE @SQL as varchar(4000)\n\n-- set to body of view\nSET @SQL = 'SELECT X, Y, Z FROM TABLE' \n\nIF Object_ID('TestView') IS NULL\n SET @SQL = 'CREATE VIEW TestView AS ' + @SQL\nELSE \n SET @SQL = 'ALTER VIEW TestView AS ' + @SQL\n</code></pre>\n"
},
{
"answer_id": 60426669,
"author": "Jitan Gupta",
"author_id": 8178474,
"author_profile": "https://Stackoverflow.com/users/8178474",
"pm_score": 1,
"selected": false,
"text": "<p>There is one more option to check if the table exists across databases</p>\n\n<pre><code>IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name')\nBEGIN\n -- do whatever you want\nEND\n</code></pre>\n"
},
{
"answer_id": 73935575,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I think the following query works:</p>\n<pre><code>IF EXISTS (select * from sys.tables \nWHERE name='mytablename' )\nBEGIN\n print 'table exists in the database'\nEND\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24461/"
] |
I am working on a project that requires reliable access to historic feed entries which are not necessarily available in the current feed of the website. I have found several ways to access such data, but none of them give me all the characteristics I need.
Look at this as a brainstorm. I will tell you how much I have found and you can contribute if you have any other ideas.
1. [Google AJAX Feed API](http://code.google.com/apis/ajaxfeeds/) - will limit you to 250 items
2. [Unofficial Google Reader API](http://www.niallkennedy.com/blog/2005/12/google-reader-api.html) - Perfect but unofficial and therefore unreliable (and perhaps quasi-illegal?). Also, the authentication seems to be tricky.
3. [Spinn3r](http://spinn3r.com/) - Costs a lot of money
4. Spidering the [internet archive](http://www.archive.org) at the site of the feed - Lots of complexity, spotty coverage, only useful as a last resort
5. [Yahoo! Feed API](http://www.niallkennedy.com/blog/2005/12/my-yahoo-feed-a.html) or [Yahoo! Search BOSS](http://developer.yahoo.com/search/boss/) - The first looks more like an aggregator, meaning I'd need a different registration for each feed and the second should give more access to Yahoo's data but I can find no mention of feeds.
6. (thanks to Lou Franco) [Bloglines Sync API](http://www.bloglines.com/services/api/sync) - Besides the problem of needing an account and being designed more as an aggregator, it does not have a way to add feeds to the account. So no retrieval of arbitrary feeds. You need to manually add them through the reader first.
7. Other search engines/blog search/whatever?
This is a really irritating problem as we are talking about semantic information that was once out there, is still (usually) valid, yet is difficult to access reliably, freely and without limits. Anybody know any alternative sources for feed entry goodness?
|
For queries like this it is always best to use an `INFORMATION_SCHEMA` view. These views are (mostly) standard across many different databases and rarely change from version to version.
To check if a table exists use:
```
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
```
|
167,587 |
<p>I'm trying to load assemblies in a separate app domain, but am running into a very strange problem. Here's some code:</p>
<pre><code> public static void LoadAssembly(string assemblyPath)
{
string pathToDll = Assembly.GetCallingAssembly().CodeBase;
AppDomainSetup domainSetup = new AppDomainSetup
{
PrivateBinPath = pathToDll
};
AppDomain newDomain = AppDomain.CreateDomain("AssemblyLoader",null,domainSetup);
AssemblyLoader loader = (AssemblyLoader)newDomain.CreateInstanceFromAndUnwrap(
pathToDll,
typeof(AssemblyLoader).FullName);
}
</code></pre>
<p>AssemblyLoader is another class in the same assembly as this one, and it inherits from MarshalByRef, however for some strange reason, I get a cast exception every time I try to run this. I even hardcoded the path to the DLL instead of using GetCallingAssembly().CodeBase yet I keep getting this exception. </p>
<p>I understand it's hard to answer a question like this without actually seeing it and having more information, but maybe someone has run into a similar situation and would know the common "gotchas" and what I should look out for.</p>
<p>EDIT: The reason I don't want to load it directly is because this is just part of the code. The ultimate goal is that this class will have a method that load assemblies, gets their GUID and some other info about them and stores them in a database for a project I'm working on. Therefore, if I load this assembly in a separate app domain, I can load the others there too and then unload the app domain. No point in having all these assemblies loaded for the duration of the app, if I only need that data.</p>
|
[
{
"answer_id": 167658,
"author": "TheXenocide",
"author_id": 8543,
"author_profile": "https://Stackoverflow.com/users/8543",
"pm_score": 0,
"selected": false,
"text": "<p>I don't believe the PrivateBinPath configuration is necessary, beyond that you don't need to use the Path to the DLL, but rather the Assembly's fully qualified name for the first parameter; try:</p>\n\n<pre><code>AssemblyLoader loader = (AssemblyLoader)newDomain.CreateInstanceFromAndUnwrap(\n typeof(AssemblyLoader).Assembly.FullName,\n typeof(AssemblyLoader).FullName);\n</code></pre>\n"
},
{
"answer_id": 167766,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 2,
"selected": false,
"text": "<p><em>(EDIT: after reading the exception given, changing answer completely)</em></p>\n\n<p>It appears the problem is the CreateInstanceFromAndUnwrap call, which uses the LoadFrom semantics of 'pathToDll'. <a href=\"http://blogs.msdn.com/suzcook/archive/2003/05/29/choosing-a-binding-context.aspx#57147\" rel=\"nofollow noreferrer\">Suzanne Cook detailed the possible sticking point</a> on her blog where your original AppDomain tries to call Load(\"SomeAssembly, [...]\") as opposed to LoadFrom(\"pathToDll\") when trying to resolve the type in question. </p>\n\n<p>Her advice was to hook the AssemblyResolve event on the current domain to do the correct LoadFrom in order to get the type. A little bit of targetted googling brings up <a href=\"http://www.codeguru.com/forum/showpost.php?s=dc0b90f26601b3cca385d2c9fdaac2a4&p=1450762&postcount=5\" rel=\"nofollow noreferrer\">a possible solution to the problem</a> based on Suzanne's suggestion.</p>\n"
},
{
"answer_id": 939394,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "<p>There's a lot of good information for what you're trying to do here: <a href=\"https://stackoverflow.com/questions/225330/how-to-load-a-net-assembly-for-reflection-operations-and-subsequently-unload-it\">How to load a .NET assembly for reflection operations and subsequently unload it?</a></p>\n"
},
{
"answer_id": 1814842,
"author": "Jason D",
"author_id": 215962,
"author_profile": "https://Stackoverflow.com/users/215962",
"pm_score": 0,
"selected": false,
"text": "<p>Check out <a href=\"http://www.west-wind.com/WebLog/posts/601200.aspx\" rel=\"nofollow noreferrer\"> this article.</a> </p>\n\n<p>Using the code in that article I got a cross app-domain object. I abstracted things a bit with generics and have three assemblies. (i.e. 1 defining the interface, 1 defining the plugin implementation, and the main program which tells the generic what to load.) The original articles code is easy to follow.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15861/"
] |
I'm trying to load assemblies in a separate app domain, but am running into a very strange problem. Here's some code:
```
public static void LoadAssembly(string assemblyPath)
{
string pathToDll = Assembly.GetCallingAssembly().CodeBase;
AppDomainSetup domainSetup = new AppDomainSetup
{
PrivateBinPath = pathToDll
};
AppDomain newDomain = AppDomain.CreateDomain("AssemblyLoader",null,domainSetup);
AssemblyLoader loader = (AssemblyLoader)newDomain.CreateInstanceFromAndUnwrap(
pathToDll,
typeof(AssemblyLoader).FullName);
}
```
AssemblyLoader is another class in the same assembly as this one, and it inherits from MarshalByRef, however for some strange reason, I get a cast exception every time I try to run this. I even hardcoded the path to the DLL instead of using GetCallingAssembly().CodeBase yet I keep getting this exception.
I understand it's hard to answer a question like this without actually seeing it and having more information, but maybe someone has run into a similar situation and would know the common "gotchas" and what I should look out for.
EDIT: The reason I don't want to load it directly is because this is just part of the code. The ultimate goal is that this class will have a method that load assemblies, gets their GUID and some other info about them and stores them in a database for a project I'm working on. Therefore, if I load this assembly in a separate app domain, I can load the others there too and then unload the app domain. No point in having all these assemblies loaded for the duration of the app, if I only need that data.
|
*(EDIT: after reading the exception given, changing answer completely)*
It appears the problem is the CreateInstanceFromAndUnwrap call, which uses the LoadFrom semantics of 'pathToDll'. [Suzanne Cook detailed the possible sticking point](http://blogs.msdn.com/suzcook/archive/2003/05/29/choosing-a-binding-context.aspx#57147) on her blog where your original AppDomain tries to call Load("SomeAssembly, [...]") as opposed to LoadFrom("pathToDll") when trying to resolve the type in question.
Her advice was to hook the AssemblyResolve event on the current domain to do the correct LoadFrom in order to get the type. A little bit of targetted googling brings up [a possible solution to the problem](http://www.codeguru.com/forum/showpost.php?s=dc0b90f26601b3cca385d2c9fdaac2a4&p=1450762&postcount=5) based on Suzanne's suggestion.
|
167,602 |
<p>I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this:</p>
<pre><code> protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
</code></pre>
<p>If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away.</p>
|
[
{
"answer_id": 167621,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 3,
"selected": false,
"text": "<p>I believe in this case the code-generator honors your code. It should be safe to put it in the codebehind.</p>\n"
},
{
"answer_id": 167627,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 3,
"selected": false,
"text": "<p>In VS 2005 (and 2008) you can update the <code>Dispose</code> method and it will not get removed when you edit the control from the designer.</p>\n"
},
{
"answer_id": 167629,
"author": "Mark Heath",
"author_id": 7532,
"author_profile": "https://Stackoverflow.com/users/7532",
"pm_score": 2,
"selected": false,
"text": "<p>You can move it out from the .designer.cs file and into the main .cs file if you want. As has been said already, it won't be overwritten.</p>\n"
},
{
"answer_id": 167642,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 7,
"selected": true,
"text": "<p>In such a case I move the generated <code>Dispose</code> method to the main file and extend it. Visual Studio respects this.</p>\n\n<p>An other approach would be using a partial method (C# 3.0).</p>\n"
},
{
"answer_id": 330018,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>All <code>Component</code> classes implement a <code>Disposed</code> event. You can add an event handler for that event and clean up things in there.</p>\n\n<p>For example, in your <code>UserControl</code> you could add following method:</p>\n\n<pre><code>private void OnDispose(object sender, EventArgs e)\n{\n // do stuff on dispose\n}\n</code></pre>\n\n<p>And in constructor (or in <code>Load</code> event handler) add the following line:</p>\n\n<pre><code>Disposed += OnDispose;\n</code></pre>\n"
},
{
"answer_id": 776548,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You just need to overload the public void Dispose() method in the Component Class that the user control inherits.</p>\n\n<p>make sure you pass the call to the base method as well as doing your dispose functionally or you'll break the functionality unless you fully implement it</p>\n"
},
{
"answer_id": 10756557,
"author": "tridy.net",
"author_id": 1374435,
"author_profile": "https://Stackoverflow.com/users/1374435",
"pm_score": -1,
"selected": false,
"text": "<p>there is a Unloaded event for the UserControl that you can use to clean up,</p>\n"
},
{
"answer_id": 44513071,
"author": "dynamichael",
"author_id": 1148881,
"author_profile": "https://Stackoverflow.com/users/1148881",
"pm_score": 0,
"selected": false,
"text": "<p>I would think the cleanest way would be to have your control subscribe to its own Disposed() event and do your cleanup in there.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22252/"
] |
I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this:
```
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
```
If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away.
|
In such a case I move the generated `Dispose` method to the main file and extend it. Visual Studio respects this.
An other approach would be using a partial method (C# 3.0).
|
167,622 |
<p>What are the major difference between bindable LINQ and continuous LINQ?</p>
<p>•Bindable LINQ: www.codeplex.com/bindablelinq</p>
<p>•Continuous LINQ: www.codeplex.com/clinq</p>
<p>One more project was added basing on the provided feedback:</p>
<p>•Obtics: obtics.codeplex.com</p>
|
[
{
"answer_id": 174924,
"author": "KyleLanser",
"author_id": 12923,
"author_profile": "https://Stackoverflow.com/users/12923",
"pm_score": 6,
"selected": true,
"text": "<p>Their are 2 problems both these packages try to solve: Lack of a CollectionChanged event and Dynamic result sets. There is one additional problem bindable solves, additional automatic event triggers.</p>\n\n<hr>\n\n<p><strong>The First Problem</strong> both packages aim to solve is this: </p>\n\n<blockquote>\n <p>Objects returned by a LINQ query do\n not provide CollectionChanged events.</p>\n</blockquote>\n\n<p><strong>Continuous LINQ</strong> automatically does this to all queries, with no change:</p>\n\n<pre><code>from item in theSource select item ;\n</code></pre>\n\n<p><strong>Bindable LINQ</strong> does this when you add .asBindable to your query Source Object:</p>\n\n<pre><code>from item in theSource.AsBindable() select item ;\n</code></pre>\n\n<hr>\n\n<p><strong>The Second Problem</strong> both packages aim to solve is:</p>\n\n<blockquote>\n <p>Result sets returned from a LINQ Query\n are static.</p>\n</blockquote>\n\n<p>Normally when you do a LINQ Query your <em>result set</em> is unchanged until you do a new query. With these two packages, your <em>result set</em> is updated whenever the <em>source</em> is updated. (bad for performance, good for realtime updates) </p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>var theSource = new ContinuousCollection<Customer>();\nvar theResultSet = from item in theSource where item.Age > 25 select item;\n//theResultSet.Count would equal 0.\n</code></pre>\n\n<p>Because your using Bindable or Continuous LINQ, you could modify <em>theSource</em>, and <em>theResultSet</em> would automatically include the new item.</p>\n\n<pre><code>theSource.Add(new Customer(\"Bob\", \"Barker\" , 35, Gender.Male)); //Age == 35\n//theResultSet.Count would now equal 1.\n</code></pre>\n\n<hr>\n\n<p><strong>The Additional Problem</strong> Bindable LINQ offers: (Quoting directly from their own page)</p>\n\n<pre><code>contactsListBox.ItemsSource = from c in customers\n where c.Name.StartsWith(textBox1.Text)\n select c;\n</code></pre>\n\n<blockquote>\n <p>Bindable LINQ will detect that the\n query relies on the Text property of\n the TextBox object, textBox1. Since\n the TextBox is a WPF control, Bindable\n LINQ knows to subscribe to the\n TextChanged event on the control.</p>\n \n <p>The end result is that as the user\n types, the items in the query are\n re-evaluated and the changes appear on\n screen. No additional code is needed\n to handle events.</p>\n</blockquote>\n"
},
{
"answer_id": 360627,
"author": "viggity",
"author_id": 4572,
"author_profile": "https://Stackoverflow.com/users/4572",
"pm_score": 3,
"selected": false,
"text": "<p>Another thing to keep in mind, although BindableLinq requires the \".AsBindable()\" call in the LINQ statement, CLINQ requires that you use ContinuousCollection<T> instead of ObservableCollection<T>. After looking at both briefly, I think I'm going to go with bindable LINQ.</p>\n"
},
{
"answer_id": 512416,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Indeed; the main issue with Continuous LINQ is the inability to use any collection that implements the generic IEnumerable and INotifyCollectionChanged. Bindable LINQ has no problem with using custom collections implementing the two interfaces.</p>\n"
},
{
"answer_id": 606571,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>May I draw your attention to another codeplex project? It's called Obtics and deals with the same issues (<a href=\"http://obtics.codeplex.com\" rel=\"noreferrer\">http://obtics.codeplex.com</a>).</p>\n\n<p>It addresses both the first the second and the additional problem and takes reactivity to a very deep level (has a demonstration with a LINQ based raytracer).</p>\n\n<p>It claims full support for all LINQ statements an methods of the Enumerable class.</p>\n\n<p>It uses yet another mechanism to create live queries:</p>\n\n<pre><code>var theResultSet = ExpressionObserver.Execute(\n () => from item in theSource where item.Age > 25 select item\n).Cascade();\n</code></pre>\n"
},
{
"answer_id": 12163131,
"author": "Nestor",
"author_id": 122732,
"author_profile": "https://Stackoverflow.com/users/122732",
"pm_score": 1,
"selected": false,
"text": "<p>Use bindable LINQ, as it implements IDisposable, and therefore you can control when a query gets disposed. When you dispose it, all the subscriptions to INotifyPropertyChanged will unsubscribe.</p>\n\n<p>Continuous LINQ is supposed to solve this problem with weak events, but it doesn't work as far as I was able to test.</p>\n\n<p>Hmm... this seems to be a problem with bindable LINQ (the second assert fails):</p>\n\n<pre><code>var _source = CreateSource_6People(); //(David, 27), (Mark, 15), (Steve, 30), (Jordan, 43), (Shiva, 30), (Erb, 43)\nIBindable<int> bindable = _source.AsBindable().Sum(x => x.Age);\nvar agesSum = 27+15+30+43+30+43;\nAssert.AreEqual(agesSum, bindable.Current); //PASSES\n\n_source[0].Age += 1;\nAssert.AreEqual(agesSum + 1, bindable.Current); //FAILS... DISAPPOINTING\n</code></pre>\n"
},
{
"answer_id": 58950913,
"author": "Igor Buchelnikov",
"author_id": 2663791,
"author_profile": "https://Stackoverflow.com/users/2663791",
"pm_score": -1,
"selected": false,
"text": "<p>I think Bindable LINQ and continuous LINQ are about the same: they provides observing for changes in LINQ computation. Implementation and API provided may some differ. It seems my <a href=\"https://github.com/IgorBuchelnikov/ObservableComputations\" rel=\"nofollow noreferrer\">ObservableComputations</a> library covers functionality expected from Bindable LINQ and continuous LINQ and has no problems mentioned in <a href=\"https://stackoverflow.com/a/174924/2663791\">https://stackoverflow.com/a/174924/2663791</a>. That library works with <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged?view=netframework-4.8\" rel=\"nofollow noreferrer\">INotifyPropertyChanged</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.inotifycollectionchanged?view=netframework-4.8\" rel=\"nofollow noreferrer\">INotifyCollectionChanged</a> interfaces, that makes it possible to operate with <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.8\" rel=\"nofollow noreferrer\">ObservableCollection</a> direcly. \nUsing that library you can code like this:</p>\n\n\n\n<pre class=\"lang-C# prettyprint-override\"><code>using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Linq;\nusing IBCode.ObservableComputations;\n\nnamespace ObservableComputationsExamples\n{\n public class Order : INotifyPropertyChanged\n {\n public event PropertyChangedEventHandler PropertyChanged;\n\n public int Num {get; set;}\n\n private decimal _price;\n public decimal Price\n {\n get => _price;\n set\n {\n _price = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Price)));\n }\n }\n\n public Order(int num, decimal price)\n {\n Num = num;\n _price = price;\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n ObservableCollection<Order> orders = \n new ObservableCollection<Order>(new []\n {\n new Order(1, 15),\n new Order(2, 15),\n new Order(3, 25),\n new Order(4, 27),\n new Order(5, 30),\n new Order(6, 75),\n new Order(7, 80),\n });\n\n //********************************************\n // We start using ObservableComputations here!\n Filtering<Order> expensiveOrders = orders.Filtering(o => o.Price > 25); \n\n checkFiltering(orders, expensiveOrders); // Prints \"True\"\n\n expensiveOrders.CollectionChanged += (sender, eventArgs) =>\n {\n // see the changes (add, remove, replace, move, reset) here\n };\n\n // Start the changing...\n orders.Add(new Order(8, 30));\n orders.Add(new Order(9, 10));\n orders[0].Price = 60;\n orders[4].Price = 10;\n orders.Move(5, 1);\n orders[1] = new Order(10, 17);\n\n checkFiltering(orders, expensiveOrders); // Prints \"True\"\n\n Console.ReadLine();\n }\n\n static void checkFiltering(\n ObservableCollection<Order> orders, \n Filtering<Order> expensiveOrders)\n {\n Console.WriteLine(expensiveOrders.SequenceEqual(\n orders.Where(o => o.Price > 25)));\n }\n }\n}\n</code></pre>\n\n\n\n<p>Please, add <a href=\"https://github.com/IgorBuchelnikov/ObservableComputations\" rel=\"nofollow noreferrer\">ObservableComputations</a> library to the list in the question (after Obtics).</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19268/"
] |
What are the major difference between bindable LINQ and continuous LINQ?
•Bindable LINQ: www.codeplex.com/bindablelinq
•Continuous LINQ: www.codeplex.com/clinq
One more project was added basing on the provided feedback:
•Obtics: obtics.codeplex.com
|
Their are 2 problems both these packages try to solve: Lack of a CollectionChanged event and Dynamic result sets. There is one additional problem bindable solves, additional automatic event triggers.
---
**The First Problem** both packages aim to solve is this:
>
> Objects returned by a LINQ query do
> not provide CollectionChanged events.
>
>
>
**Continuous LINQ** automatically does this to all queries, with no change:
```
from item in theSource select item ;
```
**Bindable LINQ** does this when you add .asBindable to your query Source Object:
```
from item in theSource.AsBindable() select item ;
```
---
**The Second Problem** both packages aim to solve is:
>
> Result sets returned from a LINQ Query
> are static.
>
>
>
Normally when you do a LINQ Query your *result set* is unchanged until you do a new query. With these two packages, your *result set* is updated whenever the *source* is updated. (bad for performance, good for realtime updates)
**Example**
```
var theSource = new ContinuousCollection<Customer>();
var theResultSet = from item in theSource where item.Age > 25 select item;
//theResultSet.Count would equal 0.
```
Because your using Bindable or Continuous LINQ, you could modify *theSource*, and *theResultSet* would automatically include the new item.
```
theSource.Add(new Customer("Bob", "Barker" , 35, Gender.Male)); //Age == 35
//theResultSet.Count would now equal 1.
```
---
**The Additional Problem** Bindable LINQ offers: (Quoting directly from their own page)
```
contactsListBox.ItemsSource = from c in customers
where c.Name.StartsWith(textBox1.Text)
select c;
```
>
> Bindable LINQ will detect that the
> query relies on the Text property of
> the TextBox object, textBox1. Since
> the TextBox is a WPF control, Bindable
> LINQ knows to subscribe to the
> TextChanged event on the control.
>
>
> The end result is that as the user
> types, the items in the query are
> re-evaluated and the changes appear on
> screen. No additional code is needed
> to handle events.
>
>
>
|
167,628 |
<p>We are managing our development with Subversion over HTTPS, Bugzilla, and Mediawiki. Some of our developers have expressed an interest in migrating to Trac, so I have to evaluate what the cost of doing so would be. </p>
<p>For both the wiki and bugzilla, we would need to either migrate the existing data into Trac or a way to integrate with trac. Having two apps to create wiki pages or log bugs would not be acceptable. Also, currently each of these applications requires a separate sign on so we would need to map each of these accounts into Trac.</p>
<p>So know of any easy methods of importing or integrating these systems with Trac and/or a tutorial for doing so?</p>
|
[
{
"answer_id": 174924,
"author": "KyleLanser",
"author_id": 12923,
"author_profile": "https://Stackoverflow.com/users/12923",
"pm_score": 6,
"selected": true,
"text": "<p>Their are 2 problems both these packages try to solve: Lack of a CollectionChanged event and Dynamic result sets. There is one additional problem bindable solves, additional automatic event triggers.</p>\n\n<hr>\n\n<p><strong>The First Problem</strong> both packages aim to solve is this: </p>\n\n<blockquote>\n <p>Objects returned by a LINQ query do\n not provide CollectionChanged events.</p>\n</blockquote>\n\n<p><strong>Continuous LINQ</strong> automatically does this to all queries, with no change:</p>\n\n<pre><code>from item in theSource select item ;\n</code></pre>\n\n<p><strong>Bindable LINQ</strong> does this when you add .asBindable to your query Source Object:</p>\n\n<pre><code>from item in theSource.AsBindable() select item ;\n</code></pre>\n\n<hr>\n\n<p><strong>The Second Problem</strong> both packages aim to solve is:</p>\n\n<blockquote>\n <p>Result sets returned from a LINQ Query\n are static.</p>\n</blockquote>\n\n<p>Normally when you do a LINQ Query your <em>result set</em> is unchanged until you do a new query. With these two packages, your <em>result set</em> is updated whenever the <em>source</em> is updated. (bad for performance, good for realtime updates) </p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>var theSource = new ContinuousCollection<Customer>();\nvar theResultSet = from item in theSource where item.Age > 25 select item;\n//theResultSet.Count would equal 0.\n</code></pre>\n\n<p>Because your using Bindable or Continuous LINQ, you could modify <em>theSource</em>, and <em>theResultSet</em> would automatically include the new item.</p>\n\n<pre><code>theSource.Add(new Customer(\"Bob\", \"Barker\" , 35, Gender.Male)); //Age == 35\n//theResultSet.Count would now equal 1.\n</code></pre>\n\n<hr>\n\n<p><strong>The Additional Problem</strong> Bindable LINQ offers: (Quoting directly from their own page)</p>\n\n<pre><code>contactsListBox.ItemsSource = from c in customers\n where c.Name.StartsWith(textBox1.Text)\n select c;\n</code></pre>\n\n<blockquote>\n <p>Bindable LINQ will detect that the\n query relies on the Text property of\n the TextBox object, textBox1. Since\n the TextBox is a WPF control, Bindable\n LINQ knows to subscribe to the\n TextChanged event on the control.</p>\n \n <p>The end result is that as the user\n types, the items in the query are\n re-evaluated and the changes appear on\n screen. No additional code is needed\n to handle events.</p>\n</blockquote>\n"
},
{
"answer_id": 360627,
"author": "viggity",
"author_id": 4572,
"author_profile": "https://Stackoverflow.com/users/4572",
"pm_score": 3,
"selected": false,
"text": "<p>Another thing to keep in mind, although BindableLinq requires the \".AsBindable()\" call in the LINQ statement, CLINQ requires that you use ContinuousCollection<T> instead of ObservableCollection<T>. After looking at both briefly, I think I'm going to go with bindable LINQ.</p>\n"
},
{
"answer_id": 512416,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Indeed; the main issue with Continuous LINQ is the inability to use any collection that implements the generic IEnumerable and INotifyCollectionChanged. Bindable LINQ has no problem with using custom collections implementing the two interfaces.</p>\n"
},
{
"answer_id": 606571,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>May I draw your attention to another codeplex project? It's called Obtics and deals with the same issues (<a href=\"http://obtics.codeplex.com\" rel=\"noreferrer\">http://obtics.codeplex.com</a>).</p>\n\n<p>It addresses both the first the second and the additional problem and takes reactivity to a very deep level (has a demonstration with a LINQ based raytracer).</p>\n\n<p>It claims full support for all LINQ statements an methods of the Enumerable class.</p>\n\n<p>It uses yet another mechanism to create live queries:</p>\n\n<pre><code>var theResultSet = ExpressionObserver.Execute(\n () => from item in theSource where item.Age > 25 select item\n).Cascade();\n</code></pre>\n"
},
{
"answer_id": 12163131,
"author": "Nestor",
"author_id": 122732,
"author_profile": "https://Stackoverflow.com/users/122732",
"pm_score": 1,
"selected": false,
"text": "<p>Use bindable LINQ, as it implements IDisposable, and therefore you can control when a query gets disposed. When you dispose it, all the subscriptions to INotifyPropertyChanged will unsubscribe.</p>\n\n<p>Continuous LINQ is supposed to solve this problem with weak events, but it doesn't work as far as I was able to test.</p>\n\n<p>Hmm... this seems to be a problem with bindable LINQ (the second assert fails):</p>\n\n<pre><code>var _source = CreateSource_6People(); //(David, 27), (Mark, 15), (Steve, 30), (Jordan, 43), (Shiva, 30), (Erb, 43)\nIBindable<int> bindable = _source.AsBindable().Sum(x => x.Age);\nvar agesSum = 27+15+30+43+30+43;\nAssert.AreEqual(agesSum, bindable.Current); //PASSES\n\n_source[0].Age += 1;\nAssert.AreEqual(agesSum + 1, bindable.Current); //FAILS... DISAPPOINTING\n</code></pre>\n"
},
{
"answer_id": 58950913,
"author": "Igor Buchelnikov",
"author_id": 2663791,
"author_profile": "https://Stackoverflow.com/users/2663791",
"pm_score": -1,
"selected": false,
"text": "<p>I think Bindable LINQ and continuous LINQ are about the same: they provides observing for changes in LINQ computation. Implementation and API provided may some differ. It seems my <a href=\"https://github.com/IgorBuchelnikov/ObservableComputations\" rel=\"nofollow noreferrer\">ObservableComputations</a> library covers functionality expected from Bindable LINQ and continuous LINQ and has no problems mentioned in <a href=\"https://stackoverflow.com/a/174924/2663791\">https://stackoverflow.com/a/174924/2663791</a>. That library works with <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged?view=netframework-4.8\" rel=\"nofollow noreferrer\">INotifyPropertyChanged</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.inotifycollectionchanged?view=netframework-4.8\" rel=\"nofollow noreferrer\">INotifyCollectionChanged</a> interfaces, that makes it possible to operate with <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.8\" rel=\"nofollow noreferrer\">ObservableCollection</a> direcly. \nUsing that library you can code like this:</p>\n\n\n\n<pre class=\"lang-C# prettyprint-override\"><code>using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Linq;\nusing IBCode.ObservableComputations;\n\nnamespace ObservableComputationsExamples\n{\n public class Order : INotifyPropertyChanged\n {\n public event PropertyChangedEventHandler PropertyChanged;\n\n public int Num {get; set;}\n\n private decimal _price;\n public decimal Price\n {\n get => _price;\n set\n {\n _price = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Price)));\n }\n }\n\n public Order(int num, decimal price)\n {\n Num = num;\n _price = price;\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n ObservableCollection<Order> orders = \n new ObservableCollection<Order>(new []\n {\n new Order(1, 15),\n new Order(2, 15),\n new Order(3, 25),\n new Order(4, 27),\n new Order(5, 30),\n new Order(6, 75),\n new Order(7, 80),\n });\n\n //********************************************\n // We start using ObservableComputations here!\n Filtering<Order> expensiveOrders = orders.Filtering(o => o.Price > 25); \n\n checkFiltering(orders, expensiveOrders); // Prints \"True\"\n\n expensiveOrders.CollectionChanged += (sender, eventArgs) =>\n {\n // see the changes (add, remove, replace, move, reset) here\n };\n\n // Start the changing...\n orders.Add(new Order(8, 30));\n orders.Add(new Order(9, 10));\n orders[0].Price = 60;\n orders[4].Price = 10;\n orders.Move(5, 1);\n orders[1] = new Order(10, 17);\n\n checkFiltering(orders, expensiveOrders); // Prints \"True\"\n\n Console.ReadLine();\n }\n\n static void checkFiltering(\n ObservableCollection<Order> orders, \n Filtering<Order> expensiveOrders)\n {\n Console.WriteLine(expensiveOrders.SequenceEqual(\n orders.Where(o => o.Price > 25)));\n }\n }\n}\n</code></pre>\n\n\n\n<p>Please, add <a href=\"https://github.com/IgorBuchelnikov/ObservableComputations\" rel=\"nofollow noreferrer\">ObservableComputations</a> library to the list in the question (after Obtics).</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
We are managing our development with Subversion over HTTPS, Bugzilla, and Mediawiki. Some of our developers have expressed an interest in migrating to Trac, so I have to evaluate what the cost of doing so would be.
For both the wiki and bugzilla, we would need to either migrate the existing data into Trac or a way to integrate with trac. Having two apps to create wiki pages or log bugs would not be acceptable. Also, currently each of these applications requires a separate sign on so we would need to map each of these accounts into Trac.
So know of any easy methods of importing or integrating these systems with Trac and/or a tutorial for doing so?
|
Their are 2 problems both these packages try to solve: Lack of a CollectionChanged event and Dynamic result sets. There is one additional problem bindable solves, additional automatic event triggers.
---
**The First Problem** both packages aim to solve is this:
>
> Objects returned by a LINQ query do
> not provide CollectionChanged events.
>
>
>
**Continuous LINQ** automatically does this to all queries, with no change:
```
from item in theSource select item ;
```
**Bindable LINQ** does this when you add .asBindable to your query Source Object:
```
from item in theSource.AsBindable() select item ;
```
---
**The Second Problem** both packages aim to solve is:
>
> Result sets returned from a LINQ Query
> are static.
>
>
>
Normally when you do a LINQ Query your *result set* is unchanged until you do a new query. With these two packages, your *result set* is updated whenever the *source* is updated. (bad for performance, good for realtime updates)
**Example**
```
var theSource = new ContinuousCollection<Customer>();
var theResultSet = from item in theSource where item.Age > 25 select item;
//theResultSet.Count would equal 0.
```
Because your using Bindable or Continuous LINQ, you could modify *theSource*, and *theResultSet* would automatically include the new item.
```
theSource.Add(new Customer("Bob", "Barker" , 35, Gender.Male)); //Age == 35
//theResultSet.Count would now equal 1.
```
---
**The Additional Problem** Bindable LINQ offers: (Quoting directly from their own page)
```
contactsListBox.ItemsSource = from c in customers
where c.Name.StartsWith(textBox1.Text)
select c;
```
>
> Bindable LINQ will detect that the
> query relies on the Text property of
> the TextBox object, textBox1. Since
> the TextBox is a WPF control, Bindable
> LINQ knows to subscribe to the
> TextChanged event on the control.
>
>
> The end result is that as the user
> types, the items in the query are
> re-evaluated and the changes appear on
> screen. No additional code is needed
> to handle events.
>
>
>
|
167,657 |
<p>When IE8 is released, will the following code work to add a conditional stylesheet?</p>
<pre><code><!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="ie-8.0.css" />
<![endif]-->
</code></pre>
<p>I've read conflicting reports as to whether this works with the beta. I'm hoping someone can share their experience. Thanks.</p>
|
[
{
"answer_id": 167691,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "<p>It worked for me – both in quirks mode and in standards compliance mode. However, it does <em>not</em> work when switching to IE8 compatibility mode.</p>\n"
},
{
"answer_id": 168131,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 5,
"selected": false,
"text": "<p>One thing to note:</p>\n\n<p>It does work, <strong><em>BUT</em></strong> if you are loading the page/site <strong><em>local network (e.g. Intranet)</em></strong> it will load in <strong><em>IE7</em></strong> mode <strong><em>by default!</em></strong> (update - <a href=\"http://blogs.msdn.com/ie/archive/2008/12/03/compatibility-view-improvements-to-come-in-ie8.aspx#9180796\" rel=\"noreferrer\">localhost</a>[*] is a special case, that <strong>does</strong> render in standards mode)</p>\n\n<p>This goes against MSFT's original statement of going STANDARDS by default.</p>\n\n<p>e.g.</p>\n\n<pre><code>http://127.0.0.1/mysite/mypage.php <-- IE8 by default (updated!)\nhttp://localhost/mysite/mypage.php <-- IE8 by default (updated!)\nhttp://machinename/mysite/mypage.php <-- IE7 by default\nhttp://192.168.100.x/mysite/mypage.php <-- IE7 by default\nhttp://google.com/ <-- IE8 by default\n</code></pre>\n\n<p>[*] - Scott Dickens [MSFT] noted in a comment <a href=\"http://blogs.msdn.com/ie/archive/2008/12/03/compatibility-view-improvements-to-come-in-ie8.aspx#9180796\" rel=\"noreferrer\">here on the IE Blog</a> that localhost was a special scenario in the Intranet (often used to develop Internet sites) thus would render in Standards mode by default.</p>\n\n<p>To test what mode a page in IE8 is really rendering in, you can use check the developer tools or use this bookmarklet code (only works in IE8):</p>\n\n<pre><code>javascript:\nvar vMode=document.documentMode;\nvar rMode='IE5 Quirks Mode';\nif(vMode==8){\n rMode='IE8 Standards Mode';\n} else if(vMode==7){\n rMode='IE7 Strict Mode';\n}\nalert('Rendering in: '+rMode);\n</code></pre>\n"
},
{
"answer_id": 666541,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Tools/Compatability view settings</p>\n\n<p>uncheck them all</p>\n"
},
{
"answer_id": 1246566,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you for your help. I've discovered the solution, apparently the problem was having each style sheet use its own title attribute. Once I took the title off all but the main style sheet, no prob.</p>\n\n<p>This is a weird issue unique to IE8 - and although I've been told its supposed to work that way, something to do with \"Stylesheet Preference\" - it only serves to create problems since the solution requires you remove the title which could be helpful when scripting, etc - when you need to call the style sheet.</p>\n\n<p>In any case, not sure if this is a bug, or its supposed to be that way, but I hope Microsoft investigates further.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 1745086,
"author": "Sankho Mallik",
"author_id": 212416,
"author_profile": "https://Stackoverflow.com/users/212416",
"pm_score": 0,
"selected": false,
"text": "<p>Why even bother writing a separate stylesheet for IE8?</p>\n\n<p>If you've already debugged for IE7, you can force IE8 into compatibility mode, and thus display your code as though IE8 were IE7.</p>\n\n<p>All you gotta do is put this RIGHT BELOW the opening head tag. Anywhere else and it won't work.</p>\n\n<p>And then that's a half hour or so less work on average per project, no intense debugging for IE8 needed!</p>\n\n<p>Even Msn.com does this - kind of ironic, eh?</p>\n\n<p>Wrote a blog post about it recently: <a href=\"http://blog.sankhomallik.com/2009/11/16/stop-wasting-time-debugging-on-ie8-when-you-dont-have-to-or-get-ie8-to-behave-like-ie7/\" rel=\"nofollow noreferrer\">http://blog.sankhomallik.com/2009/11/16/stop-wasting-time-debugging-on-ie8-when-you-dont-have-to-or-get-ie8-to-behave-like-ie7/</a></p>\n"
},
{
"answer_id": 1777148,
"author": "Eze",
"author_id": 216278,
"author_profile": "https://Stackoverflow.com/users/216278",
"pm_score": 0,
"selected": false,
"text": "<p>IE8 renders pretty nice compared to IE7, I have stylesheets for IE6, IE7 and IE8; at first i thought conditional comments were not working for IE8 after a bit of experimentation i found some rules were not beeing applied by IE8 just because i needed to put the ancestor or parent class first, e.g. \ni had a class like </p>\n\n<p><code>.niceclass {some:properties;more:properties;}</code></p>\n\n<p>it worked <strong>only</strong> if i changed it for something like:</p>\n\n<p><code>.parentclass .niceclass {some:properties;more:properties;}</code> <strong>or</strong></p>\n\n<p><code>#parentselector .niceclass {some:properties;more:properties;}</code></p>\n\n<p>btw in my IE8-only css i have only one overriding rule, the rest is rendered almost like firefox, though thats not making me leave FF anyway!.</p>\n"
},
{
"answer_id": 1968690,
"author": "Carsten",
"author_id": 239495,
"author_profile": "https://Stackoverflow.com/users/239495",
"pm_score": 0,
"selected": false,
"text": "<p>For my part I wanted to use rounded borders using css. IE8 on Vista does not support such. And since the graphics were so that the rounded borders would show a nice rounded shadow as well, the page looked terrible in IE8.</p>\n\n<p>I tried using conditional comments, but to no avail, IE8 would not evaluate the if IE expression and thus would not include the external stylesheet.</p>\n\n<p>Then I had a look at putting it into quirks / compatiblity mode, however, this still did not work as the CSS hacks I had used did no longer work for the IE8.</p>\n\n<p>Last but least I found a working CSS hack that will render the page correctly when in compatibility mode.</p>\n\n<pre><code>* + html #test[id] { color:lime } \n</code></pre>\n\n<p>Now, I do not know if this works for IE7 or below, so you would have at least three\ndifferent hacks for each IE release you want to support, e.e.</p>\n\n<pre><code>* + html #test,\n html+body #test,\n * html body #test\n { color:lime }\n</code></pre>\n\n<p>I wonder what the next regression of the Internet Exploiter will behold for us.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13850/"
] |
When IE8 is released, will the following code work to add a conditional stylesheet?
```
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="ie-8.0.css" />
<![endif]-->
```
I've read conflicting reports as to whether this works with the beta. I'm hoping someone can share their experience. Thanks.
|
It worked for me – both in quirks mode and in standards compliance mode. However, it does *not* work when switching to IE8 compatibility mode.
|
167,667 |
<p>Some of my users are complaining about some odd errors my installers had after downloading them from my web server.</p>
<p>This are NSIS installer that when downloaded came crippled or incomplete (usually because of slow Internet connections), the message is very clear "The installer you are trying to use is corrupted or incomplete....." IN ENGLISH!! (Did I mention my users only speak Spanish?).</p>
<p>How do I change the language or create custom error messages?</p>
<p>I already create the installer in Spanish by using:</p>
<pre><code>; Language files
!insertmacro MUI_LANGUAGE "Spanish"
</code></pre>
<p>Any Idea?</p>
|
[
{
"answer_id": 167711,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't done an NSIS package since it was referred to as Super Pimp (great name). See if this helps:\n<a href=\"http://nsis.sourceforge.net/Adding_Language_strings_as_resources\" rel=\"nofollow noreferrer\">NSIS Language Table</a></p>\n"
},
{
"answer_id": 776453,
"author": "Anders",
"author_id": 3501,
"author_profile": "https://Stackoverflow.com/users/3501",
"pm_score": 2,
"selected": false,
"text": "<p>The CRC check runs before you/nsis can access the langstrings, so the only way to change this message is to recompile the source code.</p>\n\n<p>The message was changed several versions ago and now includes a URL to the NSIS wiki, one would think your users would be able to run a translator on that page</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7946/"
] |
Some of my users are complaining about some odd errors my installers had after downloading them from my web server.
This are NSIS installer that when downloaded came crippled or incomplete (usually because of slow Internet connections), the message is very clear "The installer you are trying to use is corrupted or incomplete....." IN ENGLISH!! (Did I mention my users only speak Spanish?).
How do I change the language or create custom error messages?
I already create the installer in Spanish by using:
```
; Language files
!insertmacro MUI_LANGUAGE "Spanish"
```
Any Idea?
|
The CRC check runs before you/nsis can access the langstrings, so the only way to change this message is to recompile the source code.
The message was changed several versions ago and now includes a URL to the NSIS wiki, one would think your users would be able to run a translator on that page
|
167,670 |
<p>I have a multi-column text file ( tab delimited ) that I use for localized text in my project. </p>
<p>I picked this format since it can easily be edited by anyone in most text editors (and excel too). </p>
<p>My makefile processes it into a bunch of defines and binary data for including directly into my app. </p>
<p>Do you know if SVN merge only does line by line merging or can it so sub-line merging too?</p>
<p>For example:</p>
<p>Original File ( untranslated ) contains:</p>
<pre><code>DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES *YES* *YES*
STRING_NO NO *NO* *NO*
</code></pre>
<p>Then the french tranlator updates it:</p>
<pre><code>DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES *YES* OUI
STRING_NO NO *NO* NON
</code></pre>
<p>Then the german tranlator updates it:</p>
<pre><code>DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES JA *YES*
STRING_NO NO NEIN *NO*
</code></pre>
<p>Then they both merge the results back int SVN, so will they overwrite each others changes or can it handle mulitple changes on a line?</p>
|
[
{
"answer_id": 167722,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 3,
"selected": true,
"text": "<p>It is line by line.</p>\n\n<ol>\n<li>The person who tries to commit later will get 'out of date' error, and when they try to update it, they will get a conflict in changed lines.</li>\n<li>Same with the merge. The one who merges later will have to sort out conflicts manually.</li>\n</ol>\n"
},
{
"answer_id": 174605,
"author": "Nate Green",
"author_id": 9231,
"author_profile": "https://Stackoverflow.com/users/9231",
"pm_score": 0,
"selected": false,
"text": "<p>SVN merge is line by line, so in the situation you outline, conflicts would be created and would have to be merged by hand. However, with decent merge tools, the translators themselves could probably handle this - the tools can show differences character by character.</p>\n\n<p><a href=\"http://tortoisesvn.tigris.org/\" rel=\"nofollow noreferrer\">TortoiseSVN</a> is the de facto Windows SVN client, which includes <a href=\"http://tortoisesvn.tigris.org/TortoiseMerge.html\" rel=\"nofollow noreferrer\">TortoiseMerge (screenshot)</a>.</p>\n\n<p>There are several merge tools in Linux, <a href=\"http://meld.sourceforge.net/\" rel=\"nofollow noreferrer\">Meld</a> being my current (gnome) favorite.</p>\n\n<p>There are also several <a href=\"https://stackoverflow.com/questions/899/best-subversion-client-for-mac-os#902\">Mac clients</a> that I'd expect to have this feature.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
I have a multi-column text file ( tab delimited ) that I use for localized text in my project.
I picked this format since it can easily be edited by anyone in most text editors (and excel too).
My makefile processes it into a bunch of defines and binary data for including directly into my app.
Do you know if SVN merge only does line by line merging or can it so sub-line merging too?
For example:
Original File ( untranslated ) contains:
```
DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES *YES* *YES*
STRING_NO NO *NO* *NO*
```
Then the french tranlator updates it:
```
DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES *YES* OUI
STRING_NO NO *NO* NON
```
Then the german tranlator updates it:
```
DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES JA *YES*
STRING_NO NO NEIN *NO*
```
Then they both merge the results back int SVN, so will they overwrite each others changes or can it handle mulitple changes on a line?
|
It is line by line.
1. The person who tries to commit later will get 'out of date' error, and when they try to update it, they will get a conflict in changed lines.
2. Same with the merge. The one who merges later will have to sort out conflicts manually.
|
167,697 |
<p>We're working with a semi-centralized git repository here where I work. Each developer has their own subtree in the central git repository, so it looks something like this:</p>
<pre>master
alice/branch1
alice/branch2
bob/branch1
michael/feature
release/1.0
release/1.1</pre>
<p>Working locally in my tree I have <code>topic/feature</code>, which corresponds to <code>michael/feature</code> in the central tree.</p>
<p>I've been using</p>
<pre><code>git push origin topic/feature:michael/feature
</code></pre>
<p>to push my changes to the remote tree. However, this is cumbersome and prone to mistakes (e.g. omitting the developer name, misspelling the feature name, etc.).</p>
<p>I'm looking for a cleaner way to do this. For instance, "<code>git push</code>". I suspect that setting a different remote with a modified fetch refspec will do it, but I'm not sure how exactly to do it. I'm also not sure how to modify my current branch definitions to use the different remote.</p>
<p>My current <code>.git/config</code> looks something like:</p>
<pre>[remote "origin"]
url = git://central/git/project
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "topic/feature"]
remote = origin
merge = refs/heads/michael/project</pre>
<p><strong>Edit:</strong> I'd also like to apply this to pulls/fetches. But does the <code>branch.<name>.merge</code> take care of that?</p>
<p>I'll continue to research this and post here if I find something, but I'm hoping to get some other good ideas.</p>
<p><strong>Edit 2:</strong> I've decided I'll keep local and remote branch names the same. It appears it will be the least work and least prone to future problems.</p>
|
[
{
"answer_id": 169110,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 2,
"selected": false,
"text": "<p>In your [remote \"origin\"] section, add one line per mapping. Including master to master.</p>\n\n<pre><code>push = refs/heads/master:master\npush = refs/heads/topic/feature:michael/feature\n</code></pre>\n\n<p>I'm not sure how to do it with the git-config command. </p>\n\n<p>Be aware that from now on, all branches are pushed at the same when you do a straight git push (with no params).</p>\n\n<p>Would you care to explain why you don't keep the same branch names locally and remotely?</p>\n"
},
{
"answer_id": 169777,
"author": "Paul",
"author_id": 23356,
"author_profile": "https://Stackoverflow.com/users/23356",
"pm_score": 3,
"selected": true,
"text": "<p>If you can, I suggest you use the same branch names locally & remotely. Then <code>git push</code> will push all of your local branches to corresponding branches in the central repository.</p>\n\n<p>To use different prefixes in local and remote repos, you need to add a mapping to your config file each time you create a new feature branch. The command to set up the mapping for topic/BRANCH_NAME is</p>\n\n<pre><code> git config remote.origin.push refs/heads/topic/BRANCH_NAME:michael/BRANCH_NAME\n</code></pre>\n"
},
{
"answer_id": 9693905,
"author": "studgeek",
"author_id": 255961,
"author_profile": "https://Stackoverflow.com/users/255961",
"pm_score": 1,
"selected": false,
"text": "<p>You can map your branch to different tracking branch on the remote with something like this:</p>\n\n<pre><code>git remote add heroku [email protected]:YOURAPPNAME.git\ngit checkout -b heroku -t heroku/master\n</code></pre>\n\n<p>Your config ends up similar to what @Paul suggests (a tad \"simpler\" actually).</p>\n\n<p>See this gist (with tweaks by me) for usage steps that work well for me <a href=\"https://gist.github.com/2002048\" rel=\"nofollow\">https://gist.github.com/2002048</a>.</p>\n"
},
{
"answer_id": 64501952,
"author": "Adwait Mathkari",
"author_id": 9413125,
"author_profile": "https://Stackoverflow.com/users/9413125",
"pm_score": 2,
"selected": false,
"text": "<p>Use</p>\n<pre><code>git branch --set-upstream-to=origin/remoteBranch localBranch\n</code></pre>\n<p>where origin/remoteBranch is the remote name, and localBranch is the local branch name.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17688/"
] |
We're working with a semi-centralized git repository here where I work. Each developer has their own subtree in the central git repository, so it looks something like this:
```
master
alice/branch1
alice/branch2
bob/branch1
michael/feature
release/1.0
release/1.1
```
Working locally in my tree I have `topic/feature`, which corresponds to `michael/feature` in the central tree.
I've been using
```
git push origin topic/feature:michael/feature
```
to push my changes to the remote tree. However, this is cumbersome and prone to mistakes (e.g. omitting the developer name, misspelling the feature name, etc.).
I'm looking for a cleaner way to do this. For instance, "`git push`". I suspect that setting a different remote with a modified fetch refspec will do it, but I'm not sure how exactly to do it. I'm also not sure how to modify my current branch definitions to use the different remote.
My current `.git/config` looks something like:
```
[remote "origin"]
url = git://central/git/project
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "topic/feature"]
remote = origin
merge = refs/heads/michael/project
```
**Edit:** I'd also like to apply this to pulls/fetches. But does the `branch.<name>.merge` take care of that?
I'll continue to research this and post here if I find something, but I'm hoping to get some other good ideas.
**Edit 2:** I've decided I'll keep local and remote branch names the same. It appears it will be the least work and least prone to future problems.
|
If you can, I suggest you use the same branch names locally & remotely. Then `git push` will push all of your local branches to corresponding branches in the central repository.
To use different prefixes in local and remote repos, you need to add a mapping to your config file each time you create a new feature branch. The command to set up the mapping for topic/BRANCH\_NAME is
```
git config remote.origin.push refs/heads/topic/BRANCH_NAME:michael/BRANCH_NAME
```
|
167,735 |
<p>I am looking for a pseudo random number generator which would be specialized to work fast when it is given a seed before generating each number. Most generators I have seen so far assume you set seed once and then generate a long sequence of numbers. The only thing which looks somewhat similar to I have seen so far is Perlin Noise, but it generates too "smooth" data - for similar inputs it tends to produce similar results.</p>
<p>The declaration of the generator should look something like:</p>
<pre><code>int RandomNumber1(int seed);
</code></pre>
<p>Or:</p>
<pre><code>int RandomNumber3(int seedX, int seedY, int seedZ);
</code></pre>
<p>I think having good RandomNumber1 should be enough, as it is possible to implement RandomNumber3 by hashing its inputs and passing the result into the RandomNumber1, but I wrote the 2nd prototype in case some implementation could use the independent inputs.</p>
<p>The intended use for this generator is to use it for procedural content generator, like generating a forest by placing trees in a grid and determining a random tree species and random spatial offsets for each location.</p>
<p>The generator needs to be very efficient (below 500 CPU cycles), because the procedural content is created in huge quantities in real time during rendering.</p>
|
[
{
"answer_id": 167764,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>Seems like you're asking for a hash-function rather than a PRNG. Googling 'fast hash function' yields several promising-looking results.</p>\n\n<p><a href=\"http://burtleburtle.net/bob/hash/integer.html\" rel=\"noreferrer\">For example</a>:</p>\n\n<pre><code>uint32_t hash( uint32_t a)\n a = (a ^ 61) ^ (a >> 16);\n a = a + (a << 3);\n a = a ^ (a >> 4);\n a = a * 0x27d4eb2d;\n a = a ^ (a >> 15);\n return a;\n}\n</code></pre>\n\n<p><strong>Edit:</strong> Yep, some hash functions definitely look more suitable than others.</p>\n\n<p>For your purposes, it should be sufficient to eyeball thefunction and check that a single-bit change in the input will propagate to lots of output bits.</p>\n"
},
{
"answer_id": 167790,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 3,
"selected": false,
"text": "<p>Yep, you are looking for a fast integer hash algorithm rather than a PRNG.</p>\n\n<p>This <a href=\"http://www.concentric.net/~Ttwang/tech/inthash.htm\" rel=\"nofollow noreferrer\">page</a> has a few algorithms, I'm sure you'll find plenty more now you know the correct search terms.</p>\n\n<p><strong>Edit</strong>: The original page has been removed, a live version can be <a href=\"https://gist.github.com/badboy/6267743\" rel=\"nofollow noreferrer\">found on GitHub</a>.</p>\n"
},
{
"answer_id": 168078,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 2,
"selected": false,
"text": "<p>see <code>std::tr1::ranlux3</code>, or other random number generators that are part of TR1 additions to the standard C++ library. I suggested mt19937 initialially, but then saw your note that it needs to be very fast. TR1 is should be available on <a href=\"http://msdn.microsoft.com/en-us/library/bb982847.aspx\" rel=\"nofollow noreferrer\">Microsoft VC++</a> and GCC, and can also be found in the boost libraries which support even more compilers.</p>\n\n<p>example adapted from <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/random/index.html\" rel=\"nofollow noreferrer\">boost documentation</a>: </p>\n\n<pre><code>#include <random>\n#include <iostream>\n#include <iterator>\n#include <functional>\n#include <algorithm>\n#include <ctime>\nusing namespace std;\nusing namespace std::tr1;\nint main(){\n random_device trueRand;\n ranlux3 rng(trueRand); // produces randomness out of thin air\n // see pseudo-random number generators\n uniform_int<> six(1,6); // distribution that maps to 1..6\n // see random number distributions\n variate_generator<ranlux3&, uniform_int<> >\n die(rng, six); // glues randomness with mapping\n\n // simulate rolling a die\n generate_n( ostream_iterator<int>(cout, \" \"), 10, ref(die));\n}\n</code></pre>\n\n<p>example output:</p>\n\n<pre><code>2 4 4 2 4 5 4 3 6 2\n</code></pre>\n\n<p>Any TR1 random number generator can seed any <em>other</em> random number generator. If you need higher quality results, consider feeding the output of mt19937 (which is slower, but higher quality) into a minstd_rand or randlux3, which are faster generators.</p>\n"
},
{
"answer_id": 171212,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 0,
"selected": false,
"text": "<p>If memory is not really an issue and speed is of utmost importance then you can prebuild a large array of random numbers and just iterate through it at runtime. For example have a seperate program generate 100,000 random numbers and save it as it's own file like </p>\n\n<p>unsigned int randarray []={1,2,3,....}</p>\n\n<p>then include that file into your compile and at runtime your random number function only needs to pull numbers from that array and loop back to the start when it hits the end.</p>\n"
},
{
"answer_id": 215818,
"author": "John D. Cook",
"author_id": 25188,
"author_profile": "https://Stackoverflow.com/users/25188",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a small random number generator developed by George Marsaglia. He's an expert in the field, so you can be confident the generator has good statistical properties.</p>\n\n<pre><code>v = 36969*(v & 65535) + (v >> 16);\nu = 18000*(u & 65535) + (u >> 16);\nreturn (v << 16) + (u & 65535);\n</code></pre>\n\n<p>Here u and v are unsigned ints. Initialize them to any non-zero values. Each time you generate a random number, store u and v somewhere. You could wrap this in a function to match your signature above (except the ints are unsigned.)</p>\n"
},
{
"answer_id": 1759161,
"author": "mikera",
"author_id": 214010,
"author_profile": "https://Stackoverflow.com/users/214010",
"pm_score": 0,
"selected": false,
"text": "<p>I use the following code in my Java random number library - this has worked pretty well for me. I also use this for generating procedural content.</p>\n\n<pre><code>/**\n * State for random number generation\n */\nprivate static volatile long state=xorShift64(System.nanoTime()|0xCAFEBABE);\n\n/**\n * Gets a long random value\n * @return Random long value based on static state\n */\npublic static long nextLong() {\n long a=state;\n state = xorShift64(a);\n return a;\n}\n\n/**\n * XORShift algorithm - credit to George Marsaglia!\n * @param a initial state\n * @return new state\n */\npublic static final long xorShift64(long a) {\n a ^= (a << 21);\n a ^= (a >>> 35);\n a ^= (a << 4);\n return a;\n}\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16673/"
] |
I am looking for a pseudo random number generator which would be specialized to work fast when it is given a seed before generating each number. Most generators I have seen so far assume you set seed once and then generate a long sequence of numbers. The only thing which looks somewhat similar to I have seen so far is Perlin Noise, but it generates too "smooth" data - for similar inputs it tends to produce similar results.
The declaration of the generator should look something like:
```
int RandomNumber1(int seed);
```
Or:
```
int RandomNumber3(int seedX, int seedY, int seedZ);
```
I think having good RandomNumber1 should be enough, as it is possible to implement RandomNumber3 by hashing its inputs and passing the result into the RandomNumber1, but I wrote the 2nd prototype in case some implementation could use the independent inputs.
The intended use for this generator is to use it for procedural content generator, like generating a forest by placing trees in a grid and determining a random tree species and random spatial offsets for each location.
The generator needs to be very efficient (below 500 CPU cycles), because the procedural content is created in huge quantities in real time during rendering.
|
Seems like you're asking for a hash-function rather than a PRNG. Googling 'fast hash function' yields several promising-looking results.
[For example](http://burtleburtle.net/bob/hash/integer.html):
```
uint32_t hash( uint32_t a)
a = (a ^ 61) ^ (a >> 16);
a = a + (a << 3);
a = a ^ (a >> 4);
a = a * 0x27d4eb2d;
a = a ^ (a >> 15);
return a;
}
```
**Edit:** Yep, some hash functions definitely look more suitable than others.
For your purposes, it should be sufficient to eyeball thefunction and check that a single-bit change in the input will propagate to lots of output bits.
|
167,740 |
<p>I recently began profiling an osgi java application that I am writing using VisualVM. One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate. The Heap size and the PermGen size remains constant, however. The number of classes never falls, even after it stops sending data. Is this a memory leak? I think it is, because the loaded classes have to be stored somewhere, however the heap and permgen never increase even after I run the application for several hours.</p>
<p>For the screenshot of my profiling application go <a href="http://sites.google.com/site/javaperformacescreenshot/Home/profile.png" rel="noreferrer">here</a></p>
|
[
{
"answer_id": 167779,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it's usually a memory leak (since we don't really deal with memory directly, it's more of a class instance leak). I've gone through this process before and usually it's some listener added to an old toolkit that didn't remove it self.</p>\n\n<p>In older code, A listener relationship causes the \"listener\" object to remain around. I'd look at older toolkits or ones that haven't been through many revs. Any long-existing library running on a later JDK would know about reference objects which removes the requirement for \"Remove Listener\".</p>\n\n<p>Also, call dispose on your windows if you recreate them each time. I don't think they ever go away if you don't (Actually there is also a dispose on close setting).</p>\n\n<p>Don't worry about Swing or JDK listeners, they should all use references so you should be okay.</p>\n"
},
{
"answer_id": 167842,
"author": "rice",
"author_id": 23933,
"author_profile": "https://Stackoverflow.com/users/23933",
"pm_score": 2,
"selected": false,
"text": "<p>Unless I misunderstand, we're looking here at loaded classes, not instances.</p>\n\n<p>When your code first references a class, the JVM has the ClassLoader go out and fetch the information about the class from a .class file or the like.</p>\n\n<p>I'm not sure under what conditions it would unload a class. Certainly it should never unload any class with static information.</p>\n\n<p>So I would expect a pattern roughly like yours, where as your application runs it goes into areas and references new classes, so the number of loaded classes would go up and up.</p>\n\n<p>However, two things seems strange to me:</p>\n\n<ol>\n<li>Why is it so linear?</li>\n<li>Why doesn't it plateau?</li>\n</ol>\n\n<p>I would expect it to trend upwards, but in a wobbly line, and then taper off on the increase as the JVM has already loaded most of the classes your program references. I mean, there are a finite number of classes referenced in most applications.</p>\n\n<p>Are you dynamically creating new classes on the fly somehow?</p>\n\n<p>I would suggest running a simpler test app through the same debugger to get a baseline case. Then you could consider implementing your own ClassLoader that spits out some debug information, or maybe there is a tool to make it report.</p>\n\n<p>You need to figure out what these classes being loaded are.</p>\n"
},
{
"answer_id": 167887,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 2,
"selected": false,
"text": "<p>You might find some hotspot flags to be of use in understanding this behavior like:</p>\n\n<ul>\n<li>-XX:+TraceClassLoading</li>\n<li>-XX:+TraceClassUnloading</li>\n</ul>\n\n<p>This is a good reference:</p>\n\n<p><a href=\"http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp</a></p>\n"
},
{
"answer_id": 167971,
"author": "Kyle",
"author_id": 3335,
"author_profile": "https://Stackoverflow.com/users/3335",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>Are you dynamically creating new classes on the fly somehow?</p>\n</blockquote>\n\n<p>Thanks for your help. I figured out what the problem is. In one of my classes, I was using Jaxb to create an XML string. In doing this, JAXB ueses reflection to create a new class.</p>\n\n<pre><code>JAXBContext context = JAXBContext.newInstance(this.getClass());\n</code></pre>\n\n<p>So although the JAXBContext wasn't saying around in the heap, the classes had been loaded.</p>\n\n<p>I have run my program again, and I see a normal plateau as I would expect.</p>\n"
},
{
"answer_id": 168056,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 2,
"selected": false,
"text": "<p>I'm willing to bet that your problem is related to bytecode generation. </p>\n\n<p>Many libraries use CGLib, BCEL, Javasist or Janino to generate bytecode for new classes at runtime and then load them from controlled classloader. The only way to release these classes is to release all references to the classloader. </p>\n\n<p>Since the classloader is held by each class, this also means that you should not release the references to all classes as well [1]. You can catch these with a decent profiler (I use Yourkit - search for multiple classloader instances with the same retained size)</p>\n\n<p>One catch is that the JVM does not unload classes by default (the reason is backwards compatibility - that people assume (wrongly) that static initializers would be executed only once. The truth is that they get executed every time a class is loaded.) To enable unloading, you should pass some use the following options:</p>\n\n<pre><code>-XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled\n</code></pre>\n\n<p>(tested with JDK 1.5)</p>\n\n<p>Even then, excessive bytecode generation is not a good idea, so I suggest you look in your code to find the culprit and cache the generated classes. Frequent offenders are scripting languages, dynamic proxies (including the ones generated by application servers) or huge Hibernate model (in this case you can just increase your permgen).</p>\n\n<p>See also:</p>\n\n<ol>\n<li><a href=\"http://blogs.oracle.com/watt/resource/jvm-options-list.html\" rel=\"nofollow noreferrer\">http://blogs.oracle.com/watt/resource/jvm-options-list.html</a></li>\n<li><a href=\"http://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation\" rel=\"nofollow noreferrer\">http://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation</a></li>\n<li><a href=\"http://forums.sun.com/thread.jspa?messageID=2833028\" rel=\"nofollow noreferrer\">http://forums.sun.com/thread.jspa?messageID=2833028</a></li>\n</ol>\n"
},
{
"answer_id": 191852,
"author": "kohlerm",
"author_id": 26056,
"author_profile": "https://Stackoverflow.com/users/26056",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <a href=\"http://www.eclipse.org/mat/\" rel=\"nofollow noreferrer\">Eclipse Memory Analyzer</a> to check for duplicated classes and memory leaks. It might happen that the same class gets loaded more than once. </p>\n\n<p>Regards,\n<a href=\"http://kohlerm.blogspot.com/\" rel=\"nofollow noreferrer\">Markus</a> </p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3335/"
] |
I recently began profiling an osgi java application that I am writing using VisualVM. One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate. The Heap size and the PermGen size remains constant, however. The number of classes never falls, even after it stops sending data. Is this a memory leak? I think it is, because the loaded classes have to be stored somewhere, however the heap and permgen never increase even after I run the application for several hours.
For the screenshot of my profiling application go [here](http://sites.google.com/site/javaperformacescreenshot/Home/profile.png)
|
>
> Are you dynamically creating new classes on the fly somehow?
>
>
>
Thanks for your help. I figured out what the problem is. In one of my classes, I was using Jaxb to create an XML string. In doing this, JAXB ueses reflection to create a new class.
```
JAXBContext context = JAXBContext.newInstance(this.getClass());
```
So although the JAXBContext wasn't saying around in the heap, the classes had been loaded.
I have run my program again, and I see a normal plateau as I would expect.
|
167,752 |
<p>I would like to add a typing speed indicator just below the textarea we use on our contact form. It is just for fun and to give the user some interactivity with the page while they are completing the form.</p>
<p>It should display the average speed while typing and keep the last average when the keystrokes are idle. When they leave the textarea the last average should stick.</p>
<p>Ideally I would like to have a jQuery plugin if it is available.</p>
<p>[Edit] this was originally for just a few of my websites. But after I posted the question it struck me how this would be a neat feature for SO. If you agree <a href="http://stackoverflow.uservoice.com/pages/general/suggestions/32755" rel="noreferrer">vote here</a></p>
|
[
{
"answer_id": 167799,
"author": "Kent Brewster",
"author_id": 1151280,
"author_profile": "https://Stackoverflow.com/users/1151280",
"pm_score": 1,
"selected": false,
"text": "<p>Typing speed is generally computed in words per minute minus a penalty for typos. To do this it seems like you'd need an inline spell-checker at the very least, plus some heavy lifting for languages and encoding schemes. (And then it starts to get complicated; when does the clock start, for instance? What do you do about people who are entering code? How about copy-and-pasting?)</p>\n"
},
{
"answer_id": 167828,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": -1,
"selected": false,
"text": "<p>a horribly simple, <strong>untested</strong> implementation:</p>\n\n<pre><code>var lastrun = new Date();\ntextarea.onkeyup = function() {\n var words = textarea.value.split(' ');\n var minutes_since_last_check = somefunctiontogetminutesdifference(new Date(), lastrun);\n var wpm = (words.length-1)/minutes_since_last_check;\n //show the wpm in a div or something\n};\n</code></pre>\n"
},
{
"answer_id": 167902,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 5,
"selected": true,
"text": "<p>Here's a tested implementation,which seems ok, but I don't guarantee the math.</p>\n\n<p>A Demo: <a href=\"http://jsfiddle.net/iaezzy/pLpx5oLf/\" rel=\"noreferrer\">http://jsfiddle.net/iaezzy/pLpx5oLf/</a></p>\n\n<p>And the code:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n <title>Type Speed</title>\n <script type=\"text/javascript\" src=\"js/jquery-1.2.6.js\"></script>\n <style type=\"text/css\">\n form {\n margin: 20px auto;\n width: 500px;\n }\n\n #textariffic {\n width: 400px;\n height: 400px;\n font-size: 12px;\n font-family: monospace;\n line-height: 15px;\n }\n </style>\n <script type=\"text/javascript\">\n $(function() {\n $('textarea')\n .keyup(checkSpeed);\n });\n\n var iLastTime = 0;\n var iTime = 0;\n var iTotal = 0;\n var iKeys = 0;\n\n function checkSpeed() {\n iTime = new Date().getTime();\n\n if (iLastTime != 0) {\n iKeys++;\n iTotal += iTime - iLastTime;\n iWords = $('textarea').val().split(/\\s/).length;\n $('#CPM').html(Math.round(iKeys / iTotal * 6000, 2));\n $('#WPM').html(Math.round(iWords / iTotal * 6000, 2));\n }\n\n iLastTime = iTime;\n }\n\n </script>\n </head>\n <body>\n <form id=\"tipper\">\n <textarea id=\"textariffic\"></textarea>\n <p>\n <span class=\"label\">CPM</span>\n <span id=\"CPM\">0</span>\n </p>\n <p>\n <span class=\"label\">WPM</span>\n <span id=\"WPM\">0</span>\n </p>\n </form>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 22908660,
"author": "Xsi",
"author_id": 1835606,
"author_profile": "https://Stackoverflow.com/users/1835606",
"pm_score": 2,
"selected": false,
"text": "<p>It's my own ego involvement:</p>\n\n<pre><code><textarea id=\"b\" onblur=\"clc();\"></textarea>\n<script>\nt=0;\ndocument.getElementById('b').onkeypress=function()\n{\nt==0 ? s=new Date() : e=new Date();\nt=1;\n}\nfunction clc()\n{\nd = e.getTime() - s.getTime();\nc = b.value.length;\nb.value += \"\\n\"+c+\"s in \"+d+\"ms: \"+c/d+\" cpms\";\n}\n</script>\n</code></pre>\n\n<p>I spent over a week on this learning JavaScript from zero (cutting and cutting). This will be a good starting point. It's now so simple that needs bare explanation. You could add anything to it. Its the best known minimalist and purest form. </p>\n\n<p>It just gives you all into a textarea:\n<img src=\"https://i.stack.imgur.com/Wi2yj.jpg\" alt=\"enter image description here\"></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
I would like to add a typing speed indicator just below the textarea we use on our contact form. It is just for fun and to give the user some interactivity with the page while they are completing the form.
It should display the average speed while typing and keep the last average when the keystrokes are idle. When they leave the textarea the last average should stick.
Ideally I would like to have a jQuery plugin if it is available.
[Edit] this was originally for just a few of my websites. But after I posted the question it struck me how this would be a neat feature for SO. If you agree [vote here](http://stackoverflow.uservoice.com/pages/general/suggestions/32755)
|
Here's a tested implementation,which seems ok, but I don't guarantee the math.
A Demo: <http://jsfiddle.net/iaezzy/pLpx5oLf/>
And the code:
```
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Type Speed</title>
<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<style type="text/css">
form {
margin: 20px auto;
width: 500px;
}
#textariffic {
width: 400px;
height: 400px;
font-size: 12px;
font-family: monospace;
line-height: 15px;
}
</style>
<script type="text/javascript">
$(function() {
$('textarea')
.keyup(checkSpeed);
});
var iLastTime = 0;
var iTime = 0;
var iTotal = 0;
var iKeys = 0;
function checkSpeed() {
iTime = new Date().getTime();
if (iLastTime != 0) {
iKeys++;
iTotal += iTime - iLastTime;
iWords = $('textarea').val().split(/\s/).length;
$('#CPM').html(Math.round(iKeys / iTotal * 6000, 2));
$('#WPM').html(Math.round(iWords / iTotal * 6000, 2));
}
iLastTime = iTime;
}
</script>
</head>
<body>
<form id="tipper">
<textarea id="textariffic"></textarea>
<p>
<span class="label">CPM</span>
<span id="CPM">0</span>
</p>
<p>
<span class="label">WPM</span>
<span id="WPM">0</span>
</p>
</form>
</body>
</html>
```
|
167,760 |
<p>I have a class holding complex scientific computations. It is set up to only allow a user to create a properly instantiated case. To properly test the code, however, requires setting internal state variables directly, since the reference documents supply this data in their test cases. Done improperly, however, it can invalidate the state.<p>
So I must have the ability, a member function, to set internal variables from the unit test programs. But I want to <b>strongly discourage</b> normal users from calling this function. (Yes, a determined user can muck with anything... but I don't want to <i>advertise</i> that there is a way to do something <i>wrong</i>.)<p>
It would be nice to be able to tell Intellisense to not show the function, for instance.<p>
The best solution I have at the moment is to just name the function something like: DangerousSet().<p>
What other options do I have?<P>
<b>Follow-Up</b><p>
I found Amy B's answer most useful to my situation. Thanks!<br>
Mufasa's suggestion to use reflection was great, but harder to implement (for me).<br>
Chris' suggestion of using a decorator was good, but didn't pan out.<br>
BFree's suggestion on XML is also good, and was already in use, but doesn't really solve the problem.<p>
Finally, BillTheLizard's suggestion that the problem is in the source documents is not something I can control. International experts publish highly technical books and journal articles for use by their community. The fact that they don't address my particular needs is a fact of life. There simply are no alternative documents.</p>
|
[
{
"answer_id": 167767,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow noreferrer\">InternalsVisibleToAttribute</a> to mark internal members as visible to your test assembly. It seems to shine when used in this context, though its not quite \"friend\".</p>\n\n<ol>\n<li><p>Mark your <code>DangerousSet</code> function <code>internal</code> instead of <code>public</code>.</p></li>\n<li><p>In Properties\\AssemblyInfo.cs of the project containing <code>DangerousSet</code>:</p>\n\n<p><code>[assembly:InternalsVisibleTo(\"YourTestAssembly\")]</code></p></li>\n</ol>\n\n<p>If you have two test assemblies for whatever reason, the syntax is:</p>\n\n<pre><code>[assembly:InternalsVisibleTo(\"TestAssembly1\"), \n InternalsVisibleTo(\"TestAssembly2\")]\n</code></pre>\n"
},
{
"answer_id": 167769,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 0,
"selected": false,
"text": "<p>Can your test code include a subclass of the calculations class? If so, you can mark the function <code>protected</code> and only inheritors will be able to use it. I'm pretty sure this also takes it out of intellisense, but I could be wrong about that. </p>\n"
},
{
"answer_id": 167770,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 3,
"selected": false,
"text": "<p>Decorate your method with this attribute:</p>\n\n<pre><code>[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n</code></pre>\n\n<p>This will hide it from Intellisense.</p>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>But apparently this has a rather significant caveat: \"In Visual C#, <code>EditorBrowsableAttribute</code> does not suppress members from a class in the same assembly.\" <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx\" rel=\"nofollow noreferrer\">Via MSDN</a>.</p>\n"
},
{
"answer_id": 167782,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like your real problem is in your reference documents. You shouldn't test cases that are impossible to encounter under proper use of your class. If users shouldn't be allowed to change the state of those variables, then neither should your tests.</p>\n"
},
{
"answer_id": 167802,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 0,
"selected": false,
"text": "<p>What I've done in the past is I put XML Comments by the method and used the section to write in big bold letters. DON'T USE THIS METHOD or whatever. That way, if someone tried to use it, Intellisense would give them a nice warning.</p>\n"
},
{
"answer_id": 168094,
"author": "Jon Adams",
"author_id": 2291,
"author_profile": "https://Stackoverflow.com/users/2291",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use reflection. Google search turned up <a href=\"http://sjbdeveloper.blogspot.com/2005/02/unit-testing-private-methods-using.html\" rel=\"nofollow noreferrer\">Unit testing private methods using reflection</a>.</p>\n"
},
{
"answer_id": 168097,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "<p>Suppose you want to test this object by manipulating its fields.</p>\n\n<pre><code>public class ComplexCalculation\n{\n protected int favoriteNumber;\n public int FavoriteNumber\n {\n get { return favoriteNumber; }\n }\n}\n</code></pre>\n\n<p>Place this object in your test assembly/namespace:</p>\n\n<pre><code>public class ComplexCalculationTest : ComplexCalculation\n{\n public void SetFavoriteNumber(int newFavoriteNumber)\n {\n this.favoriteNumber = newFavoriteNumber;\n }\n}\n</code></pre>\n\n<p>And write your test:</p>\n\n<pre><code> public void Test()\n {\n ComplexCalculationTest myTestObject = new ComplexCalculationTest();\n myTestObject.SetFavoriteNumber(3);\n ComplexCalculation myObject = myTestObject;\n\n if (myObject.FavoriteNumber == 3)\n Console.WriteLine(\"Win!\");\n\n }\n</code></pre>\n\n<p>PS: I know you said <em>internal</em>, but I don't think you meant <a href=\"http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx\" rel=\"nofollow noreferrer\">internal</a>.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722/"
] |
I have a class holding complex scientific computations. It is set up to only allow a user to create a properly instantiated case. To properly test the code, however, requires setting internal state variables directly, since the reference documents supply this data in their test cases. Done improperly, however, it can invalidate the state.
So I must have the ability, a member function, to set internal variables from the unit test programs. But I want to **strongly discourage** normal users from calling this function. (Yes, a determined user can muck with anything... but I don't want to *advertise* that there is a way to do something *wrong*.)
It would be nice to be able to tell Intellisense to not show the function, for instance.
The best solution I have at the moment is to just name the function something like: DangerousSet().
What other options do I have?
**Follow-Up**
I found Amy B's answer most useful to my situation. Thanks!
Mufasa's suggestion to use reflection was great, but harder to implement (for me).
Chris' suggestion of using a decorator was good, but didn't pan out.
BFree's suggestion on XML is also good, and was already in use, but doesn't really solve the problem.
Finally, BillTheLizard's suggestion that the problem is in the source documents is not something I can control. International experts publish highly technical books and journal articles for use by their community. The fact that they don't address my particular needs is a fact of life. There simply are no alternative documents.
|
Suppose you want to test this object by manipulating its fields.
```
public class ComplexCalculation
{
protected int favoriteNumber;
public int FavoriteNumber
{
get { return favoriteNumber; }
}
}
```
Place this object in your test assembly/namespace:
```
public class ComplexCalculationTest : ComplexCalculation
{
public void SetFavoriteNumber(int newFavoriteNumber)
{
this.favoriteNumber = newFavoriteNumber;
}
}
```
And write your test:
```
public void Test()
{
ComplexCalculationTest myTestObject = new ComplexCalculationTest();
myTestObject.SetFavoriteNumber(3);
ComplexCalculation myObject = myTestObject;
if (myObject.FavoriteNumber == 3)
Console.WriteLine("Win!");
}
```
PS: I know you said *internal*, but I don't think you meant [internal](http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx).
|
167,827 |
<p>Friends/family/etc ask me what I do and it always causes me pause while I think of how to explain it. They know what a software developer is but how can I explain what SCM is in 10 words?</p>
|
[
{
"answer_id": 167840,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "<p>The guy who makes sure that what gets deployed is what's meant to get deployed.</p>\n"
},
{
"answer_id": 167869,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 1,
"selected": false,
"text": "<p>I'd tell people \"I work in software development\". I wouldn't bother explaining what you do IN software development unless they ask for more details. I find that 90% of people are satisfied with that answer, and give more details to the 10% of people who are interested.</p>\n"
},
{
"answer_id": 167992,
"author": "John Ferguson",
"author_id": 8312,
"author_profile": "https://Stackoverflow.com/users/8312",
"pm_score": 2,
"selected": true,
"text": "<p>Surprising they know what a software developer does!</p>\n\n<p>Anwyay, this sounds like a challenge for Haiku enthusiasts:</p>\n\n<p>in 5-7-5 (I'm lazy when doing english haiku and my seasonal reference is flakey - try a 3-5-3 if you like)</p>\n\n<pre><code>from many good parts:\none programme on your PC;\nlose track, get winter\n</code></pre>\n\n<p>(hmm, 13 words)</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24881/"
] |
Friends/family/etc ask me what I do and it always causes me pause while I think of how to explain it. They know what a software developer is but how can I explain what SCM is in 10 words?
|
Surprising they know what a software developer does!
Anwyay, this sounds like a challenge for Haiku enthusiasts:
in 5-7-5 (I'm lazy when doing english haiku and my seasonal reference is flakey - try a 3-5-3 if you like)
```
from many good parts:
one programme on your PC;
lose track, get winter
```
(hmm, 13 words)
|
167,852 |
<p>I am hosting a WCF service in a Windows Service on one of our servers. After making it work in basicHttpBinding and building a test client in .NET (which finally worked) I went along and try to access it from PHP using the SoapClient class. The final consumer will be a PHP site so I need to make it consumable in PHP.</p>
<p>I got stumped when I had to enter the WSDL url in the constructor of the SoapClient class in the PHP code. Where is the WSDL? All I have is :</p>
<p><a href="http://172.27.7.123:8000/WordService" rel="noreferrer">http://172.27.7.123:8000/WordService</a> and
<a href="http://172.27.7.123:8000/WordService/mex" rel="noreferrer">http://172.27.7.123:8000/WordService/mex</a></p>
<p>None of these do not expose WSDL.</p>
<p>Being a newbie in WCF I might have asked a dumb thing (or I might have a wrong assumption somewhere). Please be gentle :D</p>
<p>And no, <a href="http://172.27.7.123:8000/WordService?wsdl" rel="noreferrer">http://172.27.7.123:8000/WordService?wsdl</a> does not show anything different than <a href="http://172.27.7.123:8000/WordService" rel="noreferrer">http://172.27.7.123:8000/WordService</a> :(</p>
<p>Am I forced to host it in IIS? Am I forced to use a regular WebService?</p>
|
[
{
"answer_id": 167965,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 1,
"selected": false,
"text": "<p>Please see this link:</p>\n\n<p><a href=\"http://keithelder.net/blog/archive/2008/01/17/Exposing-a-WCF-Service-With-Multiple-Bindings-and-Endpoints.aspx\" rel=\"nofollow noreferrer\">Exposing a WCF Service With Multiple Bindings and Endpoints</a></p>\n\n<pre>\nUnlike previous ASMX services, the WSDL (web service definition language) for WCF \nservices is not automatically generated. The previous image even tells us that \n\"Metadata publishing for this service is currently disabled.\". \nThis is because we haven't configured our service to expose any meta data about it. \n To expose a WSDL for a service we need to configure our service to provide meta information. Note: \nThe mexHttpBinding is also used to share meta information about a service. While \nthe name isn't very \"gump\" it stands for Meta Data Exchange.\n</pre>\n"
},
{
"answer_id": 167968,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 4,
"selected": true,
"text": "<p>This might help:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms734765.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms734765.aspx</a></p>\n\n<p>In a nutshell you need to configure your service endpoints and behaviour. Here is a minimal example:</p>\n\n<pre><code><system.serviceModel>\n <services>\n\n <service \n <!-- Namespace.ServiceClass implementation -->\n name=\"WcfService1.Service1\" \n\n <!-- User behaviour defined below -->\n behaviorConfiguration=\"SimpleServiceBehaviour\"> \n\n <endpoint \n address=\"\" \n binding=\"basicHttpBinding\"\n <!-- Namespace.Interface that defines our service contract -->\n contract=\"WcfService1.IService1\"/>\n\n </service>\n </services>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"SimpleServiceBehaviour\">\n\n <serviceMetadata \n <!-- We allow HTTP GET -->\n httpGetEnabled=\"true\" \n\n <!-- Conform to WS-Policy 1.5 when generating metadata -->\n policyVersion=\"Policy15\"/>\n\n </behavior>\n </serviceBehaviors>\n </behaviors>\n</system.serviceModel>\n</code></pre>\n\n<p>Don't forget to remove the XML comments as they're invalid where they are.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796/"
] |
I am hosting a WCF service in a Windows Service on one of our servers. After making it work in basicHttpBinding and building a test client in .NET (which finally worked) I went along and try to access it from PHP using the SoapClient class. The final consumer will be a PHP site so I need to make it consumable in PHP.
I got stumped when I had to enter the WSDL url in the constructor of the SoapClient class in the PHP code. Where is the WSDL? All I have is :
<http://172.27.7.123:8000/WordService> and
<http://172.27.7.123:8000/WordService/mex>
None of these do not expose WSDL.
Being a newbie in WCF I might have asked a dumb thing (or I might have a wrong assumption somewhere). Please be gentle :D
And no, <http://172.27.7.123:8000/WordService?wsdl> does not show anything different than <http://172.27.7.123:8000/WordService> :(
Am I forced to host it in IIS? Am I forced to use a regular WebService?
|
This might help:
<http://msdn.microsoft.com/en-us/library/ms734765.aspx>
In a nutshell you need to configure your service endpoints and behaviour. Here is a minimal example:
```
<system.serviceModel>
<services>
<service
<!-- Namespace.ServiceClass implementation -->
name="WcfService1.Service1"
<!-- User behaviour defined below -->
behaviorConfiguration="SimpleServiceBehaviour">
<endpoint
address=""
binding="basicHttpBinding"
<!-- Namespace.Interface that defines our service contract -->
contract="WcfService1.IService1"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SimpleServiceBehaviour">
<serviceMetadata
<!-- We allow HTTP GET -->
httpGetEnabled="true"
<!-- Conform to WS-Policy 1.5 when generating metadata -->
policyVersion="Policy15"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
```
Don't forget to remove the XML comments as they're invalid where they are.
|
167,858 |
<p>I need to do some communications over a serial port in Ruby. From my research, it appears that there aren't many modern libraries for serial communications and the newest material I can find is from 2006. Are there any gems that I'm not aware of?</p>
<p>I ultimately need to maintain communications with a serial device attached to USB (I can figure out the port no problem) for back and forth communications like so (somewhat Ruby-esque pseudo code).</p>
<pre><code>def serial_write_read
if serial.read == "READY"
serial.write "1"
until serial.read == "OK"
serial.write "5"
end
return when serial.read == "DONE"
end
end
</code></pre>
|
[
{
"answer_id": 168132,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 3,
"selected": true,
"text": "<p>The serial port specification has not changed in forever, I wouldn't worry about how old the libraries are.</p>\n\n<p>I'm assuming you saw <a href=\"http://www.rubyinside.com/cross-platform-ruby-serial-port-library-328.html\" rel=\"nofollow noreferrer\">this</a> article from 2006 about ruby and serial ports </p>\n\n<p><a href=\"http://www.openlogic.com/blogs/2008/04/access-serial-ports-through-ruby/\" rel=\"nofollow noreferrer\">Here's</a> someone who got the <a href=\"http://rubyforge.org/projects/ruby-serialport/\" rel=\"nofollow noreferrer\">Ruby-SerialPort</a> library mentioned there to work on macs this year.</p>\n\n<p>There's also <a href=\"http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/35355\" rel=\"nofollow noreferrer\">this old post</a> from ruby talk, about interfacing to the Win32 Serial API.</p>\n"
},
{
"answer_id": 241676,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>While the serial standard has not changed, the way Ruby Gems interact with Ruby C extensions changed enough over the years so that the RubyForge serial port extension would not play well. There have been some patches over the years on RubyForge to fix that, but it hasn't been pretty. The great news is that Github has allowed an incredible acceleration in the activity to clean up the Ruby serial port extension. At least three different people are cross-branching their serial port code on Github. You can search on Github, but I believe that Toholio has the latest code, which recodes and repackages the Ruby serial port as a Ruby Gem. (Yea!)</p>\n\n<p><a href=\"http://github.com/toholio/ruby-serialport/tree/master\" rel=\"nofollow noreferrer\">http://github.com/toholio/ruby-serialport/tree/master</a></p>\n\n<p>It works great for me on Linux, solving the earlier conflict with the latest Ruby Gems release. On Windows, I'm still having a problem getting it working. Compiling Ruby extensions on Windows is never very easy, but that is a whole 'nuther can of worms. I'm just happy that people are working on the Ruby serial port support again. I've asked Toholio to generate a Windows binary gem, which would solve everyone's problems, and he says it's on his list to do.</p>\n"
},
{
"answer_id": 3811961,
"author": "Vassilis Rizopoulos",
"author_id": 436079,
"author_profile": "https://Stackoverflow.com/users/436079",
"pm_score": 2,
"selected": false,
"text": "<p>Just because searching for ruby-serialport will lead you sometimes here:</p>\n\n<p>toholio's github repo no longer seems to be active (as of 09/2010).\nThe published gem comes from</p>\n\n<p><a href=\"http://github.com/hparra/ruby-serialport\" rel=\"nofollow\">http://github.com/hparra/ruby-serialport</a></p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23909/"
] |
I need to do some communications over a serial port in Ruby. From my research, it appears that there aren't many modern libraries for serial communications and the newest material I can find is from 2006. Are there any gems that I'm not aware of?
I ultimately need to maintain communications with a serial device attached to USB (I can figure out the port no problem) for back and forth communications like so (somewhat Ruby-esque pseudo code).
```
def serial_write_read
if serial.read == "READY"
serial.write "1"
until serial.read == "OK"
serial.write "5"
end
return when serial.read == "DONE"
end
end
```
|
The serial port specification has not changed in forever, I wouldn't worry about how old the libraries are.
I'm assuming you saw [this](http://www.rubyinside.com/cross-platform-ruby-serial-port-library-328.html) article from 2006 about ruby and serial ports
[Here's](http://www.openlogic.com/blogs/2008/04/access-serial-ports-through-ruby/) someone who got the [Ruby-SerialPort](http://rubyforge.org/projects/ruby-serialport/) library mentioned there to work on macs this year.
There's also [this old post](http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/35355) from ruby talk, about interfacing to the Win32 Serial API.
|
167,862 |
<p>One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having... </p>
<pre><code>using namespace xyzzy
</code></pre>
<p>...statements in them, which impact on my code when I least want or expect it.</p>
<p>Is there a way I can somehow cancel/override a previous "using" statement to avoid this.</p>
<p>Maybe...</p>
<pre><code>unusing namespace xyzzy;
</code></pre>
|
[
{
"answer_id": 168007,
"author": "jk.",
"author_id": 21284,
"author_profile": "https://Stackoverflow.com/users/21284",
"pm_score": 6,
"selected": false,
"text": "<p>No you can't <em>unuse</em> a namespace. The only thing you can do is putting the <code>using namespace</code>-statement a block to limit it's scope.</p>\n\n<p>Example:</p>\n\n<pre><code>{\n using namespace xyzzy;\n\n} // stop using namespace xyzzy here\n</code></pre>\n\n<p>Maybe you can change the template which is used of your auto-generated headers.</p>\n"
},
{
"answer_id": 168023,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 1,
"selected": false,
"text": "<p>Quick experiment with Visual Studio 2005 shows that you can enclose those headers in your own named namespace and then <code>use</code> what you need from this namespace (but don't <code>use</code> the whole namespace, as it will introduces the namespace you want to hide.</p>\n"
},
{
"answer_id": 168027,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 4,
"selected": false,
"text": "<p>You may be stuck using explicit namespaces on conflicts:</p>\n\n<pre><code>string x; // Doesn't work due to conflicting declarations\n::string y; // use the class from the global namespace\nstd::string z; // use the string class from the std namespace\n</code></pre>\n"
},
{
"answer_id": 168033,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 7,
"selected": true,
"text": "<p>Nope. But there's a potential solution: if you enclose your include directive in a namespace of its own, like this...</p>\n\n<pre><code>namespace codegear {\n #include \"codegear_header.h\"\n} // namespace codegear\n</code></pre>\n\n<p>...then the effects of any using directives within that header are neutralized.</p>\n\n<p>That might be problematic in some cases. That's why every C++ style guide strongly recommends <em>not</em> putting a \"using namespace\" directive in a header file.</p>\n"
},
{
"answer_id": 168105,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>How about using sed, perl or some other command-line tool as part of your build process to modify the generated headers after they are generated but before they are used?</p>\n"
},
{
"answer_id": 4652630,
"author": "cdelacroix",
"author_id": 570553,
"author_profile": "https://Stackoverflow.com/users/570553",
"pm_score": 3,
"selected": false,
"text": "<p>For future reference : since the XE version there is a new value that you can #define to avoid the dreaded <code>using namespace System;</code> int the include : DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE</p>\n"
},
{
"answer_id": 43629955,
"author": "Narendra kumawat",
"author_id": 7918558,
"author_profile": "https://Stackoverflow.com/users/7918558",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include<iostream>\n#include<stdio.h>\nnamespace namespace1 {\n int t = 10;\n}\nnamespace namespace2 {\n int t = 20;\n}\nint main() {\nusing namespace namespace1;\n printf(\"%d\" , t);\n printf(\"%d\" , namespace2::t);\n}\n</code></pre>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having...
```
using namespace xyzzy
```
...statements in them, which impact on my code when I least want or expect it.
Is there a way I can somehow cancel/override a previous "using" statement to avoid this.
Maybe...
```
unusing namespace xyzzy;
```
|
Nope. But there's a potential solution: if you enclose your include directive in a namespace of its own, like this...
```
namespace codegear {
#include "codegear_header.h"
} // namespace codegear
```
...then the effects of any using directives within that header are neutralized.
That might be problematic in some cases. That's why every C++ style guide strongly recommends *not* putting a "using namespace" directive in a header file.
|
167,909 |
<p>I hate Physics, but I love software development. When I go back to school after Thanksgiving, I'll be taking two more quarters of Physics before I'm done with the horrid thing. I am currently reading postings on the F# units of measurement feature, but I've never used a language like F#. Would it be suitable to write applications so I can perhaps learn something about Physics while doing something I like?</p>
<p>I'm interested in command-line applications (even those that I can just execute and have spit out an answer without needing inputs) for things like kinematics, planar motion, Newton's Laws, gravitation, work, energy, momentum and impulse, systems of particles, rotational kinematics and dynamics, angular momentum, static equilibrium, oscillatory motion, wave motion, sound, physical optics, electrostatics, Gauss' law, electric field and potential, capacitance, resistance, DC circuits, magnetic field, Ampere's law, and inductance.</p>
<p>The reason I'm interested in F# is because of the units of measure functionality that the language provides.</p>
|
[
{
"answer_id": 167933,
"author": "Ian Hopkinson",
"author_id": 19172,
"author_profile": "https://Stackoverflow.com/users/19172",
"pm_score": -1,
"selected": false,
"text": "<p>Learning any computer language won't teach you physics, and you can learn physics by writing programs in any language.</p>\n\n<p>Dimensional analysis is a rather handy tool for physics problems, it can steer you away from being \"not even wrong\".</p>\n\n<p>I've always gained a certain perverse pleasure in getting an answer wrong by factors of 10^34 because I'd got my units wrong somewhere ;-)</p>\n"
},
{
"answer_id": 167967,
"author": "Pascal T.",
"author_id": 19816,
"author_profile": "https://Stackoverflow.com/users/19816",
"pm_score": 3,
"selected": false,
"text": "<p>I rode the introduction of a book call \"F# for scientists\" (the intro is available for free), and it seems to be a good introduction to the field, since F# seems to be very well adapted to this kind of field.</p>\n\n<p>You might want to have a look at the introduction.</p>\n\n<p><a href=\"http://www.ffconsultancy.com/products/fsharp_for_scientists/\" rel=\"nofollow noreferrer\">http://www.ffconsultancy.com/products/fsharp_for_scientists/</a></p>\n\n<p>(And no, I have no relationship with the author ;-)</p>\n"
},
{
"answer_id": 167989,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 1,
"selected": false,
"text": "<p>Fsharp is one choice. If you want to learn a skill which may also be of more long-term benefit why not learn python. You'll also have numpy and scipy at your fingertips then too.</p>\n"
},
{
"answer_id": 168053,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 2,
"selected": false,
"text": "<p>Yes (any language is) and No (learn what your future colleagues will use, like maybe they use python.). An interesting aside is <a href=\"http://en.wikipedia.org/wiki/Fortress_(programming_language)\" rel=\"nofollow noreferrer\">Fortress</a>.</p>\n"
},
{
"answer_id": 168110,
"author": "Chris Smith",
"author_id": 322,
"author_profile": "https://Stackoverflow.com/users/322",
"pm_score": 5,
"selected": true,
"text": "<p>In my biased opinion, F# is ideal for physics. It has a feature called Units of Measure which does dimensional analysis for you, providing errors if you get it wrong. For example if you write:</p>\n\n<pre><code>let distance : float<meters> = gravity * 3.0<seconds>\n</code></pre>\n\n<p>That would <strong>yield a compile-error</strong>, since gravity is < meters/seconds^2 > and not < meters >. This prevents a great deal of physics-related programming errors.</p>\n\n<p>For more information check out <a href=\"http://blogs.msdn.com/andrewkennedy/\" rel=\"noreferrer\">Andrew Kennedy's blog</a>.</p>\n"
},
{
"answer_id": 170461,
"author": "Pascal T.",
"author_id": 19816,
"author_profile": "https://Stackoverflow.com/users/19816",
"pm_score": 2,
"selected": false,
"text": "<p>About dimensional analysis : a fun calculus trick once given by one of my physics professors: given that it takes one hour to perfectly cook a one pound turkey in a given oven, how long would it take to cook a 2 pound turkey is the same oven ?</p>\n\n<p>Well, dimensional analysis shows </p>\n\n<p>(1) that the total amount of heat energy needed in order to cook the turkey is proportional to the mass of the turkey, which itself is proportional to its volume, which itself is proportional to the cube of it average \"radius\"<br>\ni.e<br>\nCooking heat energy needed = k1 * (turkeyRadius\" ^3) ==> unit : m^3 * k (where k1 unit is J / m^3)</p>\n\n<p>(2) That the total amount of heat energy provided by the oven is proportional to the surface of the turkey multiplied by the amount of time you cook it,<br>\ni.e<br>\nHeat provided by the oven = k2 * time * (turkeyRadius ^ 2) (where k2 unit is J / s / m^2 )</p>\n\n<p>Then by using (1) = (2) , you obtain<br>\ntime = k1 / k2 * turkeyRadius ^ (3/2) </p>\n\n<p>i.e<br>\n- the cooking time is proportionnal to the radius ^ 3/2<br>\n- given that turkeyRadius is proportionnal to the cubic root of the mass, we obtain<br>\n cooking time = k3 * sqrt(mass)</p>\n\n<p>So, it will take sqrt(2) times longer to cook our 2 pounds turkey, and the result is obtained with no calculation at all - only dimensional analysis.</p>\n"
},
{
"answer_id": 703532,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, F# is a great way to build on functional programming, just as Chris Smith said in his response. I am working on building an extensive discussion about physics, engineering and biology using F#. I could certainly use input from a student like yourself. Programming without a real life problem in mind is one way of programming. The other way that is successful is to provide solutions that are only used by people using computers, certainly another way to go and one that builds wealth.</p>\n\n<p>F# is made for knowledge domains like Physics.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
I hate Physics, but I love software development. When I go back to school after Thanksgiving, I'll be taking two more quarters of Physics before I'm done with the horrid thing. I am currently reading postings on the F# units of measurement feature, but I've never used a language like F#. Would it be suitable to write applications so I can perhaps learn something about Physics while doing something I like?
I'm interested in command-line applications (even those that I can just execute and have spit out an answer without needing inputs) for things like kinematics, planar motion, Newton's Laws, gravitation, work, energy, momentum and impulse, systems of particles, rotational kinematics and dynamics, angular momentum, static equilibrium, oscillatory motion, wave motion, sound, physical optics, electrostatics, Gauss' law, electric field and potential, capacitance, resistance, DC circuits, magnetic field, Ampere's law, and inductance.
The reason I'm interested in F# is because of the units of measure functionality that the language provides.
|
In my biased opinion, F# is ideal for physics. It has a feature called Units of Measure which does dimensional analysis for you, providing errors if you get it wrong. For example if you write:
```
let distance : float<meters> = gravity * 3.0<seconds>
```
That would **yield a compile-error**, since gravity is < meters/seconds^2 > and not < meters >. This prevents a great deal of physics-related programming errors.
For more information check out [Andrew Kennedy's blog](http://blogs.msdn.com/andrewkennedy/).
|
167,923 |
<p>This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern and return modified string.</p>
<p>Just to be clear...regex <code>.*Dog.*</code> would take </p>
<pre><code>Cat
Dog
My Dog
Her Dog
Mouse
</code></pre>
<p>and return </p>
<pre><code>Cat
Dog
::::: Pattern .*Dog.* repeats 2 more times.
Mouse
#!/usr/bin/env python
#
import re
import types
def remove_repeats (l_string, l_regex):
"""Take a string, remove similar lines and replace with a summary message.
l_regex accepts strings and tuples.
"""
# Convert string to tuple.
if type(l_regex) == types.StringType:
l_regex = l_regex,
for t in l_regex:
r = ''
p = ''
for l in l_string.splitlines(True):
if l.startswith('::::: Pattern'):
r = r + l
else:
if re.search(t, l): # If line matches regex.
m += 1
if m == 1: # If this is first match in a set of lines add line to file.
r = r + l
elif m > 1: # Else update the message string.
p = "::::: Pattern '" + t + "' repeats " + str(m-1) + ' more times.\n'
else:
if p: # Write the message string if it has value.
r = r + p
p = ''
m = 0
r = r + l
if p: # Write the message if loop ended in a pattern.
r = r + p
p = ''
l_string = r # Reset string to modified string.
return l_string
</code></pre>
|
[
{
"answer_id": 168009,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": true,
"text": "<p>The rematcher function seems to do what you want:</p>\n\n<pre><code>def rematcher(re_str, iterable):\n\n matcher= re.compile(re_str)\n in_match= 0\n for item in iterable:\n if matcher.match(item):\n if in_match == 0:\n yield item\n in_match+= 1\n else:\n if in_match > 1:\n yield \"%s repeats %d more times\\n\" % (re_str, in_match-1)\n in_match= 0\n yield item\n if in_match > 1:\n yield \"%s repeats %d more times\\n\" % (re_str, in_match-1)\n\nimport sys, re\n\nfor line in rematcher(\".*Dog.*\", sys.stdin):\n sys.stdout.write(line)\n</code></pre>\n\n<h1>EDIT</h1>\n\n<p>In your case, the final string should be:</p>\n\n<pre><code>final_string= '\\n'.join(rematcher(\".*Dog.*\", your_initial_string.split(\"\\n\")))\n</code></pre>\n"
},
{
"answer_id": 168052,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "<p>Updated your code to be a bit more effective</p>\n\n<pre><code>#!/usr/bin/env python\n#\n\nimport re\nimport types\n\ndef remove_repeats (l_string, l_regex):\n \"\"\"Take a string, remove similar lines and replace with a summary message.\n\n l_regex accepts strings/patterns or tuples of strings/patterns.\n \"\"\"\n\n # Convert string/pattern to tuple.\n if not hasattr(l_regex, '__iter__'):\n l_regex = l_regex,\n\n ret = []\n last_regex = None\n count = 0\n\n for line in l_string.splitlines(True):\n if last_regex:\n # Previus line matched one of the regexes\n if re.match(last_regex, line):\n # This one does too\n count += 1\n continue # skip to next line\n elif count > 1:\n ret.append(\"::::: Pattern %r repeats %d more times.\\n\" % (last_regex, count-1))\n count = 0\n last_regex = None\n\n ret.append(line)\n\n # Look for other patterns that could match\n for regex in l_regex:\n if re.match(regex, line):\n # Found one\n last_regex = regex\n count = 1\n break # exit inner loop\n\n return ''.join(ret)\n</code></pre>\n"
},
{
"answer_id": 1250162,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>First, your regular expression will match more slowly than if you had left off the greedy match.</p>\n\n<pre><code>.*Dog.*\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>Dog\n</code></pre>\n\n<p>but the latter matches more quickly because no backtracking is involved. The longer the strings, the more likely \"Dog\" appears multiple times and thus the more backtracking work the regex engine has to do. As it is, \".*D\" virtually guarantees backtracking.</p>\n\n<p>That said, how about:</p>\n\n<pre><code>#! /usr/bin/env python\n\nimport re # regular expressions\nimport fileinput # read from STDIN or file\n\nmy_regex = '.*Dog.*'\nmy_matches = 0\n\nfor line in fileinput.input():\n line = line.strip()\n\n if re.search(my_regex, line):\n if my_matches == 0:\n print(line)\n my_matches = my_matches + 1\n else:\n if my_matches != 0:\n print('::::: Pattern %s repeats %i more times.' % (my_regex, my_matches - 1))\n print(line)\n my_matches = 0\n</code></pre>\n\n<p>It's not clear what should happen with non-neighboring matches.</p>\n\n<p>It's also not clear what should happen with single-line matches surrounded by non-matching lines. Append \"Doggy\" and \"Hula\" to the input file and you'll get the matching message \"0\" more times.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4527/"
] |
This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern and return modified string.
Just to be clear...regex `.*Dog.*` would take
```
Cat
Dog
My Dog
Her Dog
Mouse
```
and return
```
Cat
Dog
::::: Pattern .*Dog.* repeats 2 more times.
Mouse
#!/usr/bin/env python
#
import re
import types
def remove_repeats (l_string, l_regex):
"""Take a string, remove similar lines and replace with a summary message.
l_regex accepts strings and tuples.
"""
# Convert string to tuple.
if type(l_regex) == types.StringType:
l_regex = l_regex,
for t in l_regex:
r = ''
p = ''
for l in l_string.splitlines(True):
if l.startswith('::::: Pattern'):
r = r + l
else:
if re.search(t, l): # If line matches regex.
m += 1
if m == 1: # If this is first match in a set of lines add line to file.
r = r + l
elif m > 1: # Else update the message string.
p = "::::: Pattern '" + t + "' repeats " + str(m-1) + ' more times.\n'
else:
if p: # Write the message string if it has value.
r = r + p
p = ''
m = 0
r = r + l
if p: # Write the message if loop ended in a pattern.
r = r + p
p = ''
l_string = r # Reset string to modified string.
return l_string
```
|
The rematcher function seems to do what you want:
```
def rematcher(re_str, iterable):
matcher= re.compile(re_str)
in_match= 0
for item in iterable:
if matcher.match(item):
if in_match == 0:
yield item
in_match+= 1
else:
if in_match > 1:
yield "%s repeats %d more times\n" % (re_str, in_match-1)
in_match= 0
yield item
if in_match > 1:
yield "%s repeats %d more times\n" % (re_str, in_match-1)
import sys, re
for line in rematcher(".*Dog.*", sys.stdin):
sys.stdout.write(line)
```
EDIT
====
In your case, the final string should be:
```
final_string= '\n'.join(rematcher(".*Dog.*", your_initial_string.split("\n")))
```
|
167,954 |
<p>So I build an array of various dates. Birthdays, anniversaries, and holidays. I'd like to order the array by which one is happening next, essentially sort October to September (wrapping to next year)</p>
<p>so if my array is </p>
<pre><code>$a = ([0]=>"1980-04-14", [1]=>"2007-06-08",
[2]=>"2008-12-25", [3]=>"1978-11-03")
</code></pre>
<p>I'd like to sort it so it is arranged</p>
<pre><code>$a = ([0]=>"1978-11-03", [1]=>"2008-12-25",
[2]=>"1980-04-14", [3]=>"2007-06-08")
</code></pre>
<p>because the november 'event' is the one that will happen next (based on it being october right now).</p>
<p>I'm trying usort where my cmp function is </p>
<pre><code>function cmp($a, $b)
{
$a_tmp = split("-", $a);
$b_tmp = split("-", $b);
return strcmp($a_tmp[1], $b_tmp[1]);
}
</code></pre>
<p>I am not sure how to modify this to get my desired effect.</p>
|
[
{
"answer_id": 167995,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": -1,
"selected": false,
"text": "<p>Don't compare strings, instead use seconds since 1970 (ints):</p>\n\n<pre><code>$date1 = split(\"-\", $a);\n$date2 = split(\"-\", $b);\n$seconds1 = mktime(0,0,0,$date1[1],$date1[2],$date1[0]);\n$seconds2 = mktime(0,0,0,$date2[1],$date2[2],$date2[0]);\n// eliminate years\n$seconds1 %= 31536000;\n$seconds2 %= 31536000;\nreturn $seconds1 - $seconds2;\n</code></pre>\n\n<p>Also I don't know PHP but I think the gist is correct.</p>\n\n<p>Edit: The comparison function is encapsulated to perform comparison, nothing more. To order a list in regards to the original question sort an array with today's date included, locate today's date in the array, and then move the elements before that position to the end in ascending order by position.</p>\n"
},
{
"answer_id": 168002,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "<p>I would be tempted to establish the original year of the event, and then add enough whole years to it to ensure that the value is greater than your reference date (normally today's date). Or, possibly, greater than or equal to the reference date. You can then sort in simple date order.</p>\n\n<p><strong>Edited to add</strong>:</p>\n\n<p>I'm not fluent enough in PHP to give an answer in that, but here's a Perl solution.</p>\n\n<pre><code>#!/bin/perl -w\n\n# Sort sequence of dates by next occurrence of anniversary.\n# Today's \"birthdays\" count as low (will appear first in sequence)\n\nuse strict;\n\nmy $refdate = \"2008-10-05\";\n\nmy @list = (\n \"1980-04-14\", \"2007-06-08\",\n \"2008-12-25\", \"1978-11-03\",\n \"2008-10-04\", \"2008-10-05\",\n \"2008-10-06\", \"2008-02-29\"\n);\n\nsub date_on_or_after\n{\n my($actdate, $refdate) = @_;\n my($answer) = $actdate;\n if ($actdate lt $refdate) # String compare OK with ISO8601 format\n {\n my($act_yy, $act_mm, $act_dd) = split /-/, $actdate;\n my($ref_yy, $ref_mm, $ref_dd) = split /-/, $refdate;\n $ref_yy++ if ($act_mm < $ref_mm || ($act_mm == $ref_mm && $act_dd < $ref_dd));\n $answer = \"$ref_yy-$act_mm-$act_dd\";\n }\n return $answer;\n}\n\nsub anniversary_compare\n{\n my $r1 = date_on_or_after($a, $refdate);\n my $r2 = date_on_or_after($b, $refdate);\n return $r1 cmp $r2;\n}\n\nmy @result = sort anniversary_compare @list;\n\nprint \"Before:\\n\";\nprint \"* $_\\n\" foreach (@list);\nprint \"Reference date: $refdate\\n\";\nprint \"After:\\n\";\nprint \"* $_\\n\" foreach (@result);\n</code></pre>\n\n<p>Clearly, this is not dreadfully efficient - to make it efficient, you'd calculate the date_on_or_after() value once, and then sort on those values. Perl's comparison is slightly peculiar - the variables $a and $b are magic, and appear as if out of nowhere.</p>\n\n<p>When run, the script produces:</p>\n\n<pre><code>Before:\n* 1980-04-14\n* 2007-06-08\n* 2008-12-25\n* 1978-11-03\n* 2008-10-04\n* 2008-10-05\n* 2008-10-06\n* 2008-02-29\nReference date: 2008-10-05\nAfter:\n* 2008-10-05\n* 2008-10-06\n* 1978-11-03\n* 2008-12-25\n* 2008-02-29\n* 1980-04-14\n* 2007-06-08\n* 2008-10-04\n</code></pre>\n\n<p>Note that it largely ducks the issue of what happens with the 29th of February, because it 'works' to do so. Basically, it will generate the 'date' 2009-02-29, which compares correctly in sequence. The anniversary for 2000-02-28 would be listed before the anniversary for 2008-02-29 (if 2000-02-28 were included in the data).</p>\n"
},
{
"answer_id": 168010,
"author": "Jack B Nimble",
"author_id": 3800,
"author_profile": "https://Stackoverflow.com/users/3800",
"pm_score": 0,
"selected": false,
"text": "<p>So it occured to me just to add 12 to any month that is less than my target month.\nWhich is now working.</p>\n\n<p>so the final function</p>\n\n<pre><code>function cmp($a, $b)\n{\n $a_tmp = explode('-', $a['date']);\n $b_tmp = explode('-', $b['date']);\n if ($a_tmp[1] < date('m')) {\n $a_tmp[1] += 12;\n }\n if ($b_tmp[1] < date('m')) {\n $b_tmp[1] += 12;\n }\n return strcmp($a_tmp[1] . $a_tmp[2], $b_tmp[1] . $b_tmp[2]);\n} \n</code></pre>\n"
},
{
"answer_id": 168079,
"author": "Neil Williams",
"author_id": 9617,
"author_profile": "https://Stackoverflow.com/users/9617",
"pm_score": 3,
"selected": true,
"text": "<pre><code>function relative_year_day($date) {\n $value = date('z', strtotime($date)) - date('z');\n\n if ($value < 0)\n $value += 365;\n\n return $value;\n}\n\nfunction cmp($a, $b)\n{\n $aValue = relative_year_day($a);\n $bValue = relative_year_day($b);\n\n if ($aValue == $bValue)\n return 0;\n\n return ($aValue < $bValue) ? -1 : 1;\n}\n\n$a = array(\"1980-04-14\", \"2007-06-08\",\n \"2008-12-25\", \"1978-11-03\");\n\nusort($a, \"cmp\");\n</code></pre>\n"
},
{
"answer_id": 168086,
"author": "JimmyJ",
"author_id": 2083,
"author_profile": "https://Stackoverflow.com/users/2083",
"pm_score": 0,
"selected": false,
"text": "<p>use strtotime() to convert the all dates to a timestamp before you add them to the array, then you can sort the array into ascending (also chronological) order. Now all you have to do is deal with the dates in the past which is easily done by comparing them against a current timestamp</p>\n\n<p>i.e.</p>\n\n<pre><code>for ($i=0; $i<count($a); $i++){\n if ($currentTimestamp > $a[$i]){\n unset($a[$i]);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 180063,
"author": "gradbot",
"author_id": 17919,
"author_profile": "https://Stackoverflow.com/users/17919",
"pm_score": 0,
"selected": false,
"text": "<p>No reason to reinvent the wheel. If you don't care about the keys you can use this.</p>\n\n<pre><code>$a = array_combine(array_map('strtotime', $a), $a);\nksort($a);\n</code></pre>\n\n<p>Or if you want to define your own callback.</p>\n\n<pre><code>function dateCmp($date1, $date2) {\n return (strtotime($date1) > strtotime($date2))?1:-1;\n}\n\nusort($a, 'dateCmp');\n</code></pre>\n\n<p>If you want to keep the keys associated correctly just call uasort instead.</p>\n\n<pre><code>uasort($a, 'dateCmp');\n</code></pre>\n\n<p>I did a quick speed check and the callback functions were over a magnitude slower.</p>\n"
}
] |
2008/10/03
|
[
"https://Stackoverflow.com/questions/167954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3800/"
] |
So I build an array of various dates. Birthdays, anniversaries, and holidays. I'd like to order the array by which one is happening next, essentially sort October to September (wrapping to next year)
so if my array is
```
$a = ([0]=>"1980-04-14", [1]=>"2007-06-08",
[2]=>"2008-12-25", [3]=>"1978-11-03")
```
I'd like to sort it so it is arranged
```
$a = ([0]=>"1978-11-03", [1]=>"2008-12-25",
[2]=>"1980-04-14", [3]=>"2007-06-08")
```
because the november 'event' is the one that will happen next (based on it being october right now).
I'm trying usort where my cmp function is
```
function cmp($a, $b)
{
$a_tmp = split("-", $a);
$b_tmp = split("-", $b);
return strcmp($a_tmp[1], $b_tmp[1]);
}
```
I am not sure how to modify this to get my desired effect.
|
```
function relative_year_day($date) {
$value = date('z', strtotime($date)) - date('z');
if ($value < 0)
$value += 365;
return $value;
}
function cmp($a, $b)
{
$aValue = relative_year_day($a);
$bValue = relative_year_day($b);
if ($aValue == $bValue)
return 0;
return ($aValue < $bValue) ? -1 : 1;
}
$a = array("1980-04-14", "2007-06-08",
"2008-12-25", "1978-11-03");
usort($a, "cmp");
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.