qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
59,425 |
<p>I'm using MySQL in particular, but I'm hoping for a cross-vendor solution. I'm using the NOW() function to add a timestamp as a column for each record.</p>
<pre><code>INSERT INTO messages
(typeId, messageTime, stationId, message)
VALUES
(?, NOW(), ?, ?)
</code></pre>
|
[
{
"answer_id": 59437,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 3,
"selected": true,
"text": "SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= messageTime\n"
},
{
"answer_id": 59443,
"author": "Martynnw",
"author_id": 5466,
"author_profile": "https://Stackoverflow.com/users/5466",
"pm_score": 2,
"selected": false,
"text": "Select *\nFrom Messages\nWhere MessageTime > DateAdd(dd, -1, GetDate())\n Select *\nFrom Messages\nWhere MessageTime > ADDDATE(NOW(), INTERVAL -1 DAY)\n"
},
{
"answer_id": 59459,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "PostgreSQL SELECT * FROM messages WHERE messagetime >= messagetime - interval '1 day'\n"
},
{
"answer_id": 59470,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 1,
"selected": false,
"text": "Select * From Messages Where MessageTime > dateadd( day, -1, now() )\n"
},
{
"answer_id": 59508,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM messages WHERE messageTime > SYSDATE - 1\n"
},
{
"answer_id": 59532,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "PreparedStatement stmt = connection.prepareStatement( \n \"INSERT INTO messages \" +\n \"(typeId, messageTime, stationId, message) VALUES \" +\n \"(?, ?, ?, ?)\" );\nstmt.setInt(1, typeId);\nstmt.setDate(2, new java.sql.Date(System.currentTimeMillis()));\nstmt.setInt(3, stationId);\nstmt.setString(4, message);\n PrepatedStatement stmt = connection.prepareStatement(\n \"SELECT typeId, messageTime, stationId, message \" +\n \"from messages where messageTime < ?\");\nlong yesterday = System.currentTimeMillis() - 86400000; // 86400 sec/day\nstmt.setDate(1,new java.sql.Date(yesterday));\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
59,444 |
<p>Is there a system stored procedure to get the version #?</p>
|
[
{
"answer_id": 59457,
"author": "Joe Kuemerle",
"author_id": 4273,
"author_profile": "https://Stackoverflow.com/users/4273",
"pm_score": 9,
"selected": true,
"text": "SELECT @@VERSION \n SELECT SERVERPROPERTY('productversion')\n , SERVERPROPERTY('productlevel')\n , SERVERPROPERTY('edition')\n"
},
{
"answer_id": 510741,
"author": "Bruce Chapman",
"author_id": 174730,
"author_profile": "https://Stackoverflow.com/users/174730",
"pm_score": 2,
"selected": false,
"text": "declare @isSqlServer2005 bit\nselect @isSqlServer2005 = case when CONVERT(int, SUBSTRING(CONVERT(varchar(15), SERVERPROPERTY('productversion')), 0, CHARINDEX('.', CONVERT(varchar(15), SERVERPROPERTY('productversion'))))) < 9 then 0 else 1 end\nselect @isSqlServer2005\n"
},
{
"answer_id": 3178966,
"author": "freak",
"author_id": 383595,
"author_profile": "https://Stackoverflow.com/users/383595",
"pm_score": 1,
"selected": false,
"text": "if (SELECT LEFT(CAST(SERVERPROPERTY('productversion') as varchar), 2)) = '10'\nBEGIN\n"
},
{
"answer_id": 6454881,
"author": "Geoff",
"author_id": 55487,
"author_profile": "https://Stackoverflow.com/users/55487",
"pm_score": 4,
"selected": false,
"text": "declare @sqlVers numeric(4,2)\nselect @sqlVers = left(cast(serverproperty('productversion') as varchar), 4)\n"
},
{
"answer_id": 14390702,
"author": "Mark Kram",
"author_id": 100283,
"author_profile": "https://Stackoverflow.com/users/100283",
"pm_score": 5,
"selected": false,
"text": "DECLARE @ver nvarchar(128)\nSET @ver = CAST(serverproperty('ProductVersion') AS nvarchar)\nSET @ver = SUBSTRING(@ver, 1, CHARINDEX('.', @ver) - 1)\n\nIF ( @ver = '7' )\n SELECT 'SQL Server 7'\nELSE IF ( @ver = '8' )\n SELECT 'SQL Server 2000'\nELSE IF ( @ver = '9' )\n SELECT 'SQL Server 2005'\nELSE IF ( @ver = '10' )\n SELECT 'SQL Server 2008/2008 R2'\nELSE IF ( @ver = '11' )\n SELECT 'SQL Server 2012'\nELSE IF ( @ver = '12' )\n SELECT 'SQL Server 2014'\nELSE IF ( @ver = '13' )\n SELECT 'SQL Server 2016'\nELSE IF ( @ver = '14' )\n SELECT 'SQL Server 2017'\nELSE\n SELECT 'Unsupported SQL Server Version'\n"
},
{
"answer_id": 16571275,
"author": "crosswalk",
"author_id": 236423,
"author_profile": "https://Stackoverflow.com/users/236423",
"pm_score": 1,
"selected": false,
"text": "SELECT \n@@SERVERNAME AS ServerName,\nCASE WHEN LEFT(CAST(serverproperty('productversion') as char), 1) = 9 THEN '2005'\n WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 10 THEN '2008'\n WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 11 THEN '2012'\nEND AS MajorVersion,\nSERVERPROPERTY ('productlevel') AS MinorVersion, \nSERVERPROPERTY('productversion') AS FullVersion, \nSERVERPROPERTY ('edition') AS Edition\n"
},
{
"answer_id": 23385767,
"author": "Nux",
"author_id": 333296,
"author_profile": "https://Stackoverflow.com/users/333296",
"pm_score": 1,
"selected": false,
"text": "SELECT SUBSTRING(ver, 1, CHARINDEX('.', ver) - 1)\nFROM (SELECT CAST(serverproperty('ProductVersion') AS nvarchar) ver) as t\n 8 9"
},
{
"answer_id": 25188612,
"author": "Zia",
"author_id": 3919450,
"author_profile": "https://Stackoverflow.com/users/3919450",
"pm_score": 2,
"selected": false,
"text": "exec [master].sys.[xp_msver]\n"
},
{
"answer_id": 26818437,
"author": "Alex",
"author_id": 2397221,
"author_profile": "https://Stackoverflow.com/users/2397221",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION dbo.UFN_GET_SQL_SEVER_VERSION \n(\n)\nRETURNS sysname\nAS\nBEGIN\n DECLARE @ServerVersion sysname, @ProductVersion sysname, @ProductLevel sysname, @Edition sysname;\n\n SELECT @ProductVersion = CONVERT(sysname, SERVERPROPERTY('ProductVersion')), \n @ProductLevel = CONVERT(sysname, SERVERPROPERTY('ProductLevel')),\n @Edition = CONVERT(sysname, SERVERPROPERTY ('Edition'));\n --see: http://support2.microsoft.com/kb/321185\n SELECT @ServerVersion = \n CASE \n WHEN @ProductVersion LIKE '8.00.%' THEN 'Microsoft SQL Server 2000'\n WHEN @ProductVersion LIKE '9.00.%' THEN 'Microsoft SQL Server 2005'\n WHEN @ProductVersion LIKE '10.00.%' THEN 'Microsoft SQL Server 2008'\n WHEN @ProductVersion LIKE '10.50.%' THEN 'Microsoft SQL Server 2008 R2'\n WHEN @ProductVersion LIKE '11.0%' THEN 'Microsoft SQL Server 2012'\n WHEN @ProductVersion LIKE '12.0%' THEN 'Microsoft SQL Server 2014'\n END\n\n RETURN @ServerVersion + N' ('+@ProductLevel + N'), ' + @Edition + ' - ' + @ProductVersion;\n\nEND\nGO\n"
},
{
"answer_id": 35787064,
"author": "pruthvi",
"author_id": 6016258,
"author_profile": "https://Stackoverflow.com/users/6016258",
"pm_score": -1,
"selected": false,
"text": "SELECT\n 'the sqlserver is ' + substring(@@VERSION, 21, 5) AS [sql version]\n"
},
{
"answer_id": 40177596,
"author": "Allen Ackerman",
"author_id": 7053303,
"author_profile": "https://Stackoverflow.com/users/7053303",
"pm_score": 1,
"selected": false,
"text": "SELECT left(ltrim(replace(@@Version,'Microsoft SQL Server','')),4)"
},
{
"answer_id": 42291858,
"author": "Arif",
"author_id": 7579331,
"author_profile": "https://Stackoverflow.com/users/7579331",
"pm_score": 0,
"selected": false,
"text": "SELECT @@VERSION[server], SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')\n"
},
{
"answer_id": 43767263,
"author": "VAV",
"author_id": 1921460,
"author_profile": "https://Stackoverflow.com/users/1921460",
"pm_score": 1,
"selected": false,
"text": "SELECT @@MICROSOFTVERSION / 0x01000000 AS MajorVersionNumber\n"
},
{
"answer_id": 49512753,
"author": "Vikrant Bagal",
"author_id": 5426308,
"author_profile": "https://Stackoverflow.com/users/5426308",
"pm_score": 1,
"selected": false,
"text": "select substring(@@version,0,charindex(convert(varchar,SERVERPROPERTY('productversion')) ,@@version)+len(convert(varchar,SERVERPROPERTY('productversion')))) \n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
59,451 |
<p>How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.</p>
<p>Edit: Here's the code I'm now using this for, based on the answer from Santiago below.</p>
<pre><code>public DataTemplate Create(Type type)
{
return (DataTemplate)XamlReader.Load(
@"<DataTemplate
xmlns=""http://schemas.microsoft.com/client/2007"">
<" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
</DataTemplate>"
);
}
</code></pre>
<p>This works really nicely and allows me to change the binding on the fly. </p>
|
[
{
"answer_id": 72158,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": " public static DataTemplate Create(Type type)\n {\n return (DataTemplate) XamlReader.Load(\n @\"<DataTemplate\n xmlns=\"\"http://schemas.microsoft.com/client/2007\"\">\n <\" + type.Name + @\"/>\n </DataTemplate>\"\n );\n }\n"
},
{
"answer_id": 356064,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "private DataTemplate Create(Type type)\n {\n string xaml = @\"<DataTemplate \n xmlns=\"\"http://schemas.microsoft.com/client/2007\"\"\n xmlns:controls=\"\"clr-namespace:\" + type.Namespace + @\";assembly=\" + type.Namespace + @\"\"\">\n <controls:\" + type.Name + @\"/></DataTemplate>\";\n return (DataTemplate)XamlReader.Load(xaml);\n }\n"
},
{
"answer_id": 7101581,
"author": "Davut Gürbüz",
"author_id": 413032,
"author_profile": "https://Stackoverflow.com/users/413032",
"pm_score": 2,
"selected": false,
"text": " <ResourceDictionary>\n <DataTemplate x:Key=\"TextBoxEditTemplate\">\n <Some user control x:Name=\"myOwnControl\" />\n </DataTemplate>\n </ResourceDictionary>\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
] |
59,456 |
<p>I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item.</p>
<p>Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, _File</p>
<p>However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following?</p>
<pre><code><Menu>
<MenuItem>
<MenuItem.Header>
<UserControl>
<Image Source="..." />
<Label Text="_Open" />
</UserControl>
</MenuItem.Header>
</MenuItem>
...
</code></pre>
|
[
{
"answer_id": 59706,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 2,
"selected": false,
"text": "<MenuItem Header=\"_Open\">\n <MenuItem.Icon>\n <Image Source=\"images/Open.png\"/>\n </MenuItem.Icon>\n</MenuItem>\n"
},
{
"answer_id": 60365,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": true,
"text": " <Menu> \n <MenuItem>\n <MenuItem.Header>\n <StackPanel Orientation=\"Horizontal\">\n <Image Source=\"Images/Open.ico\" /> \n <AccessText>_Open..</AccessText>\n </StackPanel>\n </MenuItem.Header>\n </MenuItem>\n <MenuItem Header=\"_Close\" />\n </Menu>\n"
},
{
"answer_id": 1108605,
"author": "awe",
"author_id": 109392,
"author_profile": "https://Stackoverflow.com/users/109392",
"pm_score": 2,
"selected": false,
"text": "<MenuItem Name=\"LanguageMenu\" Header=\"_Language\" Click=\"LanguageMenu_Click\">\n <MenuItem.Icon>\n <Button Click=\"Button_Click\">i</Button>\n </MenuItem.Icon>\n</MenuItem>\n < < <MenuItem Name=\"mnuFileSave\" Header=\"Save\" Command=\"ApplicationCommands.Save\">\n <MenuItem.Icon>\n <Label VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" \n FontFamily=\"Wingdings\"><</Label>\n </MenuItem.Icon> \n</MenuItem>\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483/"
] |
59,465 |
<p>By default the webjump hotlist has the following which I use quite often:</p>
<pre><code>M-x webjump RET Google
M-x webjump RET Wikipedia
</code></pre>
<p>How can I add 'Stackoverflow' to my list?</p>
|
[
{
"answer_id": 59476,
"author": "Marcel Levy",
"author_id": 676,
"author_profile": "https://Stackoverflow.com/users/676",
"pm_score": 2,
"selected": true,
"text": ";; (require 'webjump)\n;; (global-set-key \"\\C-cj\" 'webjump)\n;; (setq webjump-sites\n;; (append '(\n;; (\"My Home Page\" . \"www.someisp.net/users/joebobjr/\")\n;; (\"Pop's Site\" . \"www.joebob-and-son.com/\")\n;; )\n;; webjump-sample-sites))\n"
},
{
"answer_id": 151984,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 2,
"selected": false,
"text": "webjump-sites .emacs (\"stackoverflow\". \"www.stackoverflow.com\")\n (setq webjump-sites\n (append '((\"stackoverflow\" . \"www.stackoverflow.com\"))\n webjump-sample-sites)\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
59,483 |
<pre><code>1167 ptr = (void*)getcwd(cwd, MAX_PATH_LENGTH-1);
(gdb) n
1168 if (!ptr) {
(gdb) print ptr
$1 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa"
(gdb) print &cwd
$2 = (char (*)[3500]) 0xbff2d96c
(gdb) print strlen(cwd)
$3 = 36
(gdb) print "%s",cwd
$4 = "/media/MMC-SD/partition1/aaaaaaaaaaa", '\0' <repeats 912 times>, "��O�001\000\000\000\000��027\000\000\000�3����EL鷠3�000��027\000\000\000\000\000\000\000\027\000\000\000\000��/�027\000\000\000�3����N����\230���鷠3�000��027\000\000\000\000\000\000\000��000\000\000\000\001\000\000\000��M鷠3����\000\000\000\000.\231�027��w\005\b\001\000"...
(gdb) print "%s", ptr
$5 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa"
(gdb) Quit
</code></pre>
<p>Why is ptr printing the string correctly but cwd not; this also affects the program and it crashes if I try to use the cwd...</p>
<p>[edit: turns out that crash was caused by a stupid buffer overflow on this var... grr...not gdb, but the print question was still valid]</p>
|
[
{
"answer_id": 59509,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 1,
"selected": false,
"text": "ptr cwd man 3 getcwd ptr cwd ptr"
},
{
"answer_id": 59517,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 3,
"selected": true,
"text": "cwd gdb gdb ptr char * cwd 3500 ptr cwd cwd ptr"
},
{
"answer_id": 59553,
"author": "Eric Hansander",
"author_id": 5039,
"author_profile": "https://Stackoverflow.com/users/5039",
"pm_score": 3,
"selected": false,
"text": "(gdb) print cwd\n$1 = \"/media\", '\\0' <repeats 782 times>, \"\\016���\" ...\n(gdb) print (char*) cwd\n$2 = 0xbfc8eb84 \"/media\"\n cwd char cwd[3500] char*"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5330/"
] |
59,515 |
<p>I am new to all the anonymous features and need some help. I have gotten the following to work:</p>
<pre><code>public void FakeSaveWithMessage(Transaction t)
{
t.Message = "I drink goats blood";
}
public delegate void FakeSave(Transaction t);
public void SampleTestFunction()
{
Expect.Call(delegate { _dao.Save(t); }).Do(new FakeSave(FakeSaveWithMessage));
}
</code></pre>
<p>But this is totally ugly and I would like to have the inside of the Do to be an anonymous method or even a lambda if it is possible. I tried:</p>
<pre><code>Expect.Call(delegate { _dao.Save(t); }).Do(delegate(Transaction t2) { t2.Message = "I drink goats blood"; });
</code></pre>
<p>and</p>
<pre><code>Expect.Call(delegate { _dao.Save(t); }).Do(delegate { t.Message = "I drink goats blood"; });
</code></pre>
<p>but these give me</p>
<blockquote>
<p>Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type** compile errors.</p>
</blockquote>
<p>What am I doing wrong?</p>
<hr>
<p>Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:</p>
<pre><code>public delegate void FakeSave(Transaction t);
Expect.Call(delegate { _dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.Message = expected_msg; }));
</code></pre>
|
[
{
"answer_id": 59531,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 0,
"selected": false,
"text": "Expect.Call(delegate { _dao.Save(t); }).Do(new EventHandler(delegate(Transaction t2) { t2.CheckInInfo.CheckInMessage = \"I drink goats blood\"; }));\n public delegate void UnitTestingDelegate<T>(T thing);\n"
},
{
"answer_id": 59551,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 6,
"selected": true,
"text": "private void MyMethod()\n{\n}\n 1) Delegate d = delegate() { }; // Cannot convert anonymous method to type ‘System.Delegate’ because it is not a delegate type\n2) Delegate d2 = MyMethod; // Cannot convert method group ‘MyMethod’ to non-delegate type ‘System.Delegate’\n3) Delegate d3 = (WaitCallback)MyMethod; // No overload for ‘MyMethod’ matches delegate ‘System.Threading.WaitCallback’\n 4) Delegate d4 = (MethodInvoker)MyMethod; // Works because we cast to a delegate type of the same signature.\n5) Delegate d5 = (Action)delegate { }; // Works for same reason as d4.\n6) Action d6 = MyMethod; // Delegate inference at work here. New Action delegate is created and assigned.\n"
},
{
"answer_id": 59611,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 1,
"selected": false,
"text": "Expect.Call(delegate { _dao.Save(t); }).Do((Delegate)delegate { t.Message = \"I drink goats blood\"; });\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
59,544 |
<p>I have the following tables, the <code>groups</code> table which contains hierarchically ordered groups and <code>group_member</code> which stores which groups a user belongs to. </p>
<pre><code>groups
---------
id
parent_id
name
group_member
---------
id
group_id
user_id
ID PARENT_ID NAME
---------------------------
1 NULL Cerebra
2 1 CATS
3 2 CATS 2.0
4 1 Cerepedia
5 4 Cerepedia 2.0
6 1 CMS
ID GROUP_ID USER_ID
---------------------------
1 1 3
2 1 4
3 1 5
4 2 7
5 2 6
6 4 6
7 5 12
8 4 9
9 1 10
</code></pre>
<p>I want to retrieve the visible groups for a given user. That it is to say groups a user belongs to and children of these groups. For example, with the above data: </p>
<pre><code>USER VISIBLE_GROUPS
9 4, 5
3 1,2,4,5,6
12 5
</code></pre>
<p>I am getting these values using recursion and several database queries. But I would like to know if it is possible to do this with a single SQL query to improve my app performance. I am using MySQL. </p>
|
[
{
"answer_id": 59632,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 0,
"selected": false,
"text": "SELECT GroupUsers.User_ID,\n (\n SELECT \n STUFF((SELECT ',' + \n Cast(Group_ID As Varchar(10))\n FROM Group_Member Member (nolock) \n WHERE Member.User_ID=GroupUsers.User_ID\n FOR XML PATH('')),1,1,'') \n ) As Groups\nFROM (SELECT User_ID FROM Group_Member GROUP BY User_ID) GroupUsers\n User_ID Groups\n3 1\n4 1\n5 1\n6 2,4\n7 2\n9 4\n10 1\n12 5\n"
},
{
"answer_id": 59765,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": -1,
"selected": false,
"text": "CONNECT BY"
},
{
"answer_id": 59767,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 3,
"selected": false,
"text": "SELECT *\nFROM\n MY_GROUPS MG1\n ,MY_GROUPS MG2\n ,MY_GROUPS MG3\n ,MY_GROUPS MG4\n ,MY_GROUPS MG5\n ,MY_GROUP_MEMBERS MGM\nWHERE MG1.PARENT_ID = MG2.UNIQID (+)\n AND MG1.UNIQID = MGM.GROUP_ID (+)\n AND MG2.PARENT_ID = MG3.UNIQID (+)\n AND MG3.PARENT_ID = MG4.UNIQID (+)\n AND MG4.PARENT_ID = MG5.UNIQID (+)\n AND MGM.USER_ID = 9\n UNIQID PARENT_ID NAME UNIQID_1 PARENT_ID_1 NAME_1 UNIQID_2 PARENT_ID_2 NAME_2 UNIQID_3 PARENT_ID_3 NAME_3 UNIQID_4 PARENT_ID_4 NAME_4 UNIQID_5 GROUP_ID USER_ID\n4 2 Cerepedia 2 1 CATS 1 null Cerebra null null null null null null 8 4 9\n CREATE OR REPLACE FUNCTION GoUpLevel(WO_ID INTEGER, UPLEVEL INTEGER) RETURN INTEGER\nIS\nBEGIN\n DECLARE\n iResult INTEGER;\n iParent INTEGER;\nBEGIN\n IF UPLEVEL <= 0 THEN\n iResult := WO_ID;\n ELSE\n SELECT PARENT_ID\n INTO iParent\n FROM WOTREE\n WHERE ID = WO_ID; \n iResult := GoUpLevel(iParent,UPLEVEL-1); --recursive\n END;\n RETURN iResult;\n EXCEPTION WHEN NO_DATA_FOUND THEN\n RETURN NULL;\n END;\nEND GoUpLevel;\n/\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
59,557 |
<p>is there an easy way to transform HTML into markdown with JAVA?</p>
<p>I am currently using the Java <strong><a href="http://code.google.com/p/markdownj/" rel="noreferrer">MarkdownJ</a></strong> library to transform markdown to html.</p>
<pre><code>import com.petebevin.markdown.MarkdownProcessor;
...
public static String getHTML(String markdown) {
MarkdownProcessor markdown_processor = new MarkdownProcessor();
return markdown_processor.markdown(markdown);
}
public static String getMarkdown(String html) {
/* TODO Ask stackoverflow */
}
</code></pre>
|
[
{
"answer_id": 741062,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "wmd.js wmd_options = {\n // format sent to the server. can also be \"HTML\"\n output: \"Markdown\",\n\n // line wrapping length for lists, blockquotes, etc.\n lineLength: 40,\n\n // toolbar buttons. Undo and redo get appended automatically.\n buttons: \"bold italic | link blockquote code image | ol ul heading hr\",\n\n // option to automatically add WMD to the first textarea found.\n autostart: true\n };\n"
},
{
"answer_id": 62105480,
"author": "Gabriel Furstenheim",
"author_id": 1536133,
"author_profile": "https://Stackoverflow.com/users/1536133",
"pm_score": 4,
"selected": false,
"text": "dependencies {\n compile 'io.github.furstenheim:copy_down:1.0'\n}\n CopyDown converter = new CopyDown();\nString myHtml = \"<h1>Some title</h1><div>Some html<p>Another paragraph</p></div>\";\nString markdown = converter.convert(myHtml);\nSystem.out.println(markdown);\n> Some title\\n==========\\n\\nSome html\\n\\nAnother paragraph\\n\n"
},
{
"answer_id": 70212129,
"author": "Mahozad",
"author_id": 8583692,
"author_profile": "https://Stackoverflow.com/users/8583692",
"pm_score": 0,
"selected": false,
"text": "var command = \"pandoc --to=markdown_strict --output=result.md input.html\";\nvar pandoc = new ProcessBuilder()\n .command(command.split(\" \"))\n .directory(new File(\".\")) // Working directory\n .start();\npandoc.waitFor();\n// The output result.md will be created in the working directory\n"
},
{
"answer_id": 72139380,
"author": "Fabian Sponholz",
"author_id": 19051614,
"author_profile": "https://Stackoverflow.com/users/19051614",
"pm_score": 2,
"selected": false,
"text": "<dependency>\n <groupId>com.vladsch.flexmark</groupId>\n <artifactId>flexmark-html2md-converter</artifactId>\n <version>0.64.0</version>\n</dependency>\n com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter String md = FlexmarkHtmlConverter.builder().build().convert(html);\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
59,560 |
<p>Of all the forms of CAPTCHA available, which one is the "least crackable" while remaining fairly human readable?</p>
|
[
{
"answer_id": 24972337,
"author": "ZeroBased_IX",
"author_id": 1888402,
"author_profile": "https://Stackoverflow.com/users/1888402",
"pm_score": 2,
"selected": false,
"text": "If honeypotfield <> Empty Then\n \"No Spam TY\"\nElse \n //Proceed with the form \nEnd If\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287/"
] |
59,599 |
<p>I have a large classic ASP app that I have to maintain, and I repeatedly find myself thwarted by the lack of short-circuit evaluation capability. E.g., VBScript won't let you get away with:</p>
<pre><code>if not isNull(Rs("myField")) and Rs("myField") <> 0 then
...
</code></pre>
<p>...because if Rs("myField") is null, you get an error in the second condition, comparing null to 0. So I'll typically end up doing this instead:</p>
<pre><code>dim myField
if isNull(Rs("myField")) then
myField = 0
else
myField = Rs("myField")
end if
if myField <> 0 then
...
</code></pre>
<p>Obviously, the verboseness is pretty appalling. Looking around this large code base, the best workaround I've found is to use a function the original programmer wrote, called TernaryOp, which basically grafts in ternary operator-like functionality, but I'm still stuck using a temporary variable that would not be necessary in a more full-featured language. Is there a better way? Some super-secret way that short-circuiting really does exist in VBScript?</p>
|
[
{
"answer_id": 59606,
"author": "busse",
"author_id": 5702,
"author_profile": "https://Stackoverflow.com/users/5702",
"pm_score": 3,
"selected": false,
"text": "if not isNull(Rs(\"myField\")) Then\n if Rs(\"myField\") <> 0 then\n"
},
{
"answer_id": 59618,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 4,
"selected": true,
"text": "if cint( getVal( rs(\"blah\"), \"\" ) )<> 0 then\n 'do something\nend if\n\n\nfunction getVal( v, replacementVal )\n if v is nothing then\n getVal = replacementVal\n else\n getVal = v\n end if\nend function\n"
},
{
"answer_id": 59631,
"author": "Marshall",
"author_id": 1302,
"author_profile": "https://Stackoverflow.com/users/1302",
"pm_score": 1,
"selected": false,
"text": "function ReplaceNull(s)\n if IsNull(s) or s = \"\" then\n ReplaceNull = \" \"\n else\n ReplaceNull = s\n end if\nend function\n"
},
{
"answer_id": 59693,
"author": "dewde",
"author_id": 2640,
"author_profile": "https://Stackoverflow.com/users/2640",
"pm_score": 3,
"selected": false,
"text": "Select Case True\n\nCase isNull(Rs(\"myField\"))\n\n myField = 0\n\nCase (Rs(\"myField\") <> 0)\n\n myField = Rs(\"myField\")\n\nCase Else\n\n myField = -1 \n\nEnd Select\n"
},
{
"answer_id": 139545,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 0,
"selected": false,
"text": "len() lenb() if not lenb(rs(\"myField\"))=0 then...\n if not isNothing(rs(\"myField\")) then...\n isNothing() function isNothing(vInput)\n isNothing = false : vInput = trim(vInput)\n if vartype(vInput)=0 or isEmpty(vInput) or isNull(vInput) or lenb(vInput)=0 then isNothing = true : end if \nend function\n"
},
{
"answer_id": 139572,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 2,
"selected": false,
"text": "iIf() myField = returnIf(isNothing(rs(\"myField\")), 0, rs(\"myField\"))\n returnIf() function returnIf(uExpression, uTrue, uFalse)\n if (uExpression = true) then returnIf = uTrue else returnIf = uFalse : end if\nend function\n"
},
{
"answer_id": 22572341,
"author": "Bond",
"author_id": 2237785,
"author_profile": "https://Stackoverflow.com/users/2237785",
"pm_score": 2,
"selected": false,
"text": "IF if not isNull(Rs(\"myField\")) then if Rs(\"myField\") <> 0 then ...\n then then : if not isNull(Rs(\"myField\")) then if Rs(\"myField\") <> 0 then x = 1 : y = 2\n if not isNull(Rs(\"myField\")) then if Rs(\"myField\") <> 0 then DoSomething(Rs(\"myField\"))\n"
},
{
"answer_id": 38354090,
"author": "JemWritesCode",
"author_id": 3593119,
"author_profile": "https://Stackoverflow.com/users/3593119",
"pm_score": 0,
"selected": false,
"text": "Else If UCase(Rs(\"myField\")) = \"THING\" then\n 'Do Things\nelseif UCase(Rs(\"myField\")) = \"STUFF\" then\n 'Do Other Stuff\nelse\n 'Invalid data, such as a NULL, \"\", etc.\n 'Throw an error, do nothing, or default action\nEnd If\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1818/"
] |
59,628 |
<p>I have a page results page (you get there after submitting your search query elsewhere) whit a whole bunch of gridviews for different type of data objects.</p>
<p>Obviously, some of the queries take longer than the others. How can I make each gridview render as soon as it has the data it needs?</p>
<p>This has been tricky for me because it must work on a postback as well as a pageload. Also, the object data sources just fire automatically on page load/postback; I'm not calling any methods programatically to get the data. Will I have to change this? </p>
|
[
{
"answer_id": 59723,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "if (this.isPostBack && ScriptManager.IsInAsyncPostback)\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
59,635 |
<p>Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system.</p>
<p>Pre-SP1, this was working fine (and still works fine on our developer machines). Now that we've done some testing post-SP1 I've been pulling my hair out since yesterday morning.</p>
<p>First off, our NSIS installer script pulls the dlls and manifest files from the redist folder. These were no longer correct, as the app still links to the RTM version.</p>
<p>So I added the define for <code>_BIND_TO_CURRENT_VCLIBS_VERSION=1</code> to all of our projects so that they will use the SP1 DLLs in the redist folder (or subsequent ones as new service packs come out). It took me hours to find this.</p>
<p>I've double checked the generated manifest files in the intermediate files folder from the compilation, and they correctly list the 9.0.30729.1 SP1 versions. I've double and triple checked depends on a clean machine: it all links to the local dlls with no errors. </p>
<p>Running the app still gets the following error:</p>
<blockquote>
<blockquote>
<p>The application failed to initialize properly (0xc0150002). Click on OK to terminate the application.</p>
</blockquote>
</blockquote>
<p>None of the searches I've done on google or microsoft have come up with anything that relates to my specific issues (but there are hits back to 2005 with this error message).</p>
<p>Any one had any similar problem with SP1?</p>
<p>Options:<ul>
<li>Find the problem and fix it so it works as it should (preferred)
<li>Install the redist
<li>dig out the old RTM dlls and manifest files and remove the #define to use the current ones. (I've got them in an earlier installer build, since Microsoft blasts them out of your redist folder!)</ul></p>
<p><b>Edit:</b> I've tried re-building with the define turned off (link to RTM dlls), and that works as long as the RTM dlls are installed in the folder. If the SP1 dlls are dropped in, it gets the following error:</p>
<blockquote>
<p>c:\Program Files\...\...\X.exe</p>
<p>This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.</p>
</blockquote>
<p>Has no-one else had to deal with this issue?</p>
<p><b>Edit:</b> Just for grins, I downloaded and ran the vcredist_x86.exe for VS2008SP1 on my test machine. <b><i>It</i></b> works. With the SP1 DLLs. And my RTM linked app. But <b>NOT</b> in a private side-by-side distribution that worked pre-SP1.</p>
|
[
{
"answer_id": 70808,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 6,
"selected": true,
"text": "#define _BIND_TO_CURRENT_MFC_VERSION 1\n#define _BIND_TO_CURRENT_CRT_VERSION 1\n #define _BIND_TO_CURRENT_VCLIBS_VERSION 1\n _BIND_TO_CURRENT_CRT_VERSION"
},
{
"answer_id": 2153085,
"author": "Dimitri C.",
"author_id": 74612,
"author_profile": "https://Stackoverflow.com/users/74612",
"pm_score": 4,
"selected": false,
"text": "Situation | .exe (A) | embedded manifest (B) | VC DLLs (C) | VC manifests (D)\n-----------------------------------------------------------------------------\n1 | v2 | v1 | v1 | v1 \n2 | v2 | v1 | v2 | v2 \n3 | v2 | v1 | v2 | v1\n4 | v2 | v2 | v2 | v2\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1441/"
] |
59,642 |
<p>What's the best way to determine which version of the .NET Compact Frameworks (including Service Packs) is installed on a device through a .NET application. </p>
|
[
{
"answer_id": 70808,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 6,
"selected": true,
"text": "#define _BIND_TO_CURRENT_MFC_VERSION 1\n#define _BIND_TO_CURRENT_CRT_VERSION 1\n #define _BIND_TO_CURRENT_VCLIBS_VERSION 1\n _BIND_TO_CURRENT_CRT_VERSION"
},
{
"answer_id": 2153085,
"author": "Dimitri C.",
"author_id": 74612,
"author_profile": "https://Stackoverflow.com/users/74612",
"pm_score": 4,
"selected": false,
"text": "Situation | .exe (A) | embedded manifest (B) | VC DLLs (C) | VC manifests (D)\n-----------------------------------------------------------------------------\n1 | v2 | v1 | v1 | v1 \n2 | v2 | v1 | v2 | v2 \n3 | v2 | v1 | v2 | v1\n4 | v2 | v2 | v2 | v2\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723/"
] |
59,648 |
<p>I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: <em><a href="http://www.gallup.com" rel="nofollow noreferrer">www.gallup.com</a></em> and <em><a href="http://www.rassmussenreports.com" rel="nofollow noreferrer">www.rassmussenreports.com</a></em></p>
<p>I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages)</p>
<p>Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations.</p>
<p>And this is my problem. At the end of the test I have an array in a single variable that looks something like this:</p>
<pre><code>[40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0]
</code></pre>
<p>The program currently produces one array for each correct simulation. <em>I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?</em></p>
<p>How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want.</p>
<p>Code testing for McCain:</p>
<pre><code> test = []
while x < 5:
test = round(100*random.random())
mctest.append(test)
x = x +1
mctestavg = (mctest[0] + mctest[1] + mctest[2])/3
#mcavg is real data
if mctestavg == mcavg[2]:
mcwork = mctest
</code></pre>
<p>How do I repeat without creating multiple mcwork vars?</p>
|
[
{
"answer_id": 59662,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": ">>> a = [ ['a', 'b'], ['c', 'd'] ]\n>>> a[1]\n['c', 'd']\n>>> a[1][1]\n'd'\n"
},
{
"answer_id": 59663,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 1,
"selected": false,
"text": "list list generate_poll_data() data = []\n\nfor in xrange(num_iterations):\n data.append(generate_poll_data())\n data[n] (n-1)"
},
{
"answer_id": 59709,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "data = {}\ndata['a'] = [generate_poll_data()]\ndata['b'] = [generate_poll_data()]\n"
},
{
"answer_id": 59778,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": true,
"text": "from random import randint \n\nmcworks = []\n\nfor n in xrange(NUM_ITERATIONS):\n mctest = [randint(0, 100) for i in xrange(5)]\n if sum(mctest[:3])/3 == mcavg[2]:\n mcworks.append(mctest) # mcavg is real data\n mctest random.randint sum mcworks"
},
{
"answer_id": 53864491,
"author": "Mattias",
"author_id": 8265788,
"author_profile": "https://Stackoverflow.com/users/8265788",
"pm_score": 0,
"selected": false,
"text": "rand_vals = [randint(0, 100) for i in range(5))]\ndf = pd.DataFrame(data=rand_vals, columns=['generated data'])\ndf['3 day avg'] = df['generated data'].rolling(3).mean()\ndf['mcavg'] = mcavg # the list of real data\n# Extract the resulting list of values\nres = df.loc[df['3 day avg'] == df['mcavg']]['3 day avg'].values\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6163/"
] |
59,651 |
<p>I have a web page that I have hooked up to a <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="nofollow noreferrer">stored procedure</a>. In this SQL data source, I have a parameter that I'm passing back to the stored procedure of type int. </p>
<p><a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> seems to want to default to <em>int32</em>, but the number won't get higher than 6. Is it ok to override the ASP.NET default and put in 16 or will there be a conflict somewhere down the road?</p>
<p>specification: the database field has a length of 4 and precision of 10, if that makes a difference in the answer.</p>
|
[
{
"answer_id": 59662,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": ">>> a = [ ['a', 'b'], ['c', 'd'] ]\n>>> a[1]\n['c', 'd']\n>>> a[1][1]\n'd'\n"
},
{
"answer_id": 59663,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 1,
"selected": false,
"text": "list list generate_poll_data() data = []\n\nfor in xrange(num_iterations):\n data.append(generate_poll_data())\n data[n] (n-1)"
},
{
"answer_id": 59709,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "data = {}\ndata['a'] = [generate_poll_data()]\ndata['b'] = [generate_poll_data()]\n"
},
{
"answer_id": 59778,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": true,
"text": "from random import randint \n\nmcworks = []\n\nfor n in xrange(NUM_ITERATIONS):\n mctest = [randint(0, 100) for i in xrange(5)]\n if sum(mctest[:3])/3 == mcavg[2]:\n mcworks.append(mctest) # mcavg is real data\n mctest random.randint sum mcworks"
},
{
"answer_id": 53864491,
"author": "Mattias",
"author_id": 8265788,
"author_profile": "https://Stackoverflow.com/users/8265788",
"pm_score": 0,
"selected": false,
"text": "rand_vals = [randint(0, 100) for i in range(5))]\ndf = pd.DataFrame(data=rand_vals, columns=['generated data'])\ndf['3 day avg'] = df['generated data'].rolling(3).mean()\ndf['mcavg'] = mcavg # the list of real data\n# Extract the resulting list of values\nres = df.loc[df['3 day avg'] == df['mcavg']]['3 day avg'].values\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] |
59,653 |
<p>Is there a way to get at the ItemContaner of a selected item in a listbox? In Silverlight 2.0 Beta 1 I could, but the container is hidden in Beta 2 of Silverlight 2.0. </p>
<p>I'm trying to resize the listbox item when it is unselected to a specific size and when selected to a variable size. I also want to get the relative position of the selected item for animations. Growing to a variable size and getting the relative pasition is why i need to get to the listbox item.</p>
<p>I should clarify i'm not adding items to the listbox explicitly. I am using data binding in xaml and DataTemplates. What I have trouble accessing is the ItemContainer of the selected item's DataTemplate.</p>
|
[
{
"answer_id": 86980,
"author": "dcstraw",
"author_id": 10391,
"author_profile": "https://Stackoverflow.com/users/10391",
"pm_score": 0,
"selected": false,
"text": "_ListBox.Items.Add(obj0);\n_ListBox.Items.Add(obj1);\n _ListBox.Items.Add(new ContentControl { Content = obj0 });\n_ListBox.Items.Add(new ContentControl { Content = obj1 });\n"
},
{
"answer_id": 162051,
"author": "MaxM",
"author_id": 4226,
"author_profile": "https://Stackoverflow.com/users/4226",
"pm_score": 2,
"selected": false,
"text": "protected override void PrepareContainerForItemOverride(DependencyObject element, object item)\n {\n base.PrepareContainerForItemOverride(element, item);\n var el = element as FrameworkElement;\n if (el != null)\n {\n // here is the elements's panel:\n _itemsHost = el.Parent as Panel;\n\n // item is original item inserted in Items or ItemsSource\n // we can save the mapping between items and FrameworElements:\n _elementMapping[item] = el;\n }\n }\n"
},
{
"answer_id": 1500946,
"author": "jpierson",
"author_id": 83658,
"author_profile": "https://Stackoverflow.com/users/83658",
"pm_score": 0,
"selected": false,
"text": "<TextBlock YourTargetProperty=\"{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListBoxItem}}, Mode=OneWay, Path=YourSourceProperty}\" />\n"
},
{
"answer_id": 10407613,
"author": "Parrhesia Joe",
"author_id": 542909,
"author_profile": "https://Stackoverflow.com/users/542909",
"pm_score": 0,
"selected": false,
"text": " <ListBox ItemsSource=\"{Binding Properties}\">\n <ListBox.ItemTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}\" />\n </DataTemplate>\n </ListBox.ItemTemplate>\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] |
59,655 |
<p>Given a controller method like: </p>
<pre><code>def show
@model = Model.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => model }
end
end
</code></pre>
<p>What's the best way to write an integration test that asserts that the return has the expected XML?</p>
|
[
{
"answer_id": 59714,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 0,
"selected": false,
"text": "@request.accept = 'text/xml' # or 'application/xml' I forget which\n assert_equal '<some>xml</some>', @response.body\n"
},
{
"answer_id": 60261,
"author": "btandyco",
"author_id": 6189,
"author_profile": "https://Stackoverflow.com/users/6189",
"pm_score": 3,
"selected": false,
"text": "class ProductsControllerTest < ActionController::TestCase\n def test_should_get_index_formatted_for_xml\n @request.env['HTTP_ACCEPT'] = 'application/xml'\n get :index\n assert_response :success\n end\nend\n"
},
{
"answer_id": 60626,
"author": "ntalbott",
"author_id": 6284,
"author_profile": "https://Stackoverflow.com/users/6284",
"pm_score": 5,
"selected": true,
"text": "class ProductsTest < ActionController::IntegrationTest\n def test_contents_of_xml\n get '/index/1.xml'\n assert_select 'product name', /widget/\n end\nend\n"
},
{
"answer_id": 613309,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "assert_equal @response.body"
},
{
"answer_id": 3532203,
"author": "bjnord",
"author_id": 291754,
"author_profile": "https://Stackoverflow.com/users/291754",
"pm_score": 3,
"selected": false,
"text": "class TruckTest < ActionController::IntegrationTest\n def test_new_truck\n paint_color = 'blue'\n fuzzy_dice_count = 2\n truck = Truck.new({:paint_color => paint_color, :fuzzy_dice_count => fuzzy_dice_count})\n @headers ||= {}\n @headers['HTTP_ACCEPT'] = @headers['CONTENT_TYPE'] = 'application/xml'\n post '/trucks.xml', truck.to_xml, @headers\n #puts @response.body\n assert_select 'truck>paint_color', paint_color\n assert_select 'truck>fuzzy_dice_count', fuzzy_dice_count.to_s\n end\nend\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4748/"
] |
59,656 |
<p>Erasing programs such as Eraser recommend overwriting data maybe 36 times.</p>
<p>As I understand it all data is stored on a hard drive as 1s or 0s.</p>
<p>If an overwrite of random 1s and 0s is carried out once over the whole file then why isn't that enough to remove all traces of the original file?</p>
|
[
{
"answer_id": 60193,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 1,
"selected": false,
"text": "public static void DeleteGutmann(string fileName)\n{\n var fi = new FileInfo(fileName);\n\n if (!fi.Exists)\n {\n return;\n }\n\n const int GutmannPasses = 35;\n var gutmanns = new byte[GutmannPasses][];\n\n for (var i = 0; i < gutmanns.Length; i++)\n {\n if ((i == 14) || (i == 19) || (i == 25) || (i == 26) || (i == 27))\n {\n continue;\n }\n\n gutmanns[i] = new byte[fi.Length];\n }\n\n using (var rnd = new RNGCryptoServiceProvider())\n {\n for (var i = 0L; i < 4; i++)\n {\n rnd.GetBytes(gutmanns[i]);\n rnd.GetBytes(gutmanns[31 + i]);\n }\n }\n\n for (var i = 0L; i < fi.Length;)\n {\n gutmanns[4][i] = 0x55;\n gutmanns[5][i] = 0xAA;\n gutmanns[6][i] = 0x92;\n gutmanns[7][i] = 0x49;\n gutmanns[8][i] = 0x24;\n gutmanns[10][i] = 0x11;\n gutmanns[11][i] = 0x22;\n gutmanns[12][i] = 0x33;\n gutmanns[13][i] = 0x44;\n gutmanns[15][i] = 0x66;\n gutmanns[16][i] = 0x77;\n gutmanns[17][i] = 0x88;\n gutmanns[18][i] = 0x99;\n gutmanns[20][i] = 0xBB;\n gutmanns[21][i] = 0xCC;\n gutmanns[22][i] = 0xDD;\n gutmanns[23][i] = 0xEE;\n gutmanns[24][i] = 0xFF;\n gutmanns[28][i] = 0x6D;\n gutmanns[29][i] = 0xB6;\n gutmanns[30][i++] = 0xDB;\n if (i >= fi.Length)\n {\n continue;\n }\n\n gutmanns[4][i] = 0x55;\n gutmanns[5][i] = 0xAA;\n gutmanns[6][i] = 0x49;\n gutmanns[7][i] = 0x24;\n gutmanns[8][i] = 0x92;\n gutmanns[10][i] = 0x11;\n gutmanns[11][i] = 0x22;\n gutmanns[12][i] = 0x33;\n gutmanns[13][i] = 0x44;\n gutmanns[15][i] = 0x66;\n gutmanns[16][i] = 0x77;\n gutmanns[17][i] = 0x88;\n gutmanns[18][i] = 0x99;\n gutmanns[20][i] = 0xBB;\n gutmanns[21][i] = 0xCC;\n gutmanns[22][i] = 0xDD;\n gutmanns[23][i] = 0xEE;\n gutmanns[24][i] = 0xFF;\n gutmanns[28][i] = 0xB6;\n gutmanns[29][i] = 0xDB;\n gutmanns[30][i++] = 0x6D;\n if (i >= fi.Length)\n {\n continue;\n }\n\n gutmanns[4][i] = 0x55;\n gutmanns[5][i] = 0xAA;\n gutmanns[6][i] = 0x24;\n gutmanns[7][i] = 0x92;\n gutmanns[8][i] = 0x49;\n gutmanns[10][i] = 0x11;\n gutmanns[11][i] = 0x22;\n gutmanns[12][i] = 0x33;\n gutmanns[13][i] = 0x44;\n gutmanns[15][i] = 0x66;\n gutmanns[16][i] = 0x77;\n gutmanns[17][i] = 0x88;\n gutmanns[18][i] = 0x99;\n gutmanns[20][i] = 0xBB;\n gutmanns[21][i] = 0xCC;\n gutmanns[22][i] = 0xDD;\n gutmanns[23][i] = 0xEE;\n gutmanns[24][i] = 0xFF;\n gutmanns[28][i] = 0xDB;\n gutmanns[29][i] = 0x6D;\n gutmanns[30][i++] = 0xB6;\n }\n\n gutmanns[14] = gutmanns[4];\n gutmanns[19] = gutmanns[5];\n gutmanns[25] = gutmanns[6];\n gutmanns[26] = gutmanns[7];\n gutmanns[27] = gutmanns[8];\n\n Stream s;\n\n try\n {\n s = new FileStream(\n fi.FullName,\n FileMode.Open,\n FileAccess.Write,\n FileShare.None,\n (int)fi.Length,\n FileOptions.DeleteOnClose | FileOptions.RandomAccess | FileOptions.WriteThrough);\n }\n catch (UnauthorizedAccessException)\n {\n return;\n }\n catch (IOException)\n {\n return;\n }\n\n using (s)\n {\n if (!s.CanSeek || !s.CanWrite)\n {\n return;\n }\n\n for (var i = 0L; i < gutmanns.Length; i++)\n {\n s.Seek(0, SeekOrigin.Begin);\n s.Write(gutmanns[i], 0, gutmanns[i].Length);\n s.Flush();\n }\n }\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6164/"
] |
59,667 |
<p>I realize that CHAR is recommended if all my values are fixed-width. But, so what? Why not just pick VARCHAR for all text fields just to be safe.</p>
|
[
{
"answer_id": 59729,
"author": "Ethan Post",
"author_id": 4527,
"author_profile": "https://Stackoverflow.com/users/4527",
"pm_score": 6,
"selected": false,
"text": "varchar char varchar varchar exists in CHAR"
},
{
"answer_id": 59756,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 5,
"selected": false,
"text": "CHAR"
},
{
"answer_id": 59847,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": 3,
"selected": false,
"text": "my_column = 'ABC' -- my_column stores 'ABC ' value which is different then 'ABC'\n"
},
{
"answer_id": 5188701,
"author": "Jeff",
"author_id": 643956,
"author_profile": "https://Stackoverflow.com/users/643956",
"pm_score": 4,
"selected": false,
"text": "create table tblStagingTable (\npkID BIGINT (IDENTITY,1,1),\nCustomerFirstName varchar(30),\nCustomerLastName varchar(30),\nCustomerCityStateZip varchar(100),\nCustomerCurrentBalance money )\n\ninsert into tblStagingTable\n(CustomerFirstName,CustomerLastName, CustomerCityStateZip) ('Joe','Blow','123 Main St Washington, MD 12345', 123.45)\n\ncreate view vwStagingTable AS\nSELECT CustomerFirstName = CAST(CustomerFirstName as CHAR(30)),\nCustomerLastName = CAST(CustomerLastName as CHAR(30)),\nCustomerCityStateZip = CAST(CustomerCityStateZip as CHAR(100)),\nCustomerCurrentBalance = CAST(CAST(CustomerCurrentBalance as NUMERIC(9,2)) AS CHAR(10))\n\nSELECT * from vwStagingTable\n"
},
{
"answer_id": 27118598,
"author": "Tuan Le PN",
"author_id": 4222315,
"author_profile": "https://Stackoverflow.com/users/4222315",
"pm_score": 1,
"selected": false,
"text": "CREATE FUNCTION List(@Status AS CHAR(1) = '')\nRETURNS TABLE\nAS\nRETURN\nSELECT * FROM TEST\nWHERE Status LIKE '%' + @Status '%'\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5592/"
] |
59,670 |
<p>I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning:</p>
<blockquote>
<p>warning: deprecated conversion from string constant to ‘char*’</p>
</blockquote>
<p>Obviously, the correct way to fix this is to find every declaration like</p>
<pre><code>char *s = "constant string";
</code></pre>
<p>or function call like:</p>
<pre><code>void foo(char *s);
foo("constant string");
</code></pre>
<p>and make them <code>const char</code> pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror" rel="nofollow noreferrer">-Werror</a>, so I need some way to stifle these warnings. How can I do that?</p>
|
[
{
"answer_id": 59690,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 6,
"selected": false,
"text": "#pragma warning"
},
{
"answer_id": 59741,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "sed find . -exec sed -E -i .backup -n \\\n -e 's/char\\s*\\*\\s*(\\w+)\\s*= \"/char const* \\1 = \"/g' {} \\;\n"
},
{
"answer_id": 541079,
"author": "BlackShift",
"author_id": 2097,
"author_profile": "https://Stackoverflow.com/users/2097",
"pm_score": 6,
"selected": false,
"text": "#include <string.h>\n\nextern void foo(char* m);\n \nint main() {\n // warning: deprecated conversion from string constant to ‘char*’\n //foo(\"Hello\");\n \n // no more warning\n char msg[] = \"Hello\";\n foo(msg);\n}\n const char* m"
},
{
"answer_id": 826858,
"author": "BillAtHRST",
"author_id": 69158,
"author_profile": "https://Stackoverflow.com/users/69158",
"pm_score": 0,
"selected": false,
"text": "strdup() putenv(\"DEBUG=1\");\n putenv putenv(strdup(\"DEBUG=1\"));\n"
},
{
"answer_id": 1309789,
"author": "vy32",
"author_id": 51167,
"author_profile": "https://Stackoverflow.com/users/51167",
"pm_score": 5,
"selected": false,
"text": "char *setf = tigetstr(\"setf\");\n char *setf = tigetstr((char *)\"setf\");\n"
},
{
"answer_id": 2461387,
"author": "alexsid",
"author_id": 295560,
"author_profile": "https://Stackoverflow.com/users/295560",
"pm_score": 3,
"selected": false,
"text": "Test string char str[] = \"Test string\";\n const char* str = \"Test string\";\nprintf(str);\n"
},
{
"answer_id": 3553118,
"author": "shindow",
"author_id": 415712,
"author_profile": "https://Stackoverflow.com/users/415712",
"pm_score": -1,
"selected": false,
"text": "typedef struct tagPyTypeObject\n{\n PyObject_HEAD;\n char *name;\n PrintFun print;\n AddFun add;\n HashFun hash;\n} PyTypeObject;\n\nPyTypeObject PyDict_Type=\n{\n PyObject_HEAD_INIT(&PyType_Type),\n \"dict\",\n dict_print,\n 0,\n 0\n};\n gcc g++"
},
{
"answer_id": 4500719,
"author": "Dario",
"author_id": 550107,
"author_profile": "https://Stackoverflow.com/users/550107",
"pm_score": 2,
"selected": false,
"text": "(char*) \"test\"\n"
},
{
"answer_id": 8140772,
"author": "EdH",
"author_id": 136087,
"author_profile": "https://Stackoverflow.com/users/136087",
"pm_score": 5,
"selected": false,
"text": "// gets rid of annoying \"deprecated conversion from string constant blah blah\" warning\n#pragma GCC diagnostic ignored \"-Wwrite-strings\"\n #pragma GCC diagnostic pop\n"
},
{
"answer_id": 10584743,
"author": "msn",
"author_id": 1393907,
"author_profile": "https://Stackoverflow.com/users/1393907",
"pm_score": -1,
"selected": false,
"text": "PyTypeObject PyDict_Type=\n{\n ...\n\nPyTypeObject PyDict_Type=\n{\n PyObject_HEAD_INIT(&PyType_Type),\n \"dict\",\n dict_print,\n 0,\n 0\n};\n gcc g++ Boost_python"
},
{
"answer_id": 10952861,
"author": "Md. Arafat Al Mahmud",
"author_id": 1096516,
"author_profile": "https://Stackoverflow.com/users/1096516",
"pm_score": 0,
"selected": false,
"text": "g++ g++ -w -o simple.o simple.cpp -lpthread\n const char* s = \"constant string\"; \n"
},
{
"answer_id": 16867229,
"author": "John",
"author_id": 1735922,
"author_profile": "https://Stackoverflow.com/users/1735922",
"pm_score": 9,
"selected": false,
"text": "\"I am a string literal\" char const * char* const char* const char* char char char* #include <iostream>\n\nvoid print(char* ch);\n\nvoid print(const char* ch) {\n std::cout<<ch;\n}\n\nint main() {\n print(\"Hello\");\n return 0;\n}\n"
},
{
"answer_id": 24758381,
"author": "tejp124",
"author_id": 2514026,
"author_profile": "https://Stackoverflow.com/users/2514026",
"pm_score": 2,
"selected": false,
"text": "char *s = (char *) \"constant string\";\n"
},
{
"answer_id": 26194079,
"author": "John",
"author_id": 4108715,
"author_profile": "https://Stackoverflow.com/users/4108715",
"pm_score": 4,
"selected": false,
"text": "void foo(char *s);\nfoo(\"constant string\");\n void foo(const char s[]);\nfoo(\"constant string\");\n"
},
{
"answer_id": 30255068,
"author": "appapurapu",
"author_id": 2568673,
"author_profile": "https://Stackoverflow.com/users/2568673",
"pm_score": 4,
"selected": false,
"text": "const_cast char* str = const_cast<char*>(\"Test string\");\n"
},
{
"answer_id": 33046116,
"author": "takataka",
"author_id": 5429122,
"author_profile": "https://Stackoverflow.com/users/5429122",
"pm_score": 5,
"selected": false,
"text": "char *str = \"hello\";\n char *str = (char*)\"hello\";\n foo(\"hello\");\n foo((char*) \"hello\");\n"
},
{
"answer_id": 35813713,
"author": "Micheal Morrow",
"author_id": 5133527,
"author_profile": "https://Stackoverflow.com/users/5133527",
"pm_score": 0,
"selected": false,
"text": "const char * timeServer[] = { \"pool.ntp.org\" }; // 0 - Worldwide \n#define WHICH_NTP 0 // Which NTP server name to use.\n...\nsendNTPpacket(const_cast<char*>(timeServer[WHICH_NTP])); // send an NTP packet to a server\n...\nvoid sendNTPpacket(char* address) { code }\n"
},
{
"answer_id": 47925509,
"author": "Sohrab",
"author_id": 2505235,
"author_profile": "https://Stackoverflow.com/users/2505235",
"pm_score": 1,
"selected": false,
"text": "char *str = \"hello\";\n std::string str (\"hello\");\n str.compare(\"HALLO\");\n"
},
{
"answer_id": 49181562,
"author": "MyGEARStationcom",
"author_id": 5365814,
"author_profile": "https://Stackoverflow.com/users/5365814",
"pm_score": 1,
"selected": false,
"text": "char StrContains(char *str, char *sfind)\n char StrContains(const char *str, const char *sfind).\n"
},
{
"answer_id": 63867734,
"author": "Anjan Parajuli",
"author_id": 13458906,
"author_profile": "https://Stackoverflow.com/users/13458906",
"pm_score": 0,
"selected": false,
"text": "void setpart(const char name[]);\n\nsetpart(\"Hello\");\n const char name[] const char \\*name [Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3830/"
] |
59,680 |
<p>In a LotusScript Agent that is being run via WebQueryOpen, how do you get the name of the current server?</p>
|
[
{
"answer_id": 59683,
"author": "Derek",
"author_id": 5440,
"author_profile": "https://Stackoverflow.com/users/5440",
"pm_score": 3,
"selected": false,
"text": "Set s = New NotesSession\nSet db = s.CurrentDatabase\n\nIf db.Server <> \"\" Then\n Set sName = New NotesName(db.Server)\nElse\n Set sName = New NotesName(s.Username)\nEnd If\n"
},
{
"answer_id": 62801,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "'initialize event of a WebQueryOpen agent\n\nDim s As New notessession \nDim servername As String\nservername = s.UserName\n"
},
{
"answer_id": 76770,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Set s = New NotesSession\nSet db = s.CurrentDatabase\nIf db.Server <> \"\" Then\n Set sName = New NotesName(db.Server)\nElse\n Set sName = New NotesName(s.Username)\nEnd If\nServerName = sName.Abbreviated\n"
},
{
"answer_id": 2446498,
"author": "angryITguy",
"author_id": 193467,
"author_profile": "https://Stackoverflow.com/users/193467",
"pm_score": 0,
"selected": false,
"text": "dim session as new notesSession\ndim strCurrServer as string\ndim nmServer as notesName\n\nstrCurrServer = session.currentagent.servername\n' this bit is optional \nset nmServer = new notesName(strCurrServer)\n' then you can do stuff like this\nprint nmServer.Abbreviated \n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5440/"
] |
59,711 |
<p>Is there an equivalent operator to Haskell's list difference operator <code>\\</code> in F#?</p>
|
[
{
"answer_id": 59814,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 3,
"selected": false,
"text": "\\ or || & && <OP >OP $OP = |OP &OP ^OP :: -OP +OP *OP /OP %OP\n\n**OP\n !OP ?OP ~OP -OP +OP % %% & &&\n"
},
{
"answer_id": 827771,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": -1,
"selected": false,
"text": "set - set xs - set ys\n > set [1..5] - set [2..4];;\nval it : Set<int> = seq [1; 5]\n"
},
{
"answer_id": 6085288,
"author": "Hans",
"author_id": 472522,
"author_profile": "https://Stackoverflow.com/users/472522",
"pm_score": 2,
"selected": false,
"text": "let ( /-/ ) xs ys =\n let ySet = set ys\n let notInYSet x = not <| Set.contains x ySet\n List.filter notInYSet xs\n"
},
{
"answer_id": 12435807,
"author": "Ramon Snir",
"author_id": 327201,
"author_profile": "https://Stackoverflow.com/users/327201",
"pm_score": 4,
"selected": true,
"text": "( /-/ ) \\\\ let flip f x y = f y x\n\nlet rec delete x = function\n | [] -> []\n | h :: t when x = h -> t\n | h :: t -> h :: delete x t\n\nlet inline ( /-/ ) xs ys = List.fold (flip delete) xs ys\n \\\\ (xs @ ys) /-/ xs = ys (7 :: [1 .. 5] @ [5 .. 11]) /-/ [4 .. 7] [1; 2; 3; 5; 7; 8; 9; 10; 11]"
},
{
"answer_id": 27955212,
"author": "Lay González",
"author_id": 1120410,
"author_profile": "https://Stackoverflow.com/users/1120410",
"pm_score": 1,
"selected": false,
"text": "let (/-/) l1 l2 = List.filter (fun i -> not <| List.exists ((=) i) l2) l1\n [1;1;2] /-/ [2;3] would be eq to [1;1]\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592/"
] |
59,719 |
<p>I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback).</p>
<p>Basically, I need to check for IsPostBack in JavaScript.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 59727,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "if (this.IsPostBack)\n{\n Page.ClientScript.RegisterStartupScript(this.GetType(),\"PostbackKey\",\"<script type='text/javascript'>var isPostBack = true;</script>\");\n}\n"
},
{
"answer_id": 59730,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 7,
"selected": true,
"text": "if(IsPostBack)\n{\n // NOTE: the following uses an overload of RegisterClientScriptBlock() \n // that will surround our string with the needed script tags \n ClientScript.RegisterClientScriptBlock(GetType(), \"IsPostBack\", \"var isPostBack = true;\", true);\n}\n if(isPostBack) {\n // do your thing\n}\n"
},
{
"answer_id": 59739,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 0,
"selected": false,
"text": "<html>\n\n<?php\nif ($_POST['myVar']) {\n //postback\n echo '<script>var postingBack = true;</script>';\n //Do other processing\n} else {\n echo '<script>var postingBack = false;</script>'\n } ?>\n<script>\nfunction myLoader() {\n if (postingBack == false) {\n //Do stuff\n }\n }\n\n<body onLoad=\"myLoader():\"> ...\n"
},
{
"answer_id": 3557484,
"author": "Faustin",
"author_id": 429637,
"author_profile": "https://Stackoverflow.com/users/429637",
"pm_score": 5,
"selected": false,
"text": "if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}\n if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}\n"
},
{
"answer_id": 3981656,
"author": "md1337",
"author_id": 303468,
"author_profile": "https://Stackoverflow.com/users/303468",
"pm_score": 3,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n string script;\n if (IsPostBack)\n {\n script = \"var isPostBack = true;\";\n }\n else\n {\n script = \"var isPostBack = false;\";\n }\n Page.ClientScript.RegisterStartupScript(GetType(), \"IsPostBack\", script, true);\n}\n"
},
{
"answer_id": 4219596,
"author": "Developer_India",
"author_id": 447461,
"author_profile": "https://Stackoverflow.com/users/447461",
"pm_score": 2,
"selected": false,
"text": " window.onload = isPostBack;\n\n function isPostBack() {\n\n if (!document.getElementById('clientSideIsPostBack')) {\n return false;\n }\n\n if (document.getElementById('clientSideIsPostBack').value == 'Y') {\n\n ***// DO ALL POST BACK RELATED WORK HERE***\n\n return true;\n }\n else {\n\n ***// DO ALL INITIAL LOAD RELATED WORK HERE***\n\n return false;\n }\n }\n"
},
{
"answer_id": 12850538,
"author": "iuppiter",
"author_id": 1566081,
"author_profile": "https://Stackoverflow.com/users/1566081",
"pm_score": 0,
"selected": false,
"text": "<script>\n var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;\n</script>\n"
},
{
"answer_id": 15159545,
"author": "Wily AO",
"author_id": 2123781,
"author_profile": "https://Stackoverflow.com/users/2123781",
"pm_score": 4,
"selected": false,
"text": "function pageLoad (sender, args) {\n\nalert (args._isPartialLoad);\n\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] |
59,726 |
<p>Is there a way in .net 2.0 to discover the network alias for the machine that my code is running on? Specifically, if my workgroup sees my machine as //jekkedev01, how do I retrieve that name programmatically?</p>
|
[
{
"answer_id": 229049,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 1,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\lanmanserver\\parameters srvcomment REG_SZ (string) System.Environment.MachineName System.Net.Dns.GetHostName() System.Net.Dns.GetHostEntry(\"LocalHost\").HostName"
},
{
"answer_id": 239489,
"author": "msulis",
"author_id": 9317,
"author_profile": "https://Stackoverflow.com/users/9317",
"pm_score": 3,
"selected": true,
"text": "public ArrayList GetAllDnsNames() {\n ArrayList names = new ArrayList();\n IPHostEntry host;\n //check each Network Interface\n foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {\n //check each IP address claimed by this Network Interface\n foreach (UnicastIPAddressInformation i in nic.GetIPProperties().UnicastAddresses) {\n //get the DNS host entry for this IP address\n host = System.Net.Dns.GetHostEntry(i.Address.ToString());\n if (!names.Contains(host.HostName)) {\n names.Add(host.HostName);\n }\n //check each alias, adding each to the list\n foreach (string s in host.Aliases) {\n if (!names.Contains(s)) {\n names.Add(s);\n }\n }\n }\n }\n //add \"simple\" host name - above loop returns fully qualified domain names (FQDNs)\n //but this method returns just the machine name without domain information\n names.Add(System.Net.Dns.GetHostName());\n\n return names;\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287/"
] |
59,734 |
<p>My application is using <strong>Dojo 1.1.1</strong> on an <em>SSL-only</em> website. It is currently taking advantage of <code>dijit.ProgressBar</code> and a <code>dijit.form.DateTextBox</code>.</p>
<p>Everything works fabulous in <em>Firefox 2 & 3</em>, but as soon as I try the same scripts in <em>IE7</em> the results are an annoying Security Information dialog:</p>
<blockquote>
<p>This page contains both secure and non-secure items. Do you want to display the non-secure items?</p>
</blockquote>
<p>I have scrutinized the page for any <em>non-HTTPS</em> reference to no avail. It appears to be something specific to <code>dojo.js</code>. There use to be an <code>iframe</code> glitch where the <code>src</code> was set to nothing, but this appears to be fixed now (on review of the source).</p>
<p>Anyone else having this problem? What are the best-practices for getting <em>Dojo</em> to play well with <em>IE</em> on an <em>SSL-only</em> web server?</p>
|
[
{
"answer_id": 72805,
"author": "esarjeant",
"author_id": 644,
"author_profile": "https://Stackoverflow.com/users/644",
"pm_score": 3,
"selected": false,
"text": "if(dojo.isIE){\n var html=\"<iframe src='javascript:\\\"\\\"'\"\n + \" style='position: absolute; left: 0px; top: 0px;\"\n + \"z-index: -1; filter:Alpha(Opacity=\\\"0\\\");'>\";\n iframe = dojo.doc.createElement(html);\n}else{...\n if(dojo.isIE){\n var html=\"<iframe src='javascript:void(0);'\"\n + \" style='position: absolute; left: 0px; top: 0px;\"\n + \"z-index: -1; filter:Alpha(Opacity=\\\"0\\\");'>\";\n iframe = dojo.doc.createElement(html);\n}else{...\n div.style.cssText = 'border: 1px solid;'\n + 'border-color:red green;'\n + 'position: absolute;'\n + 'height: 5px;'\n + 'top: -999px;'\n + 'background-image: url(\"' + dojo.moduleUrl(\"dojo\", \"resources/blank.gif\") + '\");';\n"
},
{
"answer_id": 7589230,
"author": "ZMorek",
"author_id": 671432,
"author_profile": "https://Stackoverflow.com/users/671432",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\">\ndjConfig = {\n modulePaths: {\n \"dojo\": \"https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dojo\",\n \"dijit\": \"https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dijit\",\n \"dojox\": \"https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dojox\"\n }\n};\n\n</script>\n<script src=\"https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dojo/dojo.xd.js\" type=\"text/javascript\"></script>\n 1.6.1"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644/"
] |
59,743 |
<p>How many possible combinations of the variables a,b,c,d,e are possible if I know that:</p>
<pre><code>a+b+c+d+e = 500
</code></pre>
<p>and that they are all integers and >= 0, so I know they are finite.</p>
|
[
{
"answer_id": 59824,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "public static long getNumCombinations( int summands, int sum )\n{\n if ( summands <= 1 )\n return 1;\n long combos = 0;\n for ( int a = 0 ; a <= sum ; a++ )\n combos += getNumCombinations( summands-1, sum-a );\n return combos;\n}\n summands sum summand,sum >=0 >0 a = 1 a < sum 1+2+3+4+5 2+1+3+4+5 a >= b >= c >= d >= e"
},
{
"answer_id": 59831,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " for (a=0;a<=sum;a++)\n {\n for (b = 0; b <= (sum - a); b++)\n {\n for (c = 0; c <= (sum - a - b); c++)\n {\n //d = sum - a - b - c;\n i++\n }\n }\n }\n"
},
{
"answer_id": 59833,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": true,
"text": "a 1 b 2 a 2 b 1 public static long getCombos( int n, int sum ) {\n // tab[i][j] is how many combinations of (i+1) vars add up to j\n long[][] tab = new long[n][sum+1];\n // # of combos of 1 var for any sum is 1\n for( int j=0; j < tab[0].length; ++j ) {\n tab[0][j] = 1;\n }\n for( int i=1; i < tab.length; ++i ) {\n for( int j=0; j < tab[i].length; ++j ) {\n // # combos of (i+1) vars adding up to j is the sum of the #\n // of combos of i vars adding up to k, for all 0 <= k <= j\n // (choosing i vars forces the choice of the (i+1)st).\n tab[i][j] = 0;\n for( int k=0; k <= j; ++k ) {\n tab[i][j] += tab[i-1][k];\n }\n }\n }\n return tab[n-1][sum];\n}\n"
},
{
"answer_id": 60107,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "public class Combos {\n public static void main() {\n long counter = 0;\n\n for (int a = 0; a <= 500; a++) {\n for (int b = 0; b <= (500 - a); b++) {\n for (int c = 0; c <= (500 - a - b); c++) {\n for (int d = 0; d <= (500 - a - b - c); d++) {\n counter++;\n }\n }\n }\n }\n System.out.println(counter);\n }\n}\n public class Combos {\n public static void main() {\n long counter = 0;\n\n for (int a = 1; a <= 500; a++) {\n for (int b = (a != 500) ? 1 : 0; b <= (500 - a); b++) {\n for (int c = (a + b != 500) ? 1 : 0; c <= (500 - a - b); c++) {\n for (int d = (a + b + c != 500) ? 1 : 0; d <= (500 - a - b - c); d++) {\n counter++;\n }\n }\n }\n }\n System.out.println(counter);\n }\n}\n"
},
{
"answer_id": 13333456,
"author": "neel",
"author_id": 1215889,
"author_profile": "https://Stackoverflow.com/users/1215889",
"pm_score": 0,
"selected": false,
"text": "C(N + number_of_variable - 1, N)"
},
{
"answer_id": 19784359,
"author": "user2955441",
"author_id": 2955441,
"author_profile": "https://Stackoverflow.com/users/2955441",
"pm_score": 0,
"selected": false,
"text": " long counter = 0;\n int sum=25;\n\n for (int a = 0; a <= sum; a++) {\n for (int b = 0; b <= sum ; b++) {\n for (int c = 0; c <= sum; c++) {\n for (int d = 0; d <= sum; d++) {\n for (int e = 0; e <= sum; e++) {\n if ((a+b+c+d+e)==sum) counter=counter+1L;\n\n }\n }\n }\n }\n }\n System.out.println(\"counter e \"+counter);\n"
},
{
"answer_id": 44703816,
"author": "Neil Wang",
"author_id": 8128469,
"author_profile": "https://Stackoverflow.com/users/8128469",
"pm_score": 0,
"selected": false,
"text": "Just a test for code block Just a test for code block\n\n Just a test for code block\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815/"
] |
59,761 |
<p>I need to disable specific keys (Ctrl and Backspace) in Internet Explorer 6. Is there a registry hack to do this. It has to be IE6. Thanks.</p>
<p>Long Edit: </p>
<p>@apandit: Whoops. I need to more specific about the backspace thing. When I say disable backspace, I mean disable the ability for Backspace to mimic the Back browser button. In IE, pressing Backspace when the focus is not in a text entry field is equivalent to pressing Back (browsing to the previous page).</p>
<p>As for the Ctrl key. There are some pages which have links which create new IE windows. I have the popup blocker turned on, which block this. But, Ctrl clicking result in the new window being launched.</p>
<p>This is for a kiosk application, which is currently a web based application. Clients do not have the funds at this time to make their site kiosk friendly. Things like URL filtering and disabling the URL entry field is already done.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 59824,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "public static long getNumCombinations( int summands, int sum )\n{\n if ( summands <= 1 )\n return 1;\n long combos = 0;\n for ( int a = 0 ; a <= sum ; a++ )\n combos += getNumCombinations( summands-1, sum-a );\n return combos;\n}\n summands sum summand,sum >=0 >0 a = 1 a < sum 1+2+3+4+5 2+1+3+4+5 a >= b >= c >= d >= e"
},
{
"answer_id": 59831,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " for (a=0;a<=sum;a++)\n {\n for (b = 0; b <= (sum - a); b++)\n {\n for (c = 0; c <= (sum - a - b); c++)\n {\n //d = sum - a - b - c;\n i++\n }\n }\n }\n"
},
{
"answer_id": 59833,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": true,
"text": "a 1 b 2 a 2 b 1 public static long getCombos( int n, int sum ) {\n // tab[i][j] is how many combinations of (i+1) vars add up to j\n long[][] tab = new long[n][sum+1];\n // # of combos of 1 var for any sum is 1\n for( int j=0; j < tab[0].length; ++j ) {\n tab[0][j] = 1;\n }\n for( int i=1; i < tab.length; ++i ) {\n for( int j=0; j < tab[i].length; ++j ) {\n // # combos of (i+1) vars adding up to j is the sum of the #\n // of combos of i vars adding up to k, for all 0 <= k <= j\n // (choosing i vars forces the choice of the (i+1)st).\n tab[i][j] = 0;\n for( int k=0; k <= j; ++k ) {\n tab[i][j] += tab[i-1][k];\n }\n }\n }\n return tab[n-1][sum];\n}\n"
},
{
"answer_id": 60107,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "public class Combos {\n public static void main() {\n long counter = 0;\n\n for (int a = 0; a <= 500; a++) {\n for (int b = 0; b <= (500 - a); b++) {\n for (int c = 0; c <= (500 - a - b); c++) {\n for (int d = 0; d <= (500 - a - b - c); d++) {\n counter++;\n }\n }\n }\n }\n System.out.println(counter);\n }\n}\n public class Combos {\n public static void main() {\n long counter = 0;\n\n for (int a = 1; a <= 500; a++) {\n for (int b = (a != 500) ? 1 : 0; b <= (500 - a); b++) {\n for (int c = (a + b != 500) ? 1 : 0; c <= (500 - a - b); c++) {\n for (int d = (a + b + c != 500) ? 1 : 0; d <= (500 - a - b - c); d++) {\n counter++;\n }\n }\n }\n }\n System.out.println(counter);\n }\n}\n"
},
{
"answer_id": 13333456,
"author": "neel",
"author_id": 1215889,
"author_profile": "https://Stackoverflow.com/users/1215889",
"pm_score": 0,
"selected": false,
"text": "C(N + number_of_variable - 1, N)"
},
{
"answer_id": 19784359,
"author": "user2955441",
"author_id": 2955441,
"author_profile": "https://Stackoverflow.com/users/2955441",
"pm_score": 0,
"selected": false,
"text": " long counter = 0;\n int sum=25;\n\n for (int a = 0; a <= sum; a++) {\n for (int b = 0; b <= sum ; b++) {\n for (int c = 0; c <= sum; c++) {\n for (int d = 0; d <= sum; d++) {\n for (int e = 0; e <= sum; e++) {\n if ((a+b+c+d+e)==sum) counter=counter+1L;\n\n }\n }\n }\n }\n }\n System.out.println(\"counter e \"+counter);\n"
},
{
"answer_id": 44703816,
"author": "Neil Wang",
"author_id": 8128469,
"author_profile": "https://Stackoverflow.com/users/8128469",
"pm_score": 0,
"selected": false,
"text": "Just a test for code block Just a test for code block\n\n Just a test for code block\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78/"
] |
59,766 |
<p>I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong?</p>
|
[
{
"answer_id": 59770,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 7,
"selected": true,
"text": "/// <reference path=\"jQuery.js\"/>\n"
},
{
"answer_id": 271359,
"author": "JD Courtoy",
"author_id": 23468,
"author_profile": "https://Stackoverflow.com/users/23468",
"pm_score": 4,
"selected": false,
"text": "<% if (false) { %>\n <script src=\"jquery-1.2.6-vsdoc.js\" type=\"text/javascript\"></script>\n<% } %>\n /// <reference path=\"jquery-1.2.6-vsdoc.js\" />\n"
},
{
"answer_id": 940270,
"author": "nikmd23",
"author_id": 107289,
"author_profile": "https://Stackoverflow.com/users/107289",
"pm_score": 2,
"selected": false,
"text": "<% #if (false) %>\n <!-- This block is here for jquery intellisense only. It will be removed by the compiler! -->\n <script type=\"text/javascript\" src=\"Scripts/jquery-1.3.2-vsdoc.js\"></script>\n<% #endif %>\n <script type=\"text/javascript\" src=\"http://www.google.com/jsapi\"></script>\n<script type=\"text/javascript\">\n google.load(\"jquery\", \"1.3.2\", { uncompressed: false });\n</script>\n"
},
{
"answer_id": 3984041,
"author": "Steve Miller",
"author_id": 482497,
"author_profile": "https://Stackoverflow.com/users/482497",
"pm_score": 0,
"selected": false,
"text": "/// <reference path=\"http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js\" />\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
59,787 |
<p>How do you generate and analyze a thread dump from a running JBoss instance?</p>
|
[
{
"answer_id": 11678609,
"author": "user98761",
"author_id": 98761,
"author_profile": "https://Stackoverflow.com/users/98761",
"pm_score": 1,
"selected": false,
"text": "Thread.getAllStackTraces()"
},
{
"answer_id": 16665089,
"author": "Stephan",
"author_id": 363573,
"author_profile": "https://Stackoverflow.com/users/363573",
"pm_score": 1,
"selected": false,
"text": "http://localhost:8080 jboss.system:type=ServerInfo listThreadDump File > Save As listThreadDump() <JBOSS_HOME>/bin/twiddle invoke \"jboss.system:type=ServerInfo\" listThreadDump > threads.html\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
] |
59,790 |
<p>I have been hearing the podcast blog for a while, I hope I dont break this.
The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp_xml_preparedocument that is used to get transfer XMLs to an object and throught code. </p>
<p>I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes. </p>
|
[
{
"answer_id": 60139,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 2,
"selected": false,
"text": "declare @XmlDocumentHandle int\ndeclare @XmlDocument nvarchar(1000)\nset @XmlDocument = N'<ROOT>\n<Customer>\n <FirstName>Will</FirstName>\n <LastName>Smith</LastName>\n</Customer>\n</ROOT>'\n\n-- Create temp table to insert data into\ncreate table #Customer \n( \n FirstName varchar(20),\n LastName varchar(20) \n)\n-- Create an internal representation of the XML document.\nexec sp_xml_preparedocument @XmlDocumentHandle output, @XmlDocument\n\n-- Insert using openxml allows us to read the structure\ninsert into #Customer\nselect \n FirstName = XmlFirstName,\n LastName = XmlLastName\nfrom openxml ( @XmlDocumentHandle, '/ROOT/Customer',2 )\nwith \n(\n XmlFirstName varchar(20) 'FirstName',\n XmlLastName varchar(20) 'LastName'\n)\nwhere ( XmlFirstName = 'Will' and XmlLastName = 'Smith' )\n\n-- Cleanup xml document\nexec sp_xml_removedocument @XmlDocumentHandle\n\n-- Show the data\nselect * \nfrom #Customer\n\n-- Drop tmp table\ndrop table #Customer\n"
},
{
"answer_id": 87072,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<xml type=\"user\">\n <data>1</data>\n <data>2</data>\n<xml>\n <xsl:template match=\"xml\">\n INSERT INTO <xsl:value-of select=\"@type\" /> (data1, data2) VALUES (\n '<xsl:value-of select=\"data[1]\" />',\n '<xsl:value-of select=\"data[2]\" />');\n</xsl:template>\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
59,819 |
<p>I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure:</p>
<pre><code>Contact
{
string First
string Last
string Phone
}
</code></pre>
<p>How would I go about creating this so that I could use it in function like the following:</p>
<pre><code>function PrintContact
{
param( [Contact]$contact )
"Customer Name is " + $contact.First + " " + $contact.Last
"Customer Phone is " + $contact.Phone
}
</code></pre>
<p>Is something like this possible, or even recommended in PowerShell?</p>
|
[
{
"answer_id": 59887,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 2,
"selected": false,
"text": "$contact = New-Object PSObject\n\n$contact | Add-Member -memberType NoteProperty -name \"First\" -value \"John\"\n$contact | Add-Member -memberType NoteProperty -name \"Last\" -value \"Doe\"\n$contact | Add-Member -memberType NoteProperty -name \"Phone\" -value \"123-4567\"\n [8] » $contact\n\nFirst Last Phone\n----- ---- -----\nJohn Doe 123-4567\n"
},
{
"answer_id": 59980,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 6,
"selected": false,
"text": "function New-Person()\n{\n param ($FirstName, $LastName, $Phone)\n\n $person = new-object PSObject\n\n $person | add-member -type NoteProperty -Name First -Value $FirstName\n $person | add-member -type NoteProperty -Name Last -Value $LastName\n $person | add-member -type NoteProperty -Name Phone -Value $Phone\n\n return $person\n}\n"
},
{
"answer_id": 61315,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 4,
"selected": false,
"text": "$myPerson = \"\" | Select-Object First,Last,Phone\n"
},
{
"answer_id": 66693,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 8,
"selected": true,
"text": "add-type @\"\npublic struct contact {\n public string First;\n public string Last;\n public string Phone;\n}\n\"@\n New-Struct Contact @{\n First=[string];\n Last=[string];\n Phone=[string];\n}\n Add-Type New-Struct param([Contact]$contact) $contact = new-object Contact $Contact = New-Object PSObject -Property @{ First=\"\"; Last=\"\"; Phone=\"\" }\n PSCustomObject [PSCustomObject]@{\n PSTypeName = \"Contact\"\n First = $First\n Last = $Last\n Phone = $Phone\n}\n New-Contact PSTypeName function PrintContact\n{\n param( [PSTypeName(\"Contact\")]$contact )\n \"Customer Name is \" + $contact.First + \" \" + $contact.Last\n \"Customer Phone is \" + $contact.Phone \n}\n class enum struct class Contact\n{\n # Optionally, add attributes to prevent invalid values\n [ValidateNotNullOrEmpty()][string]$First\n [ValidateNotNullOrEmpty()][string]$Last\n [ValidateNotNullOrEmpty()][string]$Phone\n\n # optionally, have a constructor to \n # force properties to be set:\n Contact($First, $Last, $Phone) {\n $this.First = $First\n $this.Last = $Last\n $this.Phone = $Phone\n }\n}\n New-Object [Contact]::new() class Contact\n{\n # Optionally, add attributes to prevent invalid values\n [ValidateNotNullOrEmpty()][string]$First\n [ValidateNotNullOrEmpty()][string]$Last\n [ValidateNotNullOrEmpty()][string]$Phone\n}\n\n$C = [Contact]@{\n First = \"Joel\"\n Last = \"Bennett\"\n}\n"
},
{
"answer_id": 4667545,
"author": "Nick Meldrum",
"author_id": 32739,
"author_profile": "https://Stackoverflow.com/users/32739",
"pm_score": 3,
"selected": false,
"text": "function New-Person() {\n param ($FirstName, $LastName, $Phone)\n\n $person = new-object PSObject | select-object First, Last, Phone\n\n $person.First = $FirstName\n $person.Last = $LastName\n $person.Phone = $Phone\n\n return $person\n}\n"
},
{
"answer_id": 27492180,
"author": "Florian JUDITH",
"author_id": 4363832,
"author_profile": "https://Stackoverflow.com/users/4363832",
"pm_score": 2,
"selected": false,
"text": "$Collection = @()\n\n$Object = New-Object -TypeName PSObject\n$Object.PsObject.TypeNames.Add('MyCustomType.Contact.Detail')\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"First\" -value \"John\"\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"Last\" -value \"Doe\"\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"Phone\" -value \"123-4567\"\n$Collection += $Object\n\n$Object = New-Object -TypeName PSObject\n$Object.PsObject.TypeNames.Add('MyCustomType.Contact.Detail')\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"First\" -value \"Jeanne\"\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"Last\" -value \"Doe\"\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"Phone\" -value \"765-4321\"\n$Collection += $Object\n\nWrite-Ouput -InputObject $Collection\n"
},
{
"answer_id": 32506564,
"author": "Benjamin Hubbard",
"author_id": 2562189,
"author_profile": "https://Stackoverflow.com/users/2562189",
"pm_score": 3,
"selected": false,
"text": "[PSCustomObject]@{\n First = $First\n Last = $Last\n Phone = $Phone\n}\n"
},
{
"answer_id": 57481684,
"author": "JohnLBevan",
"author_id": 361842,
"author_profile": "https://Stackoverflow.com/users/361842",
"pm_score": 1,
"selected": false,
"text": "Person.Types.ps1xml <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<Types>\n <Type>\n <Name>StackOverflow.Example.Person</Name>\n <Members>\n <ScriptMethod>\n <Name>Initialize</Name>\n <Script>\n Param (\n [Parameter(Mandatory = $true)]\n [string]$GivenName\n ,\n [Parameter(Mandatory = $true)]\n [string]$Surname\n )\n $this | Add-Member -MemberType 'NoteProperty' -Name 'GivenName' -Value $GivenName\n $this | Add-Member -MemberType 'NoteProperty' -Name 'Surname' -Value $Surname\n </Script>\n </ScriptMethod>\n <ScriptMethod>\n <Name>SetGivenName</Name>\n <Script>\n Param (\n [Parameter(Mandatory = $true)]\n [string]$GivenName\n )\n $this | Add-Member -MemberType 'NoteProperty' -Name 'GivenName' -Value $GivenName -Force\n </Script>\n </ScriptMethod>\n <ScriptProperty>\n <Name>FullName</Name>\n <GetScriptBlock>'{0} {1}' -f $this.GivenName, $this.Surname</GetScriptBlock>\n </ScriptProperty>\n <!-- include properties under here if we don't want them to be visible by default\n <MemberSet>\n <Name>PSStandardMembers</Name>\n <Members>\n </Members>\n </MemberSet>\n -->\n </Members>\n </Type>\n</Types>\n Update-TypeData -AppendPath .\\Person.Types.ps1xml $p = [PSCustomType]@{PSTypeName='StackOverflow.Example.Person'} $p.Initialize('Anne', 'Droid') $p | Format-Table -AutoSize $p.SetGivenName('Dan') $p | Format-Table -AutoSize PS1XML Add-Member NoteProperty AliasProperty ScriptProperty CodeProperty ScriptMethod CodeMethod PropertySet MemberSet ScriptMethod Initialize SetGivenName FullName Get-Content \n$PSHome\\types.ps1xml # have something like this defined in my script so we only try to import the definition once.\n# the surrounding if statement may be useful if we're dot sourcing the script in an existing \n# session / running in ISE / something like that\nif (!(Get-TypeData 'StackOverflow.Example.Person')) {\n Update-TypeData '.\\Person.Types.ps1xml'\n}\n\n# have a function to create my objects with all required parameters\n# creating them from the hash table means they're PROPERties; i.e. updatable without calling a \n# setter method (note: recall I said above that in this scenario I'd remove their definition \n# from the PS1XML)\nfunction New-SOPerson {\n [CmdletBinding()]\n [OutputType('StackOverflow.Example.Person')]\n Param (\n [Parameter(Mandatory)]\n [string]$GivenName\n ,\n [Parameter(Mandatory)]\n [string]$Surname\n )\n ([PSCustomObject][Ordered]@{\n PSTypeName = 'StackOverflow.Example.Person'\n GivenName = $GivenName\n Surname = $Surname\n })\n}\n\n# then use my new function to generate the new object\n$p = New-SOPerson -GivenName 'Simon' -Surname 'Borg'\n\n# and thanks to the type magic... FullName exists :)\nWrite-Information \"$($p.FullName) was created successfully!\" -InformationAction Continue\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
] |
59,825 |
<p>Suppose the following:</p>
<pre><code>>>> s = set([1, 2, 3])
</code></pre>
<p>How do I get a value (any value) out of <code>s</code> without doing <code>s.pop()</code>? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p>
<p>Quick and dirty:</p>
<pre><code>>>> elem = s.pop()
>>> s.add(elem)
</code></pre>
<p>But do you know of a better way? Ideally in constant time.</p>
|
[
{
"answer_id": 59841,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 11,
"selected": true,
"text": "for e in s:\n break\n# e is now an element from s\n e = next(iter(s))\n"
},
{
"answer_id": 59928,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": -1,
"selected": false,
"text": "\npoor_man_set = {}\npoor_man_set[1] = None\npoor_man_set[2] = None\npoor_man_set[3] = None\n...\n \nkeys = poor_man_set.keys()\nprint \"Some key = %s\" % keys[0]\n set \npoor_man_set = {}\npoor_man_set[1] = None\npoor_man_set[2] = None\npoor_man_set[3] = None\npoor_man_set = poor_man_set.keys()\n"
},
{
"answer_id": 60027,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 5,
"selected": false,
"text": ">>> import random\n>>> s = set([1,2,3])\n>>> random.sample(s, 1)\n[2]\n random.sample >>> list(set(range(10))) == range(10)\nTrue \n random.sample >>> lst = list(s) # once, O(len(s))?\n...\n>>> e = random.sample(lst, 1)[0] # constant time\n"
},
{
"answer_id": 60233,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 8,
"selected": false,
"text": ">>> s = set([1, 2, 3])\n>>> list(s)[0]\n1\n"
},
{
"answer_id": 61140,
"author": "Nick",
"author_id": 5222,
"author_profile": "https://Stackoverflow.com/users/5222",
"pm_score": 3,
"selected": false,
"text": "def anyitem(iterable):\n try:\n return iter(iterable).next()\n except StopIteration:\n return None\n"
},
{
"answer_id": 1612654,
"author": "wr.",
"author_id": 101430,
"author_profile": "https://Stackoverflow.com/users/101430",
"pm_score": 5,
"selected": false,
"text": "from timeit import *\n\nstats = [\"for i in xrange(1000): iter(s).next() \",\n \"for i in xrange(1000): \\n\\tfor x in s: \\n\\t\\tbreak\",\n \"for i in xrange(1000): s.add(s.pop()) \",\n \"for i in xrange(1000): s.get() \"]\n\nfor stat in stats:\n t = Timer(stat, setup=\"s=set(range(100))\")\n try:\n print \"Time for %s:\\t %f\"%(stat, t.timeit(number=1000))\n except:\n t.print_exc()\n $ ./test_get.py\nTime for for i in xrange(1000): iter(s).next() : 0.433080\nTime for for i in xrange(1000):\n for x in s:\n break: 0.148695\nTime for for i in xrange(1000): s.add(s.pop()) : 0.317418\nTime for for i in xrange(1000): s.get() : 0.146673\n"
},
{
"answer_id": 34973737,
"author": "AChampion",
"author_id": 2750492,
"author_profile": "https://Stackoverflow.com/users/2750492",
"pm_score": 3,
"selected": false,
"text": "from timeit import *\n\nstats = [\"for i in range(1000): next(iter(s))\",\n \"for i in range(1000): \\n\\tfor x in s: \\n\\t\\tbreak\",\n \"for i in range(1000): s.add(s.pop())\"]\n\nfor stat in stats:\n t = Timer(stat, setup=\"s=set(range(100000))\")\n try:\n print(\"Time for %s:\\t %f\"%(stat, t.timeit(number=1000)))\n except:\n t.print_exc()\n Time for for i in range(1000): next(iter(s)): 0.205888\nTime for for i in range(1000): \n for x in s: \n break: 0.083397\nTime for for i in range(1000): s.add(s.pop()): 0.226570\n remove() for iter from timeit import *\n\nstats = [\"while s:\\n\\ta = next(iter(s))\\n\\ts.remove(a)\",\n \"while s:\\n\\tfor x in s: break\\n\\ts.remove(x)\",\n \"while s:\\n\\tx=s.pop()\\n\\ts.add(x)\\n\\ts.remove(x)\"]\n\nfor stat in stats:\n t = Timer(stat, setup=\"s=set(range(100000))\")\n try:\n print(\"Time for %s:\\t %f\"%(stat, t.timeit(number=1000)))\n except:\n t.print_exc()\n Time for while s:\n a = next(iter(s))\n s.remove(a): 2.938494\nTime for while s:\n for x in s: break\n s.remove(x): 2.728367\nTime for while s:\n x=s.pop()\n s.add(x)\n s.remove(x): 0.030272\n"
},
{
"answer_id": 40054478,
"author": "Cecil Curry",
"author_id": 2809027,
"author_profile": "https://Stackoverflow.com/users/2809027",
"pm_score": 6,
"selected": false,
"text": "for first_item in muh_set: break list(s)[0] random.sample(s, 1) from timeit import Timer\n\nstats = [\n \"for i in range(1000): \\n\\tfor x in s: \\n\\t\\tbreak\",\n \"for i in range(1000): next(iter(s))\",\n \"for i in range(1000): s.add(s.pop())\",\n \"for i in range(1000): list(s)[0]\",\n \"for i in range(1000): random.sample(s, 1)\",\n]\n\nfor stat in stats:\n t = Timer(stat, setup=\"import random\\ns=set(range(100))\")\n try:\n print(\"Time for %s:\\t %f\"%(stat, t.timeit(number=1000)))\n except:\n t.print_exc()\n $ ./test_get.py\nTime for for i in range(1000): \n for x in s: \n break: 0.249871\nTime for for i in range(1000): next(iter(s)): 0.526266\nTime for for i in range(1000): s.add(s.pop()): 0.658832\nTime for for i in range(1000): list(s)[0]: 4.117106\nTime for for i in range(1000): random.sample(s, 1): 21.851104\n random set.get_first()"
},
{
"answer_id": 45803038,
"author": "skovorodkin",
"author_id": 847552,
"author_profile": "https://Stackoverflow.com/users/847552",
"pm_score": 4,
"selected": false,
"text": "e,*_=s\n [*s][0]\n"
},
{
"answer_id": 48874729,
"author": "MSeifert",
"author_id": 5393381,
"author_profile": "https://Stackoverflow.com/users/5393381",
"pm_score": 7,
"selected": false,
"text": "from random import sample\n\ndef ForLoop(s):\n for e in s:\n break\n return e\n\ndef IterNext(s):\n return next(iter(s))\n\ndef ListIndex(s):\n return list(s)[0]\n\ndef PopAdd(s):\n e = s.pop()\n s.add(e)\n return e\n\ndef RandomSample(s):\n return sample(s, 1)\n\ndef SetUnpacking(s):\n e, *_ = s\n return e\n\nfrom simple_benchmark import benchmark\n\nb = benchmark([ForLoop, IterNext, ListIndex, PopAdd, RandomSample, SetUnpacking],\n {2**i: set(range(2**i)) for i in range(1, 20)},\n argument_name='set size',\n function_aliases={first: 'First'})\n\nb.plot()\n RandomSample SetUnpacking ListIndex ForLoop iteration_utilities first >>> from iteration_utilities import first\n>>> first({1,2,3,4})\n1\n"
},
{
"answer_id": 49138346,
"author": "Solomon Ucko",
"author_id": 5445670,
"author_profile": "https://Stackoverflow.com/users/5445670",
"pm_score": -1,
"selected": false,
"text": "s.copy().pop()"
},
{
"answer_id": 60803131,
"author": "Josué Carvajal",
"author_id": 5911191,
"author_profile": "https://Stackoverflow.com/users/5911191",
"pm_score": 2,
"selected": false,
"text": "def convertSetToList(setName):\nreturn list(setName)\n userFields = convertSetToList(user)\nname = request.json[userFields[0]]\n"
},
{
"answer_id": 64224698,
"author": "seralouk",
"author_id": 5025009,
"author_profile": "https://Stackoverflow.com/users/5025009",
"pm_score": 2,
"selected": false,
"text": "s = set([1, 2, 3])\n\nv1, v2, v3 = s\n\nprint(v1,v2,v3)\n#1 2 3\n"
},
{
"answer_id": 64352862,
"author": "dzang",
"author_id": 7812912,
"author_profile": "https://Stackoverflow.com/users/7812912",
"pm_score": 4,
"selected": false,
"text": "next(iter(s))\n s.__iter__().__next__()\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
59,829 |
<p>I have a radio button list on a page that is used to configure products. when the page loads the first time the first list of options is displayed. you select one of them then click a "Next Step" button and the page posts back and shows a new radio button list for step 2. Now if i click a "Previous Step" button i can easily get the previous list of options to display but i can not for some reason get one of the radio buttons to be selected. I can easily bring back the value i need. right after making the radio button list i have a step that just says radiobuttonlist.selected = "somevalue" depending on whatever the user chose when they completed the first step the first time.</p>
<p>when i debug i see that the value is correct and is being applied. but then when the page is displayed the radiobutton is not selected.</p>
<p>I have noticed that when i click my "Previous" button while debugging the folowing steps occur.:</p>
<p>the page.load handler runs and the code inside my if not page.ispostback block does NOT run, which is correct.
then the handles for the button i just clicked gets run.
but then after that the page.load handler runs again but this time the code in the if not page.ispostback block DOES run...</p>
<p>is that normal? for the page.onload block to run twice like that on a postback? i think it may have something to do with why my value is not being applied.</p>
|
[
{
"answer_id": 59835,
"author": "ctrlShiftBryan",
"author_id": 6161,
"author_profile": "https://Stackoverflow.com/users/6161",
"pm_score": 0,
"selected": false,
"text": "AutoEventWireup = False"
},
{
"answer_id": 413434,
"author": "netseng",
"author_id": 32718,
"author_profile": "https://Stackoverflow.com/users/32718",
"pm_score": 0,
"selected": false,
"text": "yourRadioButonList.Items.FindByValue(YourSavedValue).Selected = true;\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
59,832 |
<p>I am currently calling the following line of code:</p>
<pre><code>java.net.URL connection_url = new java.net.URL("http://<ip address>:<port>/path");
</code></pre>
<p>and I get the exception above when it executes. Any ideas as to why this is happening?</p>
|
[
{
"answer_id": 59960,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 3,
"selected": true,
"text": "public static void main(String[] args) {\n try {\n java.net.URL connection_url = new java.net.URL(\"http://:/path\");\n System.out.println(\"Instantiated new URL: \" + connection_url);\n }\n catch (MalformedURLException e) {\n e.printStackTrace();\n }\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
] |
59,838 |
<p>What command checks if a directory exists or not within a Bash shell script?</p>
|
[
{
"answer_id": 59839,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 13,
"selected": true,
"text": "if [ -d \"$DIRECTORY\" ]; then\n echo \"$DIRECTORY does exist.\"\nfi\n if [ ! -d \"$DIRECTORY\" ]; then\n echo \"$DIRECTORY does not exist.\"\nfi\n ln -s \"$ACTUAL_DIR\" \"$SYMLINK\"\nif [ -d \"$SYMLINK\" ]; then \n rmdir \"$SYMLINK\" \nfi\n rmdir: failed to remove `symlink': Not a directory\n if [ -d \"$LINK_OR_DIR\" ]; then \n if [ -L \"$LINK_OR_DIR\" ]; then\n # It is a symlink!\n # Symbolic link specific commands go here.\n rm \"$LINK_OR_DIR\"\n else\n # It's a directory!\n # Directory command goes here.\n rmdir \"$LINK_OR_DIR\"\n fi\nfi\n"
},
{
"answer_id": 59853,
"author": "Neil Neyman",
"author_id": 3240,
"author_profile": "https://Stackoverflow.com/users/3240",
"pm_score": 5,
"selected": false,
"text": "find found=`find -type d -name \"myDirectory\"`\n if [ -n \"$found\" ]\n then\n # The variable 'found' contains the full path where \"myDirectory\" is.\n # It may contain several lines if there are several folders named \"myDirectory\".\n fi\n found=`find -maxdepth 1 -type d -name \"my*\"`\n if [ -n \"$found\" ]\n then\n # The variable 'found' contains the full path where folders \"my*\" have been found.\n fi\n found=`find -maxdepth 1 -type d -name \"myDirectory\"`\n if [ -n \"$found\" ]\n then\n # The variable 'found' is not empty => \"myDirectory\"` exists.\n fi\n"
},
{
"answer_id": 59871,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 8,
"selected": false,
"text": "$ ln -s tmp/ t\n$ if [ -d t ]; then rmdir t; fi\nrmdir: directory \"t\": Path component not a directory\n if [ -d t ]; then \n if [ -L t ]; then \n rm t\n else \n rmdir t\n fi\nfi\n [ [["
},
{
"answer_id": 59969,
"author": "elmarco",
"author_id": 1277510,
"author_profile": "https://Stackoverflow.com/users/1277510",
"pm_score": 8,
"selected": false,
"text": "# if $DIR is a directory, then print yes\n[ -d \"$DIR\" ] && echo \"Yes\"\n"
},
{
"answer_id": 60014,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 8,
"selected": false,
"text": "test if [[ -d \"${DIRECTORY}\" && ! -L \"${DIRECTORY}\" ]] ; then\n echo \"It's a bona-fide directory\"\nfi\n"
},
{
"answer_id": 67458,
"author": "8jean",
"author_id": 10011,
"author_profile": "https://Stackoverflow.com/users/10011",
"pm_score": 9,
"selected": false,
"text": "if [ -d \"$DIRECTORY\" ]; then\n # Will enter here if $DIRECTORY exists, even if it contains spaces\nfi\n $DIRECTORY \"My M0viez\""
},
{
"answer_id": 1288121,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "[ -d . ] || echo \"No\"\n"
},
{
"answer_id": 2283055,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 5,
"selected": false,
"text": "DIR_PATH=`readlink -f \"${the_stuff_you_test}\"` # Get rid of symlinks and get abs path\nif [[ -d \"${DIR_PATH}\" ]] ; Then # Now you're testing\n echo \"It's a dir\";\nfi\n \"${}\" [[]] []"
},
{
"answer_id": 2469169,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "if [ -d \"$DIRECTORY\" ]; then\n # Will enter here if $DIRECTORY exists\nfi\n if [ -d \"$DIRECTORY\" ] && [ -x \"$DIRECTORY\" ] ; then\n # ... to go to that directory (even if DIRECTORY is a link)\n cd $DIRECTORY\n pwd\nfi\n if [ -d \"$DIRECTORY\" ] && [ -w \"$DIRECTORY\" ] ; then\n # ... to go to that directory and write something there (even if DIRECTORY is a link)\n cd $DIRECTORY\n touch foobar\nfi\n"
},
{
"answer_id": 2680681,
"author": "muralikrishna",
"author_id": 321968,
"author_profile": "https://Stackoverflow.com/users/321968",
"pm_score": 5,
"selected": false,
"text": "if [ -d \"$Directory\" -a -w \"$Directory\" ]\nthen\n #Statements\nfi\n"
},
{
"answer_id": 7436646,
"author": "ztank1013",
"author_id": 938615,
"author_profile": "https://Stackoverflow.com/users/938615",
"pm_score": 3,
"selected": false,
"text": "ls -l ls -l d - d ISDIR [[ $(ls -ld \"$ISDIR\" | cut -c1) == 'd' ]] &&\n echo \"YES, $ISDIR is a directory.\" || \n echo \"Sorry, $ISDIR is not a directory\"\n [claudio@nowhere ~]$ ISDIR=\"$HOME/Music\" \n [claudio@nowhere ~]$ ls -ld \"$ISDIR\"\n drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music\n [claudio@nowhere ~]$ [[ $(ls -ld \"$ISDIR\" | cut -c1) == 'd' ]] && \n echo \"YES, $ISDIR is a directory.\" ||\n echo \"Sorry, $ISDIR is not a directory\"\n YES, /home/claudio/Music is a directory.\n\n [claudio@nowhere ~]$ touch \"empty file.txt\"\n [claudio@nowhere ~]$ ISDIR=\"$HOME/empty file.txt\" \n [claudio@nowhere ~]$ [[ $(ls -ld \"$ISDIR\" | cut -c1) == 'd' ]] && \n echo \"YES, $ISDIR is a directory.\" || \n echo \"Sorry, $ISDIR is not a directoy\"\n Sorry, /home/claudio/empty file.txt is not a directory\n"
},
{
"answer_id": 8480518,
"author": "dromichaetes",
"author_id": 1094365,
"author_profile": "https://Stackoverflow.com/users/1094365",
"pm_score": 3,
"selected": false,
"text": "if [ -d \"$LINK_OR_DIR\" ]; then\nif [ -L \"$LINK_OR_DIR\" ]; then\n # It is a symlink!\n # Symbolic link specific commands go here\n rm \"$LINK_OR_DIR\"\nelse\n # It's a directory!\n # Directory command goes here\n rmdir \"$LINK_OR_DIR\"\nfi\nfi\n dir=\" \"\necho \"Input directory name to search for:\"\nread dir\nfind $HOME -name $dir -type d\n"
},
{
"answer_id": 11892411,
"author": "Henk Langeveld",
"author_id": 667820,
"author_profile": "https://Stackoverflow.com/users/667820",
"pm_score": 6,
"selected": false,
"text": "(cd $dir) || return # Is this a directory,\n # and do we have access?\n can_use_as_dir() {\n (cd ${1:?pathname expected}) || return\n}\n assert_dir_access() {\n (cd ${1:?pathname expected}) || exit\n}\n cd cd ( ... ) cd ${1:?pathname expected} ( ... ) ksh93 ${parameter:?word}\n parameter word word : word 1: parameter not set pathname pathname directory"
},
{
"answer_id": 15015952,
"author": "ajmartin",
"author_id": 477522,
"author_profile": "https://Stackoverflow.com/users/477522",
"pm_score": 3,
"selected": false,
"text": "file=\"foo\" \nif [[ -e \"$file\" ]]; then echo \"File Exists\"; fi;\n"
},
{
"answer_id": 16093972,
"author": "Juan Carlos Kuri Pinto",
"author_id": 1408995,
"author_profile": "https://Stackoverflow.com/users/1408995",
"pm_score": 4,
"selected": false,
"text": "[ -d ~/Desktop/TEMPORAL/ ] && echo \"DIRECTORY EXISTS\" || echo \"DIRECTORY DOES NOT EXIST\"\n"
},
{
"answer_id": 17859049,
"author": "bailey86",
"author_id": 450406,
"author_profile": "https://Stackoverflow.com/users/450406",
"pm_score": 4,
"selected": false,
"text": "-e if [ -e ${FILE_PATH_AND_NAME} ]\nthen\n echo \"The file or directory exists.\"\nfi\n"
},
{
"answer_id": 20978574,
"author": "derFunk",
"author_id": 591004,
"author_profile": "https://Stackoverflow.com/users/591004",
"pm_score": 3,
"selected": false,
"text": "ls $DIR\nif [ $? != 0 ]; then\n echo \"Directory $DIR already exists!\"\n exit 1;\nfi\necho \"Directory $DIR does not exist...\"\n"
},
{
"answer_id": 25287796,
"author": "Sadhun",
"author_id": 3455684,
"author_profile": "https://Stackoverflow.com/users/3455684",
"pm_score": 3,
"selected": false,
"text": "find find . -type d -name dirname -prune -print\n"
},
{
"answer_id": 29505062,
"author": "Jorge Barroso",
"author_id": 4761359,
"author_profile": "https://Stackoverflow.com/users/4761359",
"pm_score": 7,
"selected": false,
"text": "if if [ -d directory/path to a directory ] ; then\n# Things to do\n\nelse #if needed #also: elif [new condition]\n# Things to do\nfi\n if [ ! -d directory/path to a directory ] ; then\n# Things to do when not an existing directory\n -e: any kind of archive\n\n-f: file\n\n-h: symbolic link\n\n-r: readable file\n\n-w: writable file\n\n-x: executable file\n\n-s: file size greater than zero\n"
},
{
"answer_id": 29724604,
"author": "Jahid",
"author_id": 3744681,
"author_profile": "https://Stackoverflow.com/users/3744681",
"pm_score": 4,
"selected": false,
"text": "[[ -d \"$DIR\" && ! -L \"$DIR\" ]] && echo \"It's a directory and not a symbolic link\"\n -d -L"
},
{
"answer_id": 30208219,
"author": "Piyush Baijal",
"author_id": 2458462,
"author_profile": "https://Stackoverflow.com/users/2458462",
"pm_score": 3,
"selected": false,
"text": "[ -d Piyush_Drv1 ] && echo \"\"Exists\"\" || echo \"Not Exists\"\n [ `find . -type d -name Piyush_Drv1 -print | wc -l` -eq 1 ] && echo Exists || echo \"Not Exists\"\n [[ -d run_dir && ! -L run_dir ]] && echo Exists || echo \"Not Exists\"\n ls [[ `ls -ld SAMPLE_DIR| grep ^d | wc -l` -eq 1 ]] && echo exists || not exists\n"
},
{
"answer_id": 32543846,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 3,
"selected": false,
"text": "mkdir -p mkdir -p /some/directory/you/want/to/exist || exit 1\n"
},
{
"answer_id": 32543895,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 7,
"selected": false,
"text": "test -d man test -d file test -d \"/etc\" && echo Exists || echo Does not exist\n test [ man [ [ test ] [ help [ help test man test man ["
},
{
"answer_id": 34508422,
"author": "Raamesh Keerthi",
"author_id": 1116081,
"author_profile": "https://Stackoverflow.com/users/1116081",
"pm_score": 4,
"selected": false,
"text": "if [ -d \"$DIRECTORY1\" ] && [ -d \"$DIRECTORY2\" ] then\n # Things to do\nfi\n"
},
{
"answer_id": 36172057,
"author": "David Okwii",
"author_id": 547050,
"author_profile": "https://Stackoverflow.com/users/547050",
"pm_score": 4,
"selected": false,
"text": "[ -d \"$DIRECTORY\" ] || mkdir $DIRECTORY\n"
},
{
"answer_id": 36654179,
"author": "Brad Parks",
"author_id": 26510,
"author_profile": "https://Stackoverflow.com/users/26510",
"pm_score": 4,
"selected": false,
"text": "$ is_dir ~ \nYES\n\n$ is_dir /tmp \nYES\n\n$ is_dir ~/bin \nYES\n\n$ mkdir '/tmp/test me'\n\n$ is_dir '/tmp/test me'\nYES\n\n$ is_dir /asdf/asdf \nNO\n\n# Example of calling it in another script\nDIR=~/mydata\nif [ $(is_dir $DIR) == \"NO\" ]\nthen\n echo \"Folder doesnt exist: $DIR\";\n exit;\nfi\n function show_help()\n{\n IT=$(CAT <<EOF\n\n usage: DIR\n output: YES or NO, depending on whether or not the directory exists.\n\n )\n echo \"$IT\"\n exit\n}\n\nif [ \"$1\" == \"help\" ]\nthen\n show_help\nfi\nif [ -z \"$1\" ]\nthen\n show_help\nfi\n\nDIR=$1\nif [ -d $DIR ]; then \n echo \"YES\";\n exit;\nfi\necho \"NO\";\n"
},
{
"answer_id": 43426718,
"author": "Abhishek Gurjar",
"author_id": 5345150,
"author_profile": "https://Stackoverflow.com/users/5345150",
"pm_score": 3,
"selected": false,
"text": "[ -d \"$directory\" ] && echo \"exist\" || echo \"not exist\"\n test test -d \"$directory\" && echo \"exist\" || echo \"not exist\"\n"
},
{
"answer_id": 44835790,
"author": "Gene",
"author_id": 2057089,
"author_profile": "https://Stackoverflow.com/users/2057089",
"pm_score": 2,
"selected": false,
"text": "if [ -d /home/ec2-user/apache-tomcat-8.5.5/webapps/Gene\\ Directory ]; then\n echo \"Directory exists!\"\n echo \"Great\"\nfi\n if [ -d '/home/ec2-user/apache-tomcat-8.5.5/webapps/Gene Directory' ]; then\n echo \"Directory exists!\"\n echo \"Great\"\nfi\n"
},
{
"answer_id": 46205746,
"author": "KANJICODER",
"author_id": 1740154,
"author_profile": "https://Stackoverflow.com/users/1740154",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\ndbox=\"~/Dropbox/\"\nresult=0\nprv=$(pwd) && eval \"cd $dbox\" && result=1 && cd \"$prv\"\necho $result\n\nread -p \"Press Enter To Continue:\"\n"
},
{
"answer_id": 47699462,
"author": "ArtOfWarfare",
"author_id": 901641,
"author_profile": "https://Stackoverflow.com/users/901641",
"pm_score": 5,
"selected": false,
"text": "if if pushd /path/you/want/to/enter; then\n # Commands you want to run in this directory\n popd\nfi\n pushd 0 then if [ -d /path/you/want/to/enter ]; then\n pushd /path/you/want/to/enter\n # Commands you want to run in this directory\n popd\nfi\n cd mv rm then 0 then"
},
{
"answer_id": 50342967,
"author": "yoctotutor.com",
"author_id": 6484851,
"author_profile": "https://Stackoverflow.com/users/6484851",
"pm_score": 7,
"selected": false,
"text": " if [ -d /home/ram/dir ] # For file \"if [ -f /home/rama/file ]\"\n then\n echo \"dir present\"\n else\n echo \"dir not present\"\n fi\n mkdir tempdir # If you want to check file use touch instead of mkdir\n ret=$?\n if [ \"$ret\" == \"0\" ]\n then\n echo \"dir present\"\n else\n echo \"dir not present\"\n fi\n $? tempdir mkdir tempdir"
},
{
"answer_id": 51017848,
"author": "Sudip Bhandari",
"author_id": 4589003,
"author_profile": "https://Stackoverflow.com/users/4589003",
"pm_score": 3,
"selected": false,
"text": "file file $directory_name file blah cannot open 'blah' (No such file or directory) file bluh bluh: directory"
},
{
"answer_id": 57223290,
"author": "Bayou",
"author_id": 8382929,
"author_profile": "https://Stackoverflow.com/users/8382929",
"pm_score": 2,
"selected": false,
"text": "stat #! /bin/bash\nMY_DIR=$1\nNODE_TYPE=$(stat -c '%F' ${MY_DIR} 2>/dev/null)\ncase \"${NODE_TYPE}\" in\n \"directory\") echo $MY_DIR;;\n \"symbolic link\") echo $(readlink $MY_DIR);;\n \"\") echo \"$MY_DIR does not exist\";;\n *) echo \"$NODE_TYPE is unsupported\";;\nesac\nexit 0\n $ mkdir tmp\n$ ln -s tmp derp\n$ touch a.txt\n$ ./dir.sh tmp\ntmp\n$ ./dir.sh derp\ntmp\n$ ./dir.sh a.txt\nregular file is unsupported\n$ ./dir.sh god\ngod does not exist\n"
},
{
"answer_id": 58297948,
"author": "Vishal",
"author_id": 197473,
"author_profile": "https://Stackoverflow.com/users/197473",
"pm_score": 5,
"selected": false,
"text": "DIRECTORY=/tmp\n\nif [ -d \"$DIRECTORY\" ]; then\n echo \"Exists\"\nfi\n"
},
{
"answer_id": 71447129,
"author": "Aybak3k",
"author_id": 16146522,
"author_profile": "https://Stackoverflow.com/users/16146522",
"pm_score": 3,
"selected": false,
"text": "[[ -d $Directory ]] && echo true\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120/"
] |
59,850 |
<p>I'd like to create a spring bean that holds the value of a double. Something like:</p>
<pre><code><bean id="doubleValue" value="3.7"/>
</code></pre>
|
[
{
"answer_id": 59875,
"author": "Pavel Feldman",
"author_id": 5507,
"author_profile": "https://Stackoverflow.com/users/5507",
"pm_score": 5,
"selected": true,
"text": "<bean id=\"doubleValue\" class=\"java.lang.Double\">\n <constructor-arg index=\"0\" value=\"3.7\"/>\n</bean>\n <bean id=\"someOtherBean\" ...>\n <property name=\"value\" ref=\"doubleValue\"/>\n</bean>\n"
},
{
"answer_id": 73838,
"author": "enricopulatzo",
"author_id": 9883,
"author_profile": "https://Stackoverflow.com/users/9883",
"pm_score": 3,
"selected": false,
"text": "<util:constant static-field=\"org.example.Constants.FOO\"/>\n <bean class=\"Foo\" p:doubleValue=\"123.00\"/>\n <bean id=\"d1\" class=\"java.lang.Double\">\n <constructor-arg value=\"3.7\"/>\n</bean>\n<bean id=\"foo\" class=\"Foo\">\n <property name=\"doubleVal\" ref=\"d1\"/>\n</bean>\n <bean\n id=\"propertyFile\"\n class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"\n p:location=\"classpath:my.properties\"\n/>\n<bean id=\"foo\" class=\"Foo\" p:doubleVal=\"${d1}\"/>\n"
},
{
"answer_id": 48786968,
"author": "Subin Chalil",
"author_id": 2756662,
"author_profile": "https://Stackoverflow.com/users/2756662",
"pm_score": 0,
"selected": false,
"text": "@Configuration\npublic class BeanConfig {\n @Bean\n public Double doubleBean(){\n return new Double(3.7);\n }\n}\n @Autowired\nDouble doubleBean;\n\npublic void printDouble(){\n System.out.println(doubleBean); //sample usage\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] |
59,857 |
<p>Should I use a dedicated network channel between the database and the application server?</p>
<p>...or... </p>
<p>Connecting both in the switch along with all other computer nodes makes no diference at all?</p>
<p>The matter is <strong>performance!</strong></p>
|
[
{
"answer_id": 59875,
"author": "Pavel Feldman",
"author_id": 5507,
"author_profile": "https://Stackoverflow.com/users/5507",
"pm_score": 5,
"selected": true,
"text": "<bean id=\"doubleValue\" class=\"java.lang.Double\">\n <constructor-arg index=\"0\" value=\"3.7\"/>\n</bean>\n <bean id=\"someOtherBean\" ...>\n <property name=\"value\" ref=\"doubleValue\"/>\n</bean>\n"
},
{
"answer_id": 73838,
"author": "enricopulatzo",
"author_id": 9883,
"author_profile": "https://Stackoverflow.com/users/9883",
"pm_score": 3,
"selected": false,
"text": "<util:constant static-field=\"org.example.Constants.FOO\"/>\n <bean class=\"Foo\" p:doubleValue=\"123.00\"/>\n <bean id=\"d1\" class=\"java.lang.Double\">\n <constructor-arg value=\"3.7\"/>\n</bean>\n<bean id=\"foo\" class=\"Foo\">\n <property name=\"doubleVal\" ref=\"d1\"/>\n</bean>\n <bean\n id=\"propertyFile\"\n class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"\n p:location=\"classpath:my.properties\"\n/>\n<bean id=\"foo\" class=\"Foo\" p:doubleVal=\"${d1}\"/>\n"
},
{
"answer_id": 48786968,
"author": "Subin Chalil",
"author_id": 2756662,
"author_profile": "https://Stackoverflow.com/users/2756662",
"pm_score": 0,
"selected": false,
"text": "@Configuration\npublic class BeanConfig {\n @Bean\n public Double doubleBean(){\n return new Double(3.7);\n }\n}\n @Autowired\nDouble doubleBean;\n\npublic void printDouble(){\n System.out.println(doubleBean); //sample usage\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
59,880 |
<p>Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them <strong>ALL THE TIME</strong>.</p>
<p>I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored procedures are necessary in modern databases such as MySQL, SQL Server, Oracle, or <<em>Insert_your_DB_here</em>>. Is it overkill to have ALL access through stored procedures?</p>
|
[
{
"answer_id": 59932,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 9,
"selected": true,
"text": "SELECT *\n FROM table WHERE id BETWEEN 1 AND\n 99999999 SELECT * FROM table WHERE id BETWEEN\n 1 AND 2 SELECT .. FROM yourtable WHERE foo = ? AND bar = ?\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
] |
59,895 |
<p>How do I get the path of the directory in which a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> script is located, <em>inside</em> that script?</p>
<p>I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:</p>
<pre><code>$ ./application
</code></pre>
|
[
{
"answer_id": 59916,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 10,
"selected": false,
"text": "dirname \"$0\" #!/usr/bin/env bash\n\necho \"The script you are running has basename $( basename -- \"$0\"; ), dirname $( dirname -- \"$0\"; )\";\necho \"The present working directory is $( pwd; )\";\n pwd [matt@server1 ~]$ pwd\n/home/matt\n[matt@server1 ~]$ ./test2.sh\nThe script you are running has basename test2.sh, dirname .\nThe present working directory is /home/matt\n[matt@server1 ~]$ cd /tmp\n[matt@server1 tmp]$ ~/test2.sh\nThe script you are running has basename test2.sh, dirname /home/matt\nThe present working directory is /tmp\n"
},
{
"answer_id": 59921,
"author": "Mr Shark",
"author_id": 6093,
"author_profile": "https://Stackoverflow.com/users/6093",
"pm_score": 7,
"selected": false,
"text": "$BASH_SOURCE #!/usr/bin/env bash\n\nscriptdir=\"$( dirname -- \"$BASH_SOURCE\"; )\";\n #!/bin/bash #!/bin/sh"
},
{
"answer_id": 60232,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "pwd $0 ./script\n\n/usr/bin/script\n\nscript\n $0 pwd /usr/share /usr/bin"
},
{
"answer_id": 60247,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "#!/bin/sh\nPRG=\"$0\"\n\n# need this for relative symlinks\nwhile [ -h \"$PRG\" ] ; do\n PRG=`readlink \"$PRG\"`\ndone\n\nscriptdir=`dirname \"$PRG\"`\n"
},
{
"answer_id": 66271,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 6,
"selected": false,
"text": "pwd dirname $0 dirname $0 dirname dirname #!/usr/bin/env bash\n\nreldir=\"$( dirname -- \"$0\"; )\";\ncd \"$reldir\";\ndirectory=\"$( pwd; )\";\n\necho \"Directory is ${directory}\";\n pwd cd \"$( dirname -- \"$0\"; )\";\n"
},
{
"answer_id": 76257,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 5,
"selected": false,
"text": "SELF=$(readlink /proc/$$/fd/255)\n"
},
{
"answer_id": 179231,
"author": "user25866",
"author_id": 25866,
"author_profile": "https://Stackoverflow.com/users/25866",
"pm_score": 8,
"selected": false,
"text": "pushd . > '/dev/null';\nSCRIPT_PATH=\"${BASH_SOURCE[0]:-$0}\";\n\nwhile [ -h \"$SCRIPT_PATH\" ];\ndo\n cd \"$( dirname -- \"$SCRIPT_PATH\"; )\";\n SCRIPT_PATH=\"$( readlink -f -- \"$SCRIPT_PATH\"; )\";\ndone\n\ncd \"$( dirname -- \"$SCRIPT_PATH\"; )\" > '/dev/null';\nSCRIPT_PATH=\"$( pwd; )\";\npopd > '/dev/null';\n source . $0 \"./script\" \"/full/path/to/script\" \"/some/path/../../another/path/script\" \"./some/folder/script\" pushd . > '/dev/null';\nSCRIPT_PATH=\"${BASH_SOURCE[0]:-$0}\";\n\nwhile [ -h \"$SCRIPT_PATH\" ];\ndo\n cd \"$( dirname -- \"$SCRIPT_PATH\"; )\";\n SCRIPT_PATH=\"$( readlink -f -- \"$SCRIPT_PATH\"; )\";\ndone\n\ncd \"$( dirname -- \"$SCRIPT_PATH\"; )\" > '/dev/null';\nSCRIPT_PATH=\"$( pwd; )\";\npopd > '/dev/null';\n SCRIPT_PATH"
},
{
"answer_id": 201915,
"author": "Matt Tardiff",
"author_id": 27925,
"author_profile": "https://Stackoverflow.com/users/27925",
"pm_score": 4,
"selected": false,
"text": "path=\"$( dirname \"$( which \"$0\" )\" )\"\n ~/bin $PATH A ~/bin/lib/B lib A source \"$( dirname \"$( which \"$0\" )\" )/lib/B\"\n"
},
{
"answer_id": 246128,
"author": "dogbane",
"author_id": 7412,
"author_profile": "https://Stackoverflow.com/users/7412",
"pm_score": 14,
"selected": true,
"text": "#!/usr/bin/env bash\n\nSCRIPT_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\n #!/usr/bin/env bash\n\nSOURCE=${BASH_SOURCE[0]}\nwhile [ -L \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n DIR=$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\n SOURCE=$(readlink \"$SOURCE\")\n [[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\n source bash -c cd $CDPATH update_terminal_cwd >&2 >/dev/null 2>&1 cd #!/usr/bin/env bash\n\nSOURCE=${BASH_SOURCE[0]}\nwhile [ -L \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n TARGET=$(readlink \"$SOURCE\")\n if [[ $TARGET == /* ]]; then\n echo \"SOURCE '$SOURCE' is an absolute symlink to '$TARGET'\"\n SOURCE=$TARGET\n else\n DIR=$( dirname \"$SOURCE\" )\n echo \"SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')\"\n SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\n fi\ndone\necho \"SOURCE is '$SOURCE'\"\nRDIR=$( dirname \"$SOURCE\" )\nDIR=$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\nif [ \"$DIR\" != \"$RDIR\" ]; then\n echo \"DIR '$RDIR' resolves to '$DIR'\"\nfi\necho \"DIR is '$DIR'\"\n SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')\nSOURCE is './sym2/scriptdir.sh'\nDIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'\nDIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'\n"
},
{
"answer_id": 337006,
"author": "Fabien",
"author_id": 21132,
"author_profile": "https://Stackoverflow.com/users/21132",
"pm_score": 7,
"selected": false,
"text": "\"`dirname -- \"$0\";`\"\n \"$( dirname -- \"$0\"; )\"\n"
},
{
"answer_id": 476266,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "LIBDIR=$(dirname \"$(readlink -f \"$(type -P $0 || echo $0)\")\")\nsource $LIBDIR/lib.sh\n"
},
{
"answer_id": 476333,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 3,
"selected": false,
"text": "basename dirname SELF=`readlink /proc/$$/fd/255`\n"
},
{
"answer_id": 541672,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "cd $(dirname $(which $0) )\n DIR=$(/usr/bin/pwd)\n"
},
{
"answer_id": 748265,
"author": "BillTorpey",
"author_id": 62513,
"author_profile": "https://Stackoverflow.com/users/62513",
"pm_score": 2,
"selected": false,
"text": "SCRIPT_DIR=$(dirname $(cd \"$(dirname \"$BASH_SOURCE\")\"; pwd))\n"
},
{
"answer_id": 1482133,
"author": "phatblat",
"author_id": 39207,
"author_profile": "https://Stackoverflow.com/users/39207",
"pm_score": 9,
"selected": false,
"text": "dirname $0 dirname -- \"$0\";\n pwd readlink dirname -- \"$( readlink -f -- \"$0\"; )\";\n readlink whatdir.sh #!/usr/bin/env bash\n\necho \"pwd: `pwd`\"\necho \"\\$0: $0\"\necho \"basename: `basename -- \"$0\"`\"\necho \"dirname: `dirname -- \"$0\"`\"\necho \"dirname/readlink: $( dirname -- \"$( readlink -f -- \"$0\"; )\"; )\"\n >>>$ ./whatdir.sh\npwd: /Users/phatblat\n$0: ./whatdir.sh\nbasename: whatdir.sh\ndirname: .\ndirname/readlink: /Users/phatblat\n >>>$ /Users/phatblat/whatdir.sh\npwd: /Users/phatblat\n$0: /Users/phatblat/whatdir.sh\nbasename: whatdir.sh\ndirname: /Users/phatblat\ndirname/readlink: /Users/phatblat\n >>>$ cd /tmp\n>>>$ ~/whatdir.sh\npwd: /tmp\n$0: /Users/phatblat/whatdir.sh\nbasename: whatdir.sh\ndirname: /Users/phatblat\ndirname/readlink: /Users/phatblat\n >>>$ ln -s ~/whatdir.sh whatdirlink.sh\n>>>$ ./whatdirlink.sh\npwd: /tmp\n$0: ./whatdirlink.sh\nbasename: whatdirlink.sh\ndirname: .\ndirname/readlink: /Users/phatblat\n >>>$ cd /tmp\n>>>$ . ~/whatdir.sh \npwd: /tmp\n$0: bash\nbasename: bash\ndirname: .\ndirname/readlink: /tmp\n"
},
{
"answer_id": 1815323,
"author": "Stefano Borini",
"author_id": 78374,
"author_profile": "https://Stackoverflow.com/users/78374",
"pm_score": -1,
"selected": false,
"text": "function getScriptAbsoluteDir { # fold>>\n # @description used to get the script path\n # @param $1 the script $0 parameter\n local script_invoke_path=\"$1\"\n local cwd=`pwd`\n\n # absolute path ? if so, the first character is a /\n if test \"x${script_invoke_path:0:1}\" = 'x/'\n then\n RESULT=`dirname \"$script_invoke_path\"`\n else\n RESULT=`dirname \"$cwd/$script_invoke_path\"`\n fi\n} # <<fold\n"
},
{
"answer_id": 2633580,
"author": "Fuwjax",
"author_id": 315943,
"author_profile": "https://Stackoverflow.com/users/315943",
"pm_score": 4,
"selected": false,
"text": "SCRIPT_DIR=''\npushd \"$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")\" > /dev/null && {\n SCRIPT_DIR=\"$PWD\"\n popd > /dev/null\n}\n popd pushd"
},
{
"answer_id": 3674520,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "/var/No one/Thought/About Spaces Being/In a Directory/Name/And Here's your file.text\n #!/bin/bash\necho \"pwd: `pwd`\"\necho \"\\$0: $0\"\necho \"basename: `basename \"$0\"`\"\necho \"dirname: `dirname \"$0\"`\"\n cd \"`dirname \"$0\"`\"\n"
},
{
"answer_id": 3774351,
"author": "tigfox",
"author_id": 455644,
"author_profile": "https://Stackoverflow.com/users/455644",
"pm_score": 3,
"selected": false,
"text": "SCRIPT_LOC=\"`ps -p $$ | sed /PID/d | sed s:.*/Network/:/Network/: |\nsed s:.*/Volumes/:/Volumes/:`\"\n"
},
{
"answer_id": 3884245,
"author": "P M",
"author_id": 396782,
"author_profile": "https://Stackoverflow.com/users/396782",
"pm_score": 5,
"selected": false,
"text": "SCRIPT_DIR=$( cd ${0%/*} && pwd -P )\n"
},
{
"answer_id": 3921651,
"author": "alanwj",
"author_id": 60873,
"author_profile": "https://Stackoverflow.com/users/60873",
"pm_score": 3,
"selected": false,
"text": "script=\"`readlink -f \"${BASH_SOURCE[0]}\"`\"\ndir=\"`dirname \"$script\"`\"\n"
},
{
"answer_id": 4560790,
"author": "Pubguy",
"author_id": 558024,
"author_profile": "https://Stackoverflow.com/users/558024",
"pm_score": 5,
"selected": false,
"text": "DIR=$(cd \"$(dirname \"$0\")\"; pwd)\n"
},
{
"answer_id": 6840978,
"author": "test11",
"author_id": 864899,
"author_profile": "https://Stackoverflow.com/users/864899",
"pm_score": 5,
"selected": false,
"text": "$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")\n"
},
{
"answer_id": 7449270,
"author": "hurrymaplelad",
"author_id": 407845,
"author_profile": "https://Stackoverflow.com/users/407845",
"pm_score": 4,
"selected": false,
"text": "$_ $0 DIR=\"$( dirname \"$_\" )\"\n"
},
{
"answer_id": 9158888,
"author": "DarkPark",
"author_id": 1192073,
"author_profile": "https://Stackoverflow.com/users/1192073",
"pm_score": 4,
"selected": false,
"text": "real=$(realpath \"$(dirname \"$0\")\")\n"
},
{
"answer_id": 13486116,
"author": "Nicolas",
"author_id": 1433151,
"author_profile": "https://Stackoverflow.com/users/1433151",
"pm_score": 4,
"selected": false,
"text": "# Retrieve the full pathname of the called script\nscriptPath=$(which $0)\n\n# Check whether the path is a link or not\nif [ -L $scriptPath ]; then\n\n # It is a link then retrieve the target path and get the directory name\n sourceDir=$(dirname $(readlink -f $scriptPath))\n\nelse\n\n # Otherwise just get the directory name of the script path\n sourceDir=$(dirname $scriptPath)\n\nfi\n"
},
{
"answer_id": 14881364,
"author": "Zombo",
"author_id": 1002260,
"author_profile": "https://Stackoverflow.com/users/1002260",
"pm_score": 0,
"selected": false,
"text": "$ cat a.sh\nBASENAME=${BASH_SOURCE/*\\/}\nDIRNAME=${BASH_SOURCE%$BASENAME}.\necho $DIRNAME\n\n$ a.sh\n/usr/local/bin/.\n\n$ ./a.sh\n./.\n\n$ . a.sh\n/usr/local/bin/.\n\n$ /usr/local/bin/a.sh\n/usr/local/bin/.\n"
},
{
"answer_id": 15255856,
"author": "lamawithonel",
"author_id": 2044979,
"author_profile": "https://Stackoverflow.com/users/2044979",
"pm_score": 5,
"selected": false,
"text": "SCRIPT_PATH=`dirname \"$0\"`; SCRIPT_PATH=`eval \"cd \\\"$SCRIPT_PATH\\\" && pwd\"`\n\n# test\necho $SCRIPT_PATH\n"
},
{
"answer_id": 16131743,
"author": "billyjmc",
"author_id": 558709,
"author_profile": "https://Stackoverflow.com/users/558709",
"pm_score": 3,
"selected": false,
"text": "script bash script bash -c script source script . script proc /dev/pts/X resolved=\"$(readlink /proc/$$/fd/255 && echo X)\" && resolved=\"${resolved%$'\\nX'}\"\n readlink echo X X ${VAR%X} X readlink $'' \\n proc ls readlink ls ? absolute_path=$(readlink -e -- \"${BASH_SOURCE[0]}\" && echo x) && absolute_path=${absolute_path%?x}\ndir=$(dirname -- \"$absolute_path\" && echo x) && dir=${dir%?x}\nfile=$(basename -- \"$absolute_path\" && echo x) && file=${file%?x}\n\nls -l -- \"$dir/$file\"\nprintf '$absolute_path: \"%s\"\\n' \"$absolute_path\"\n"
},
{
"answer_id": 17011222,
"author": "mproffitt",
"author_id": 2452553,
"author_profile": "https://Stackoverflow.com/users/2452553",
"pm_score": -1,
"selected": false,
"text": "[ \"$(dirname $0)\" = '.' ] && SOURCE_DIR=$(pwd) || SOURCE_DIR=$(dirname $0);\nls -l $0 | grep -q ^l && SOURCE_DIR=$(ls -l $0 | awk '{print $NF}');\n pwd"
},
{
"answer_id": 19153434,
"author": "AsymLabs",
"author_id": 2839332,
"author_profile": "https://Stackoverflow.com/users/2839332",
"pm_score": -1,
"selected": false,
"text": "function get_realpath() {\n\nif [[ -f \"$1\" ]]\nthen\n # The file *must* exist\n if cd \"$(echo \"${1%/*}\")\" &>/dev/null\n then\n # The file *may* not be local.\n # The exception is ./file.ext\n # tTry 'cd .; cd -;' *works!*\n local tmppwd=\"$PWD\"\n cd - &>/dev/null\n else\n # file *must* be local\n local tmppwd=\"$PWD\"\n fi\nelse\n # The file *cannot* exist\n return 1 # Failure\nfi\n\n# Reassemble realpath\necho \"$tmppwd\"/\"${1##*/}\"\nreturn 0 # Success\n\n}\n\nfunction get_dirname(){\n\nlocal realpath=\"$(get_realpath \"$1\")\"\nif (( $? )) # True when non-zero.\nthen\n return $? # Failure\nfi\necho \"${realpath%/*}\"\nreturn 0 # Success\n\n}\n\n# Then from the top level:\nget_dirname './script.sh'\n\n# Or within a script:\nget_dirname \"$0\"\n\n# Can even test the outcome!\nif (( $? )) # True when non-zero.\nthen\n exit 1 # Failure\nfi\n source '/path/to/realpath-lib'\n\nget_dirname \"$0\"\n\nif (( $? )) # True when non-zero.\nthen\n exit 1 # Failure\nfi\n"
},
{
"answer_id": 19250386,
"author": "AsymLabs",
"author_id": 2839332,
"author_profile": "https://Stackoverflow.com/users/2839332",
"pm_score": 3,
"selected": false,
"text": "\"$( cd \"$( echo \"${BASH_SOURCE[0]%/*}\" )\"; pwd )\"\n dirname readlink basename"
},
{
"answer_id": 20228026,
"author": "mikeserv",
"author_id": 2955202,
"author_profile": "https://Stackoverflow.com/users/2955202",
"pm_score": 0,
"selected": false,
"text": "$1 eval eval info coreutils $0 % _abs_0() {\n> o1=\"${1%%/*}\"; ${o1:=\"${1}\"}; ${o1:=`realpath -s \"${1}\"`}; eval \"$1=\\${o1}\";\n> }\n% _abs_0 ${abs0:=\"${0}\"} ; printf %s\\\\n \"${abs0}\"\n/no/more/dots/in/your/path2.sh\n $0 symlinks realpath ps ps ps ww -fp $$ | grep -Eo '/[^:]*'\"${0#*/}\"\n\neval \"abs0=${`ps ww -fp $$ | grep -Eo ' /'`#?}\"\n func () {\nbody here\neval \"$1=\\${foo}\"\n}\n ${foo} “$1” “${foo}” “$” foo='hello ; rm -rf /'\ndest=bar\neval \"$dest=$foo\"\n foo='hello ; rm -rf /'\ndest=bar\neval \"$dest=\\$foo\"\n “$1” “$@” “$1”"
},
{
"answer_id": 20265752,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 3,
"selected": false,
"text": "CWD=\"$(cd -P -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n realpath readlink ${BASH_SOURCE[0]} $0 source . realpath () {\n [[ $1 = /* ]] && echo \"$1\" || echo \"$PWD/${1#./}\"\n}\n $PWD ./"
},
{
"answer_id": 20721819,
"author": "Geoff Nixon",
"author_id": 2351351,
"author_profile": "https://Stackoverflow.com/users/2351351",
"pm_score": 3,
"selected": false,
"text": "#!/bin/sh # dash bash ksh # !zsh (issues). G. Nixon, 12/2013. Public domain.\n\n## 'linkread' or 'fullpath' or (you choose) is a little tool to recursively\n## dereference symbolic links (ala 'readlink') until the originating file\n## is found. This is effectively the same function provided in stdlib.h as\n## 'realpath' and on the command line in GNU 'readlink -f'.\n\n## Neither of these tools, however, are particularly accessible on the many\n## systems that do not have the GNU implementation of readlink, nor ship\n## with a system compiler (not to mention the requisite knowledge of C).\n\n## This script is written with portability and (to the extent possible, speed)\n## in mind, hence the use of printf for echo and case statements where they\n## can be substituded for test, though I've had to scale back a bit on that.\n\n## It is (to the best of my knowledge) written in standard POSIX shell, and\n## has been tested with bash-as-bin-sh, dash, and ksh93. zsh seems to have\n## issues with it, though I'm not sure why; so probably best to avoid for now.\n\n## Particularly useful (in fact, the reason I wrote this) is the fact that\n## it can be used within a shell script to find the path of the script itself.\n## (I am sure the shell knows this already; but most likely for the sake of\n## security it is not made readily available. The implementation of \"$0\"\n## specificies that the $0 must be the location of **last** symbolic link in\n## a chain, or wherever it resides in the path.) This can be used for some\n## ...interesting things, like self-duplicating and self-modifiying scripts.\n\n## Currently supported are three errors: whether the file specified exists\n## (ala ENOENT), whether its target exists/is accessible; and the special\n## case of when a sybolic link references itself \"foo -> foo\": a common error\n## for beginners, since 'ln' does not produce an error if the order of link\n## and target are reversed on the command line. (See POSIX signal ELOOP.)\n\n## It would probably be rather simple to write to use this as a basis for\n## a pure shell implementation of the 'symlinks' util included with Linux.\n\n## As an aside, the amount of code below **completely** belies the amount\n## effort it took to get this right -- but I guess that's coding for you.\n\n##===-------------------------------------------------------------------===##\n\nfor argv; do :; done # Last parameter on command line, for options parsing.\n\n## Error messages. Use functions so that we can sub in when the error occurs.\n\nrecurses(){ printf \"Self-referential:\\n\\t$argv ->\\n\\t$argv\\n\" ;}\ndangling(){ printf \"Broken symlink:\\n\\t$argv ->\\n\\t\"$(readlink \"$argv\")\"\\n\" ;}\nerrnoent(){ printf \"No such file: \"$@\"\\n\" ;} # Borrow a horrible signal name.\n\n# Probably best not to install as 'pathfull', if you can avoid it.\n\npathfull(){ cd \"$(dirname \"$@\")\"; link=\"$(readlink \"$(basename \"$@\")\")\"\n\n## 'test and 'ls' report different status for bad symlinks, so we use this.\n\n if [ ! -e \"$@\" ]; then if $(ls -d \"$@\" 2>/dev/null) 2>/dev/null; then\n errnoent 1>&2; exit 1; elif [ ! -e \"$@\" -a \"$link\" = \"$@\" ]; then\n recurses 1>&2; exit 1; elif [ ! -e \"$@\" ] && [ ! -z \"$link\" ]; then\n dangling 1>&2; exit 1; fi\n fi\n\n## Not a link, but there might be one in the path, so 'cd' and 'pwd'.\n\n if [ -z \"$link\" ]; then if [ \"$(dirname \"$@\" | cut -c1)\" = '/' ]; then\n printf \"$@\\n\"; exit 0; else printf \"$(pwd)/$(basename \"$@\")\\n\"; fi; exit 0\n fi\n\n## Walk the symlinks back to the origin. Calls itself recursivly as needed.\n\n while [ \"$link\" ]; do\n cd \"$(dirname \"$link\")\"; newlink=\"$(readlink \"$(basename \"$link\")\")\"\n case \"$newlink\" in\n \"$link\") dangling 1>&2 && exit 1 ;;\n '') printf \"$(pwd)/$(basename \"$link\")\\n\"; exit 0 ;;\n *) link=\"$newlink\" && pathfull \"$link\" ;;\n esac\n done\n printf \"$(pwd)/$(basename \"$newlink\")\\n\"\n}\n\n## Demo. Install somewhere deep in the filesystem, then symlink somewhere \n## else, symlink again (maybe with a different name) elsewhere, and link\n## back into the directory you started in (or something.) The absolute path\n## of the script will always be reported in the usage, along with \"$0\".\n\nif [ -z \"$argv\" ]; then scriptname=\"$(pathfull \"$0\")\"\n\n# Yay ANSI l33t codes! Fancy.\n printf \"\\n\\033[3mfrom/as: \\033[4m$0\\033[0m\\n\\n\\033[1mUSAGE:\\033[0m \"\n printf \"\\033[4m$scriptname\\033[24m [ link | file | dir ]\\n\\n \"\n printf \"Recursive readlink for the authoritative file, symlink after \"\n printf \"symlink.\\n\\n\\n \\033[4m$scriptname\\033[24m\\n\\n \"\n printf \" From within an invocation of a script, locate the script's \"\n printf \"own file\\n (no matter where it has been linked or \"\n printf \"from where it is being called).\\n\\n\"\n\nelse pathfull \"$@\"\nfi\n"
},
{
"answer_id": 23846906,
"author": "ideawu",
"author_id": 427640,
"author_profile": "https://Stackoverflow.com/users/427640",
"pm_score": -1,
"selected": false,
"text": "cur_dir=`old=\\`pwd\\`; cd \\`dirname $0\\`; echo \\`pwd\\`; cd $old;`\n"
},
{
"answer_id": 23905052,
"author": "user1338062",
"author_id": 1338062,
"author_profile": "https://Stackoverflow.com/users/1338062",
"pm_score": 4,
"selected": false,
"text": "readlink $(readlink -f \"$(dirname \"$0\")\")\n BASH_SOURCE $0"
},
{
"answer_id": 24545261,
"author": "konsolebox",
"author_id": 445221,
"author_profile": "https://Stackoverflow.com/users/445221",
"pm_score": -1,
"selected": false,
"text": "IFS= read -rd '' DIR < <([[ $BASH_SOURCE != */* ]] || cd \"${BASH_SOURCE%/*}/\" >&- && echo -n \"$PWD\")\n"
},
{
"answer_id": 25596764,
"author": "gkb0986",
"author_id": 1988435,
"author_profile": "https://Stackoverflow.com/users/1988435",
"pm_score": 2,
"selected": false,
"text": "${BASH_SOURCE[0]} dirname ${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\n readlink source test1/test2/test_script.sh bash test1/test2/test_script.sh #\n# Location: test1/test2/test_script.sh\n#\necho $0\necho $_\necho ${BASH_SOURCE}\necho ${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\n\ncur_file=\"${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\"\ncur_dir=\"$(dirname \"${cur_file}\")\"\nsource \"${cur_dir}/func_def.sh\"\n\nfunction test_within_func_inside {\n echo ${BASH_SOURCE}\n echo ${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\n}\n\necho \"Testing within function inside\"\ntest_within_func_inside\n\necho \"Testing within function outside\"\ntest_within_func_outside\n\n#\n# Location: test1/test2/func_def.sh\n#\nfunction test_within_func_outside {\n echo ${BASH_SOURCE}\n echo ${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\n}\n BASH_SOURCE FUNCNAME"
},
{
"answer_id": 26934693,
"author": "Paul Savage",
"author_id": 1901136,
"author_profile": "https://Stackoverflow.com/users/1901136",
"pm_score": -1,
"selected": false,
"text": "FOLDERNAME=${PWD##*/}\n"
},
{
"answer_id": 33033257,
"author": "michaeljt",
"author_id": 213180,
"author_profile": "https://Stackoverflow.com/users/213180",
"pm_score": -1,
"selected": false,
"text": "/bin/sh [script path relative to path component] $0 #! $0 \\n > * ? $0 /bin/sh #!/bin/sh\n(\n path=\"${0}\"\n while test -n \"${path}\"; do\n # Make sure we have at least one slash and no leading dash.\n expr \"${path}\" : / > /dev/null || path=\"./${path}\"\n # Filter out bad characters in the path name.\n expr \"${path}\" : \".*[*?<>\\\\]\" > /dev/null && exit 1\n # Catch embedded new-lines and non-existing (or path-relative) files.\n # $0 should always be absolute when scripts are invoked through \"#!\".\n test \"`ls -l -d \"${path}\" 2> /dev/null | wc -l`\" -eq 1 || exit 1\n # Change to the folder containing the file to resolve relative links.\n folder=`expr \"${path}\" : \"\\(.*/\\)[^/][^/]*/*$\"` || exit 1\n path=`expr \"x\\`ls -l -d \"${path}\"\\`\" : \"[^>]* -> \\(.*\\)\"`\n cd \"${folder}\"\n # If the last path was not a link then we are in the target folder.\n test -n \"${path}\" || pwd\n done\n)\n"
},
{
"answer_id": 35374073,
"author": "Simon Rigét",
"author_id": 3546836,
"author_profile": "https://Stackoverflow.com/users/3546836",
"pm_score": 7,
"selected": false,
"text": "DIR=\"$(dirname \"$(realpath \"$0\")\")\"\n dirname realpath"
},
{
"answer_id": 35514432,
"author": "James Ko",
"author_id": 4077294,
"author_profile": "https://Stackoverflow.com/users/4077294",
"pm_score": 4,
"selected": false,
"text": "actual_path=$(readlink -f \"${BASH_SOURCE[0]}\")\nscript_dir=$(dirname \"$actual_path\")\n ${BASH_SOURCE[0]} source <(echo 'echo $0') ${BASH_SOURCE[0]} readlink -f coreutils greadlink -f dirname"
},
{
"answer_id": 36322330,
"author": "Jay jargot",
"author_id": 6010343,
"author_profile": "https://Stackoverflow.com/users/6010343",
"pm_score": -1,
"selected": false,
"text": "#!/bin/bash --\ncd \"$(dirname \"${0}\")\"/. || exit 2\n $ ls \napplication\n$ mkdir \"$(printf \"\\1\\2\\3\\4\\5\\6\\7\\10\\11\\12\\13\\14\\15\\16\\17\\20\\21\\22\\23\\24\\25\\26\\27\\30\\31\\32\\33\\34\\35\\36\\37\\40\\41\\42\\43\\44\\45\\46\\47testdir\" \"\")\"\n$ mv application *testdir\n$ ln -s *testdir \"$(printf \"\\1\\2\\3\\4\\5\\6\\7\\10\\11\\12\\13\\14\\15\\16\\17\\20\\21\\22\\23\\24\\25\\26\\27\\30\\31\\32\\33\\34\\35\\36\\37\\40\\41\\42\\43\\44\\45\\46\\47symlink\" \"\")\"\n$ ls -lb\ntotal 4\nlrwxrwxrwx 1 jay stacko 46 Mar 30 20:44 \\001\\002\\003\\004\\005\\006\\a\\b\\t\\n\\v\\f\\r\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\\ !\"#$%&'symlink -> \\001\\002\\003\\004\\005\\006\\a\\b\\t\\n\\v\\f\\r\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\\ !\"#$%&'testdir\ndrwxr-xr-x 2 jay stacko 4096 Mar 30 20:44 \\001\\002\\003\\004\\005\\006\\a\\b\\t\\n\\v\\f\\r\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\\ !\"#$%&'testdir\n$ *testdir/application && printf \"SUCCESS\\n\" \"\"\nSUCCESS\n$ *symlink/application && printf \"SUCCESS\\n\" \"\"\nSUCCESS\n"
},
{
"answer_id": 40217561,
"author": "Nam G VU",
"author_id": 248616,
"author_profile": "https://Stackoverflow.com/users/248616",
"pm_score": -1,
"selected": false,
"text": "SCRIPT_HOME s=${BASH_SOURCE[0]} ; s=`dirname $s` ; SCRIPT_HOME=`cd $s ; pwd`\necho $SCRIPT_HOME\n"
},
{
"answer_id": 42025938,
"author": "ankostis",
"author_id": 548792,
"author_profile": "https://Stackoverflow.com/users/548792",
"pm_score": -1,
"selected": false,
"text": "bash -c <script> set mydir=\"$(cygpath \"$(dirname \"$0\")\")\"\n"
},
{
"answer_id": 42038422,
"author": "puchu",
"author_id": 404949,
"author_profile": "https://Stackoverflow.com/users/404949",
"pm_score": 2,
"selected": false,
"text": "$0 .xprofile #!/bin/bash\necho \"$0 $1 $2\"\necho \"${BASH_SOURCE[0]}\"\n# $dir/my_script.sh &\n /home/puchuu/.xprofile\n/home/puchuu/.xprofile\n-bash\n/home/puchuu/.xprofile\n BASH_SOURCE"
},
{
"answer_id": 43333425,
"author": "BuvinJ",
"author_id": 3220983,
"author_profile": "https://Stackoverflow.com/users/3220983",
"pm_score": 3,
"selected": false,
"text": "thisScriptPath=`realpath $0`\nthisDirPath=`dirname $thisScriptPath`\necho $thisDirPath\n"
},
{
"answer_id": 49194320,
"author": "User8461",
"author_id": 8594421,
"author_profile": "https://Stackoverflow.com/users/8594421",
"pm_score": 4,
"selected": false,
"text": " Script: \"/tmp/src dir/test.sh\"\n Calling folder: \"/tmp/src dir/other\"\n echo Script-Dir : `dirname \"$(realpath $0)\"`\n echo Script-Dir : $( cd ${0%/*} && pwd -P )\n echo Script-Dir : $(dirname \"$(readlink -f \"$0\")\")\n echo\n echo Script-Name : `basename \"$(realpath $0)\"`\n echo Script-Name : `basename $0`\n echo\n echo Script-Dir-Relative : `dirname \"$BASH_SOURCE\"`\n echo Script-Dir-Relative : `dirname $0`\n echo\n echo Calling-Dir : `pwd`\n Script-Dir : /tmp/src dir\n Script-Dir : /tmp/src dir\n Script-Dir : /tmp/src dir\n\n Script-Name : test.sh\n Script-Name : test.sh\n\n Script-Dir-Relative : ..\n Script-Dir-Relative : ..\n\n Calling-Dir : /tmp/src dir/other\n"
},
{
"answer_id": 49867891,
"author": "Rawstring",
"author_id": 2693082,
"author_profile": "https://Stackoverflow.com/users/2693082",
"pm_score": 2,
"selected": false,
"text": "pathvar=\"$( cd \"$( dirname $0 )\" && pwd )\"\n"
},
{
"answer_id": 50635459,
"author": "Alexander Mills",
"author_id": 1223975,
"author_profile": "https://Stackoverflow.com/users/1223975",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env bash\n\ndirn=\"$(dirname \"$0\")\"\nrl=\"$(readlink \"$0\")\";\nexec_dir=\"$(dirname $(dirname \"$rl\"))\";\nmy_path=\"$dirn/$exec_dir\";\nX=\"$(cd $(dirname ${my_path}) && pwd)/$(basename ${my_path})\"\n"
},
{
"answer_id": 53183593,
"author": "Thamme Gowda",
"author_id": 1506477,
"author_profile": "https://Stackoverflow.com/users/1506477",
"pm_score": 7,
"selected": false,
"text": "DIR=\"$( dirname -- \"${BASH_SOURCE[0]}\"; )\"; # Get the directory name\nDIR=\"$( realpath -e -- \"$DIR\"; )\"; # Resolve its full path if need be\n"
},
{
"answer_id": 54133107,
"author": "danemacmillan",
"author_id": 2973534,
"author_profile": "https://Stackoverflow.com/users/2973534",
"pm_score": -1,
"selected": false,
"text": "export SOURCE_DIRECTORY=\"$(php -r 'echo dirname(realpath($argv[1]));' -- \"${BASH_SOURCE[0]}\")\"\n"
},
{
"answer_id": 55352142,
"author": "Top-Master",
"author_id": 8740349,
"author_profile": "https://Stackoverflow.com/users/8740349",
"pm_score": 0,
"selected": false,
"text": "dir my-sample-app \"$@\" #!/usr/bin/env sh\n\ndir=$(cd \"${0%[/\\\\]*}\" > /dev/null && pwd)\n\nif [ -d /proc/cygdrive ]; then\n case \"$(uname -s)\" in\n CYGWIN*|MINGW32*|MSYS*|MINGW*)\n # We are under Windows, so translate path to Windows format.\n dir=$(cygpath -m \"$dir\");\n ;;\n esac\nfi\n\n# Runs the executable which is beside this script\n\"${dir}/my-sample-app\" \"$@\"\n"
},
{
"answer_id": 56031051,
"author": "Andry",
"author_id": 2672125,
"author_profile": "https://Stackoverflow.com/users/2672125",
"pm_score": -1,
"selected": false,
"text": "source source source source function include()\n{\n if [[ -n \"$CURRENT_SCRIPT_DIR\" ]]; then\n local dir_path=... get directory from `CURRENT_SCRIPT_DIR/$1`, depends if $1 is absolute path or relative ...\n local include_file_path=...\n else\n local dir_path=... request the directory from the \"$1\" argument using one of answered here methods...\n local include_file_path=...\n fi\n ... push $CURRENT_SCRIPT_DIR in to stack ...\n export CURRENT_SCRIPT_DIR=... export current script directory using $dir_path ...\n source \"$include_file_path\"\n ... pop $CURRENT_SCRIPT_DIR from stack ...\n}\n include(...) CURRENT_SCRIPT_DIR source include tkl_include"
},
{
"answer_id": 56186126,
"author": "cdonat",
"author_id": 5053331,
"author_profile": "https://Stackoverflow.com/users/5053331",
"pm_score": 2,
"selected": false,
"text": "dirname $(which $BASH_SOURCE)\n"
},
{
"answer_id": 56264110,
"author": "Chaim Leib Halbert",
"author_id": 1795125,
"author_profile": "https://Stackoverflow.com/users/1795125",
"pm_score": 2,
"selected": false,
"text": "[ -n \"$ZSH_VERSION\" ] && this_dir=$(dirname \"${(%):-%x}\") \\\n || this_dir=$(dirname \"${BASH_SOURCE[0]:-$0}\")\n ${(%):-%x} ${(%):-%x} :- ${...} :- % x=ok\n% echo \"${x}\"\nok\n\n% echo \"${x:-fallback}\"\nok\n\n% x=\n% echo \"${x:-fallback}\"\nfallback\n\n% y=yvalue\n% echo \"${x:-$y}\"\nyvalue\n %x %x (%) % cat apath/test.sh\nfpath=%x\necho \"${(%)fpath}\"\n\n% source apath/test.sh\napath/test.sh\n\n% cd apath\n% source test.sh\ntest.sh\n fpath %x fpath :- %x % cat test.sh\necho \"${(%):-%x}\"\n\n% source test.sh\ntest.sh\n (%) :- print -P %x print -P %x dirname % cat apath/test.sh\ndirname \"$(print -P %x)\" # $(...) runs a command in a new process\ndirname \"${(%):-%x}\"\n\n% source apath/test.sh\napath\napath\n"
},
{
"answer_id": 56694491,
"author": "Atul",
"author_id": 2881112,
"author_profile": "https://Stackoverflow.com/users/2881112",
"pm_score": 5,
"selected": false,
"text": "#!/bin/bash\nDIRECTORY=$(cd `dirname $0` && pwd)\necho $DIRECTORY\n"
},
{
"answer_id": 57505372,
"author": "bestOfSong",
"author_id": 5010054,
"author_profile": "https://Stackoverflow.com/users/5010054",
"pm_score": -1,
"selected": false,
"text": "#!/bin/sh\n\n# Get an absolute path for the poem.txt file.\nPOEM=\"$PWD/../poem.txt\"\n\n# Get an absolute path for the script file.\nSCRIPT=\"$(which $0)\"\nif [ \"x$(echo $SCRIPT | grep '^\\/')\" = \"x\" ] ; then\n SCRIPT=\"$PWD/$SCRIPT\"\nfi\n dirname"
},
{
"answer_id": 57660444,
"author": "LozanoMatheus",
"author_id": 2868547,
"author_profile": "https://Stackoverflow.com/users/2868547",
"pm_score": 3,
"selected": false,
"text": "$0 realpath dirname #!/usr/bin/env bash\n\nRELATIVE_PATH=\"${0}\"\nRELATIVE_DIR_PATH=\"$(dirname \"${0}\")\"\nFULL_DIR_PATH=\"$(realpath \"${0}\" | xargs dirname)\"\nFULL_PATH=\"$(realpath \"${0}\")\"\n\necho \"RELATIVE_PATH->${RELATIVE_PATH}<-\"\necho \"RELATIVE_DIR_PATH->${RELATIVE_DIR_PATH}<-\"\necho \"FULL_DIR_PATH->${FULL_DIR_PATH}<-\"\necho \"FULL_PATH->${FULL_PATH}<-\"\n # RELATIVE_PATH->./bin/startup.sh<-\n# RELATIVE_DIR_PATH->./bin<-\n# FULL_DIR_PATH->/opt/my_app/bin<-\n# FULL_PATH->/opt/my_app/bin/startup.sh<-\n"
},
{
"answer_id": 57666344,
"author": "MatteoBee",
"author_id": 11004601,
"author_profile": "https://Stackoverflow.com/users/11004601",
"pm_score": -1,
"selected": false,
"text": "## BASE BRAIN - Get where you're from and who you are.\nMYPID=$$\nORIGINAL_DIR=\"$(pwd)\" # This is not a hot air balloon ride..\nfa=\"$0\" # First Assumption\nta= # Temporary Assumption\nwa= # Weighed Assumption\nwhile true; do\n [ \"${fa:0:1}\" = \"/\" ] && wa=$0 && break\n [ \"${fa:0:2}\" = \"./\" ] && ta=\"${ORIGINAL_DIR}/${fa:2}\" && [ -e \"$ta\" ] && wa=\"$ta\" && break\n ta=\"${ORIGINAL_DIR}/${fa}\" && [ -e \"$ta\" ] && wa=\"$ta\" && break\ndone\nSW=\"$wa\"\nSWDIR=\"$(dirname \"$wa\")\"\nSWBIN=\"$(basename \"$wa\")\"\nunset ta fa wa\n( [ ! -e \"$SWDIR/$SWBIN\" ] || [ -z \"$SW\" ] ) && echo \"I could not find my way around :( possible bug in the TOP script\" && exit 1\n"
},
{
"answer_id": 58286511,
"author": "Brad Parks",
"author_id": 26510,
"author_profile": "https://Stackoverflow.com/users/26510",
"pm_score": 2,
"selected": false,
"text": "/tmp/a/b/c $ . ./test.sh\n/tmp/a/b/c\n\n/tmp/a/b/c $ . /tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n/tmp/a/b/c $ ./test.sh\n/tmp/a/b/c\n\n/tmp/a/b/c $ /tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n/tmp/a/b/c $ cd\n\n~ $ . /tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n~ $ . ../../tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n~ $ /tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n~ $ ../../tmp/a/b/c/test.sh\n/tmp/a/b/c\n #!/usr/bin/env bash\n\n# snagged from: https://stackoverflow.com/a/51264222/26510\nfunction toAbsPath {\n local target\n target=\"$1\"\n\n if [ \"$target\" == \".\" ]; then\n echo \"$(pwd)\"\n elif [ \"$target\" == \"..\" ]; then\n echo \"$(dirname \"$(pwd)\")\"\n else\n echo \"$(cd \"$(dirname \"$1\")\"; pwd)/$(basename \"$1\")\"\n fi\n}\n\nfunction getScriptDir(){\n local SOURCED\n local RESULT\n (return 0 2>/dev/null) && SOURCED=1 || SOURCED=0\n\n if [ \"$SOURCED\" == \"1\" ]\n then\n RESULT=$(dirname \"$1\")\n else\n RESULT=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n fi\n toAbsPath \"$RESULT\"\n}\n\nSCRIPT_DIR=$(getScriptDir \"$0\")\necho \"$SCRIPT_DIR\"\n"
},
{
"answer_id": 58562442,
"author": "Alexander Stohr",
"author_id": 3423146,
"author_profile": "https://Stackoverflow.com/users/3423146",
"pm_score": 3,
"selected": false,
"text": "PATH_TO_SCRIPT=`realpath -s $0`\nPATH_TO_SCRIPT_DIR=`dirname $PATH_TO_SCRIPT`\n PATH_TO_SCRIPT=`realpath -s \"$0\"`\nPATH_TO_SCRIPT_DIR=`dirname \"$PATH_TO_SCRIPT\"`\n"
},
{
"answer_id": 59485855,
"author": "Domi",
"author_id": 2228771,
"author_profile": "https://Stackoverflow.com/users/2228771",
"pm_score": 2,
"selected": false,
"text": "baseDirRelative=$(dirname \"$0\")\nbaseDir=$(node -e \"console.log(require('path').resolve('$baseDirRelative'))\") # Get absolute path using Node.js\n\necho $baseDir\n"
},
{
"answer_id": 60157372,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 4,
"selected": false,
"text": "FULL_PATH_TO_SCRIPT=\"$(realpath \"${BASH_SOURCE[-1]}\")\"\n\n# OR, if you do NOT need it to work for **sourced** scripts too:\n# FULL_PATH_TO_SCRIPT=\"$(realpath \"$0\")\"\n\n# OR, depending on which path you want, in case of nested `source` calls\n# FULL_PATH_TO_SCRIPT=\"$(realpath \"${BASH_SOURCE[0]}\")\"\n\n# OR, add `-s` to NOT expand symlinks in the path:\n# FULL_PATH_TO_SCRIPT=\"$(realpath -s \"${BASH_SOURCE[-1]}\")\"\n\nSCRIPT_DIRECTORY=\"$(dirname \"$FULL_PATH_TO_SCRIPT\")\"\nSCRIPT_FILENAME=\"$(basename \"$FULL_PATH_TO_SCRIPT\")\"\n realpath realpath sudo apt update && sudo apt install coreutils #!/bin/bash\n\n# A. Obtain the full path, and expand (walk down) symbolic links\n# A.1. `\"$0\"` works only if the file is **run**, but NOT if it is **sourced**.\n# FULL_PATH_TO_SCRIPT=\"$(realpath \"$0\")\"\n# A.2. `\"${BASH_SOURCE[-1]}\"` works whether the file is sourced OR run, and even\n# if the script is called from within another bash function!\n# NB: if `\"${BASH_SOURCE[-1]}\"` doesn't give you quite what you want, use\n# `\"${BASH_SOURCE[0]}\"` instead in order to get the first element from the array.\nFULL_PATH_TO_SCRIPT=\"$(realpath \"${BASH_SOURCE[-1]}\")\"\n# B.1. `\"$0\"` works only if the file is **run**, but NOT if it is **sourced**.\n# FULL_PATH_TO_SCRIPT_KEEP_SYMLINKS=\"$(realpath -s \"$0\")\"\n# B.2. `\"${BASH_SOURCE[-1]}\"` works whether the file is sourced OR run, and even\n# if the script is called from within another bash function!\n# NB: if `\"${BASH_SOURCE[-1]}\"` doesn't give you quite what you want, use\n# `\"${BASH_SOURCE[0]}\"` instead in order to get the first element from the array.\nFULL_PATH_TO_SCRIPT_KEEP_SYMLINKS=\"$(realpath -s \"${BASH_SOURCE[-1]}\")\"\n\n# You can then also get the full path to the directory, and the base\n# filename, like this:\nSCRIPT_DIRECTORY=\"$(dirname \"$FULL_PATH_TO_SCRIPT\")\"\nSCRIPT_FILENAME=\"$(basename \"$FULL_PATH_TO_SCRIPT\")\"\n\n# Now print it all out\necho \"FULL_PATH_TO_SCRIPT = \\\"$FULL_PATH_TO_SCRIPT\\\"\"\necho \"SCRIPT_DIRECTORY = \\\"$SCRIPT_DIRECTORY\\\"\"\necho \"SCRIPT_FILENAME = \\\"$SCRIPT_FILENAME\\\"\"\n source \"${BASH_SOURCE[-1]}\" \"${BASH_SOURCE[0]}\" 0 -1 ~/.bashrc . ~/.bashrc ~/.bash_aliases . ~/.bash_aliases realpath ~/.bash_aliases ~/.bashrc source \"${BASH_SOURCE[0]}\" ~/.bash_aliases \"${BASH_SOURCE[-1]}\" ~/.bashrc ~/GS/dev/eRCaGuy_hello_world/bash$ ./get_script_path.sh \nFULL_PATH_TO_SCRIPT = \"/home/gabriel/GS/dev/eRCaGuy_hello_world/bash/get_script_path.sh\"\nSCRIPT_DIRECTORY = \"/home/gabriel/GS/dev/eRCaGuy_hello_world/bash\"\nSCRIPT_FILENAME = \"get_script_path.sh\"\n . get_script_path.sh source get_script_path.sh \"${BASH_SOURCE[-1]}\" \"$0\" ~/GS/dev/eRCaGuy_hello_world/bash$ . get_script_path.sh \nFULL_PATH_TO_SCRIPT = \"/home/gabriel/GS/dev/eRCaGuy_hello_world/bash/get_script_path.sh\"\nSCRIPT_DIRECTORY = \"/home/gabriel/GS/dev/eRCaGuy_hello_world/bash\"\nSCRIPT_FILENAME = \"get_script_path.sh\"\n \"$0\" \"${BASH_SOURCE[-1]}\" ~/GS/dev/eRCaGuy_hello_world/bash$ . get_script_path.sh \nFULL_PATH_TO_SCRIPT = \"/bin/bash\"\nSCRIPT_DIRECTORY = \"/bin\"\nSCRIPT_FILENAME = \"bash\"\n \"$BASH_SOURCE\" \"${BASH_SOURCE[-1]}\" \"${BASH_SOURCE[-1]}\" realpath realpath -s realpath -s realpath # Obtain the full path, but do NOT expand (walk down) symbolic links; in\n# other words: **keep** the symlinks as part of the path!\nFULL_PATH_TO_SCRIPT=\"$(realpath -s \"${BASH_SOURCE[-1]}\")\"\n BASH_SOURCE BASH_SOURCE \"${BASH_SOURCE[-1]}\" man bash BASH_SOURCE BASH_SOURCE FUNCNAME ${FUNCNAME[$i]} ${BASH_SOURCE[$i]} ${BASH_SOURCE[$i+1]}"
},
{
"answer_id": 60381515,
"author": "Muhammad Adeel",
"author_id": 2407041,
"author_profile": "https://Stackoverflow.com/users/2407041",
"pm_score": -1,
"selected": false,
"text": "#!/usr/bin/env bash\nsourceDir=`pwd`\necho $sourceDir\n"
},
{
"answer_id": 62396544,
"author": "todd_dsm",
"author_id": 1778702,
"author_profile": "https://Stackoverflow.com/users/1778702",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env bash\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\necho \"opt1; original answer: $DIR\"\necho ''\n\necho \"opt2; simple answer : ${BASH_SOURCE[0]%/*}\"\n $ /var/tmp/test.sh\nopt1; original answer: /var/tmp\n\nopt2; simple answer : /var/tmp\n ${BASH_SOURCE[0]%/*}\""
},
{
"answer_id": 65430829,
"author": "Thomas Guyot-Sionnest",
"author_id": 969196,
"author_profile": "https://Stackoverflow.com/users/969196",
"pm_score": 2,
"selected": false,
"text": "/ $PWD/ $0 ${0:0:1} / cd #!/bin/bash\n\nBIN=${0/#[!\\/]/\"$PWD/${0:0:1}\"}\nDIR=${BIN%/*}\n\ncd \"$DIR\"\n $0 ${BASH_SOURCE[0]} BIN=${BASH_SOURCE[0]/#[!\\/]/\"$PWD/${BASH_SOURCE[0]:0:1}\"}\n"
},
{
"answer_id": 65802617,
"author": "ghchoi",
"author_id": 4227175,
"author_profile": "https://Stackoverflow.com/users/4227175",
"pm_score": 2,
"selected": false,
"text": "echo $(realpath $_) . application # /correct/path/to/dir or /path/to/temporary_dir\nbash application # /path/to/bash\n/PATH/TO/application # /correct/path/to/dir\n echo $(realpath $(dirname $0)) . application # failed with `realpath: missing operand`\nbash application # /correct/path/to/dir\n/PATH/TO/application # /correct/path/to/dir\n echo $(realpath $BASH_SOURCE) $BASH_SOURCE ${BASH_SOURCE[0]} . application # /correct/path/to/dir\nbash application # /correct/path/to/dir\n/PATH/TO/application # /correct/path/to/dir\n $(realpath $BASH_SOURCE)"
},
{
"answer_id": 67105198,
"author": "l0b0",
"author_id": 96588,
"author_profile": "https://Stackoverflow.com/users/96588",
"pm_score": 3,
"selected": false,
"text": "dir=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd && echo x)\"\ndir=\"${dir%x}\"\n mkdir $'\\n'"
},
{
"answer_id": 67149152,
"author": "Binary Phile",
"author_id": 75182,
"author_profile": "https://Stackoverflow.com/users/75182",
"pm_score": 2,
"selected": false,
"text": "HERE=$(cd \"$(dirname \"$BASH_SOURCE\")\"; cd -P \"$(dirname \"$(readlink \"$BASH_SOURCE\" || echo .)\")\"; pwd)\n pwd --"
},
{
"answer_id": 68056148,
"author": "mrucci",
"author_id": 133106,
"author_profile": "https://Stackoverflow.com/users/133106",
"pm_score": 3,
"selected": false,
"text": "SCRIPT_DIR=$(python -c \"import os; print(os.path.dirname(os.path.realpath('${BASH_SOURCE[0]}')))\")\n SCRIPT_DIR=$(python3 -c \"from pathlib import Path; print(Path('${BASH_SOURCE[0]}').resolve().parent)\")\n"
},
{
"answer_id": 72077148,
"author": "M Imam Pratama",
"author_id": 9157799,
"author_profile": "https://Stackoverflow.com/users/9157799",
"pm_score": 0,
"selected": false,
"text": "$0 script_path=\"$0\"\n $BASH_SOURCE ${BASH_SOURCE[0]} script_path=\"$BASH_SOURCE\"\n $BASH_SOURCE realpath readlink -f script_path=\"$(realpath \"$BASH_SOURCE\")\"\n realpath readlink -f dirname script_directory=\"$(dirname \"$script_path\")\"\n realpath readlink -f ${var-string}"
},
{
"answer_id": 72195658,
"author": "Alfred.37",
"author_id": 16931965,
"author_profile": "https://Stackoverflow.com/users/16931965",
"pm_score": 0,
"selected": false,
"text": "script_path=$(dirname \"$(readlink -f \"$0\")\")\"/\"\necho \"$script_path\"\n /home/username/desktop/\n"
},
{
"answer_id": 74638215,
"author": "digory doo",
"author_id": 1823332,
"author_profile": "https://Stackoverflow.com/users/1823332",
"pm_score": 0,
"selected": false,
"text": "SELF=$(SELF=$(dirname \"$0\") && bash -c \"cd \\\"$SELF\\\" && pwd\")\necho \"$SELF\"\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
] |
59,896 |
<p>I have a page that uses </p>
<pre><code>$(id).show("highlight", {}, 2000);
</code></pre>
<p>to highlight an element when I start a ajax request, that might fail so that I want to use something like</p>
<pre><code>$(id).show("highlight", {color: "#FF0000"}, 2000);
</code></pre>
<p>in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect?</p>
|
[
{
"answer_id": 59904,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 5,
"selected": true,
"text": ".stop() .slideUp() .stop() .stop() clearQueue true jumpToEnd .slideUp()"
},
{
"answer_id": 10280784,
"author": "Dutchie432",
"author_id": 83809,
"author_profile": "https://Stackoverflow.com/users/83809",
"pm_score": 4,
"selected": false,
"text": ".stop() .stop() .stop(true, true)"
},
{
"answer_id": 35552097,
"author": "fireydude",
"author_id": 869290,
"author_profile": "https://Stackoverflow.com/users/869290",
"pm_score": 2,
"selected": false,
"text": "$('#identifier').effect(\"pulsate\", {times:5}, 1000);\n $('#identifier').stop(true, true).effect(\"pulsate\", { times: 1 }, 1);\n"
},
{
"answer_id": 57123012,
"author": "mike85",
"author_id": 5137862,
"author_profile": "https://Stackoverflow.com/users/5137862",
"pm_score": 0,
"selected": false,
"text": "$('#identifier').stop(true, true).effect(\"pulsate\", { times: 1 }, 1);\n $('#identifier').stop(true, true).css('opacity','');\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6093/"
] |
59,942 |
<p>I started a project a long time ago and created a <strong>Data Access Layer</strong> project in my solution but have never developed anything in it. What is the purpose of a data access layer? Are there any good sources that I could learn more about the Data Access Layer?</p>
|
[
{
"answer_id": 4237176,
"author": "Shiv Kumar",
"author_id": 501146,
"author_profile": "https://Stackoverflow.com/users/501146",
"pm_score": 5,
"selected": false,
"text": "GetOrdersForCustomer(42)\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] |
59,945 |
<p>We can successfully consume a .NET 2.0 web service from a Flex/AS3 application. Aside from SSL, how else can we make the security more robust (i.e., authentication)?</p>
|
[
{
"answer_id": 196130,
"author": "matt eisenberg",
"author_id": 14654,
"author_profile": "https://Stackoverflow.com/users/14654",
"pm_score": 2,
"selected": false,
"text": "<EnableSession()>"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5592/"
] |
59,986 |
<p>I have a simple type that explicitly implemets an Interface.</p>
<pre><code>public interface IMessageHeader
{
string FromAddress { get; set; }
string ToAddress { get; set; }
}
[Serializable]
public class MessageHeader:IMessageHeader
{
private string from;
private string to;
[XmlAttribute("From")]
string IMessageHeade.FromAddress
{
get { return this.from;}
set { this.from = value;}
}
[XmlAttribute("To")]
string IMessageHeade.ToAddress
{
get { return this.to;}
set { this.to = value;}
}
}
</code></pre>
<p>Is there a way to Serialize and Deserialize objects of type IMessageHeader??</p>
<p>I got the following error when tried</p>
<p>"Cannot serialize interface IMessageHeader"</p>
|
[
{
"answer_id": 59993,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 0,
"selected": false,
"text": "XmlSerializer ser = new XmlSerializer(typeof(IMessageHeader));\n\nIMessageHeader header = (IMessageHeader)ser.Deserialize(data);\n"
},
{
"answer_id": 60043,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 3,
"selected": true,
"text": "XmlSerializer serializer = new XmlSerializer(instance.GetType())\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647/"
] |
60,000 |
<p>In C++, can member function pointers be used to point to derived (or even base) class members? </p>
<p>EDIT:
Perhaps an example will help. Suppose we have a hierarchy of three classes <code>X</code>, <code>Y</code>, <code>Z</code> in order of inheritance.
<code>Y</code> therefore has a base class <code>X</code> and a derived class <code>Z</code>.</p>
<p>Now we can define a member function pointer <code>p</code> for class <code>Y</code>. This is written as:</p>
<pre><code>void (Y::*p)();
</code></pre>
<p>(For simplicity, I'll assume we're only interested in functions with the signature <code>void f()</code> ) </p>
<p>This pointer <code>p</code> can now be used to point to member functions of class <code>Y</code>.</p>
<p>This question (two questions, really) is then:</p>
<ol>
<li>Can <code>p</code> be used to point to a function in the derived class <code>Z</code>?</li>
<li>Can <code>p</code> be used to point to a function in the base class <code>X</code>?</li>
</ol>
|
[
{
"answer_id": 60023,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 4,
"selected": false,
"text": "#include <iostream>\nusing namespace std;\n\nclass A { \npublic:\n virtual void foo() { cout << \"A::foo\\n\"; }\n};\nclass B : public A {\npublic:\n virtual void foo() { cout << \"B::foo\\n\"; }\n};\n\nint main()\n{\n void (A::*bar)() = &A::foo;\n (A().*bar)();\n (B().*bar)();\n return 0;\n}\n"
},
{
"answer_id": 1130707,
"author": "smh",
"author_id": 1077,
"author_profile": "https://Stackoverflow.com/users/1077",
"pm_score": 1,
"selected": false,
"text": "p p p"
},
{
"answer_id": 2688154,
"author": "Winston Ewert",
"author_id": 322806,
"author_profile": "https://Stackoverflow.com/users/322806",
"pm_score": 1,
"selected": false,
"text": "class X, class Y : public X, and class Z : public Y void (Y::*p)() = &Z::func; // we pretend this is legal\nY * y = new Y; // clearly legal\n(y->*p)(); // okay, follows the rules, but what would this mean?\n"
},
{
"answer_id": 2688631,
"author": "outis",
"author_id": 90527,
"author_profile": "https://Stackoverflow.com/users/90527",
"pm_score": 6,
"selected": true,
"text": "class A {\npublic: \n void foo();\n};\nclass B : public A {};\nclass C {\npublic:\n void bar();\n};\nclass D {\npublic:\n void baz();\n};\nclass E : public A, public B, private C, public virtual D {\npublic: \n typedef void (E::*member)();\n};\nclass F:public E {\npublic:\n void bam();\n};\n...\nint main() {\n E::member mbr;\n mbr = &A::foo; // invalid: ambiguous; E's A or B's A?\n mbr = &C::bar; // invalid: C is private \n mbr = &D::baz; // invalid: D is virtual\n mbr = &F::bam; // invalid: conversion isn't defined by the standard\n ...\n static_cast D::* B::* B::* D::* B::*"
},
{
"answer_id": 2688793,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 3,
"selected": false,
"text": "Z Y Y Z Y void (Y::*p)() = &Z::z_fn; // illegal\n Y Y Z Y Z Z Y Z Z Y Z void (Y::*p)() = &Y::y_fn;\nvoid (Z::*q)() = p; // legal and safe\n"
},
{
"answer_id": 28506633,
"author": "Gena Batsyan",
"author_id": 1427063,
"author_profile": "https://Stackoverflow.com/users/1427063",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass A {\npublic:\n virtual void traverse(string arg) {\n find(&A::visit, arg);\n }\n\nprotected:\n virtual void find(void (A::*method)(string arg), string arg) {\n (this->*method)(arg);\n }\n\n virtual void visit(string arg) {\n cout << \"A::visit, arg:\" << arg << endl;\n }\n};\n\nclass B : public A {\nprotected:\n virtual void visit(string arg) {\n cout << \"B::visit, arg:\" << arg << endl;\n }\n};\n\nint main()\n{\n A a;\n B b;\n a.traverse(\"one\");\n b.traverse(\"two\");\n return 0;\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1077/"
] |
60,009 |
<p>I've been playing with RSS feeds this week, and for my next trick I want to build one for our internal application log. We have a centralized database table that our myriad batch and intranet apps use for posting log messages. I want to create an RSS feed off of this table, but I'm not sure how to handle the volume- there could be hundreds of entries per day even on a normal day. An exceptional make-you-want-to-quit kind of day might see a few thousand. Any thoughts?</p>
|
[
{
"answer_id": 421550,
"author": "Steve Losh",
"author_id": 13498,
"author_profile": "https://Stackoverflow.com/users/13498",
"pm_score": 1,
"selected": false,
"text": "r'/rss/(?(\\w*?)/)+' def get_batch_file_messages():\n # Grab all the recent batch files messages here.\n # Maybe cache the result and only regenerate every so often.\n\n# Other feed functions here.\n\nfeed_mapping = { 'batch-file-output': get_batch_file_messages, }\n\ndef rss(request, *args):\n items_to_display = []\n for feed in args:\n items_to_display += feed_mapping[feed]()\n # Processing/returning the feed.\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
60,019 |
<p>I am wanting to use ActiveScaffold to create <em>assignment</em> records for several <em>students</em> in a single step. The records will all contain identical data, with the exception of the student_id.</p>
<p>I was able to override the default form and replace the dropdown box for selecting the student name with a multi-select box - which is what I want. That change however, was only cosmetic, as the underlying code only grabs the first selected name from that box, and creates a single record.</p>
<p>Can somebody suggest a good way to accomplish this in a way that doesn't require my deciphering and rewriting too much of the underlying ActiveScaffold code?</p>
<hr>
<p>Update: I still haven't found a good answer to this problem.</p>
|
[
{
"answer_id": 60366,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 0,
"selected": false,
"text": "has_many :students has_and_belongs_to_many :students"
},
{
"answer_id": 295986,
"author": "ARemesal",
"author_id": 36599,
"author_profile": "https://Stackoverflow.com/users/36599",
"pm_score": 1,
"selected": false,
"text": "params[:students].collect{|student| insert_student(student, params[:assignment_id]) }\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] |
60,030 |
<p>In Firefox you can enter the following into the awesome bar and hit enter:</p>
<pre><code>javascript:self.resizeTo(1024,768);
</code></pre>
<p>How do you do the same thing in IE?</p>
|
[
{
"answer_id": 60038,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "javascript:resizeTo(1024,768);\n"
},
{
"answer_id": 60209,
"author": "Tolle",
"author_id": 4260,
"author_profile": "https://Stackoverflow.com/users/4260",
"pm_score": 5,
"selected": true,
"text": "javascript:resizeTo(1024,768);\nvbscript:resizeto(1024,768) javascript:moveTo(0,0);resizeTo(1024,768);"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1496/"
] |
60,032 |
<p>How do I get the key of the current element in a <code>foreach</code> loop in C#?</p>
<p>For example:</p>
<h2>PHP</h2>
<pre><code>foreach ($array as $key => $value)
{
echo("$value is assigned to key: $key");
}
</code></pre>
<h3>What I'm trying to do in C#:</h3>
<pre><code>int[] values = { 5, 14, 29, 49, 99, 150, 999 };
foreach (int val in values)
{
if(search <= val && !stop)
{
// Set key to a variable
}
}
</code></pre>
|
[
{
"answer_id": 60047,
"author": "Billy Jo",
"author_id": 3447,
"author_profile": "https://Stackoverflow.com/users/3447",
"pm_score": -1,
"selected": false,
"text": "myKey = Array.IndexOf(values, val);"
},
{
"answer_id": 60058,
"author": "Tyler",
"author_id": 5642,
"author_profile": "https://Stackoverflow.com/users/5642",
"pm_score": 5,
"selected": false,
"text": "Dictionary<int, string> items = new Dictionary<int, string>();\n\nforeach (int key in items.Keys)\n{\n Console.WriteLine(\"Key: {0} has value: {1}\", key, items[key]);\n}\n"
},
{
"answer_id": 60062,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 2,
"selected": false,
"text": "Dictionary<int, int> values = new Dictionary<int, int>();\nvalues[0] = 5;\nvalues[1] = 14;\nvalues[2] = 29;\nvalues[3] = 49;\n// whatever...\n\nforeach (int key in values.Keys)\n{\n Console.WriteLine(\"{0} is assigned to key: {1}\", values[key], key);\n}\n"
},
{
"answer_id": 60089,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 6,
"selected": true,
"text": "int[] values = { 5, 14, 29, 49, 99, 150, 999 };\n\nfor (int key = 0; key < values.Length; ++key)\n if (search <= values[key] && !stop)\n {\n // set key to a variable\n }\n"
},
{
"answer_id": 60097,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "* MoveNext()\n* Current\n"
},
{
"answer_id": 1984058,
"author": "mat3",
"author_id": 173472,
"author_profile": "https://Stackoverflow.com/users/173472",
"pm_score": 0,
"selected": false,
"text": "int index=0;\nforeach (var item in enumerable)\n{\n blah(item, index); // some code that depends on the index\n index++;\n}\n enumerable.ForEach((item, index) => blah(item, index));\n public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action)\n {\n var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void\n enumerable.Select((item, i) => \n {\n action(item, i);\n return unit;\n }).ToList();\n\n return pSource;\n }\n"
},
{
"answer_id": 1984176,
"author": "Craig Gidney",
"author_id": 52239,
"author_profile": "https://Stackoverflow.com/users/52239",
"pm_score": 0,
"selected": false,
"text": "public struct IndexValue<T> {\n public int Index {get; private set;}\n public T Value {get; private set;}\n public IndexValue(int index, T value) : this() {\n this.Index = index;\n this.Value = value;\n }\n}\n\npublic static class EnumExtension\n{\n public static IEnumerable<IndexValue<T>> KeyValuePairs<T>(this IList<T> list) {\n for (int i = 0; i < list.Count; i++)\n yield return new IndexValue<T>(i, list[i]);\n }\n}\n"
},
{
"answer_id": 7366406,
"author": "Guillaume Massé",
"author_id": 449071,
"author_profile": "https://Stackoverflow.com/users/449071",
"pm_score": 4,
"selected": false,
"text": "IDictionary<string,string> openWith = new Dictionary<string,string>()\n{\n { \"txt\", \"notepad.exe\" }\n { \"bmp\", \"paint.exe\" }\n { \"rtf\", \"wordpad.exe\" }\n};\n\nforeach (DictionaryEntry de in openWith)\n{\n Console.WriteLine(\"Key = {0}, Value = {1}\", de.Key, de.Value);\n}\n\n// also\n\nforeach (KeyValuePair<string,string> de in openWith)\n{\n Console.WriteLine(\"Key = {0}, Value = {1}\", de.Key, de.Value);\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] |
60,033 |
<p>I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the <strong>id</strong>). What is the simplest way to accomplish this?</p>
<p>I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.</p>
<p>Perhaps something like this:</p>
<pre class="lang-ruby prettyprint-override"><code> new_record = Record.copy(:id)
</code></pre>
|
[
{
"answer_id": 60053,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 10,
"selected": true,
"text": "#rails >= 3.1\nnew_record = old_record.dup\n\n# rails < 3.1\nnew_record = old_record.clone\n"
},
{
"answer_id": 62925,
"author": "François Beausoleil",
"author_id": 7355,
"author_profile": "https://Stackoverflow.com/users/7355",
"pm_score": 5,
"selected": false,
"text": "new_user = User.new(old_user.attributes.merge(:login => \"newlogin\"))\n"
},
{
"answer_id": 63032,
"author": "Phillip Koebbe",
"author_id": 7283,
"author_profile": "https://Stackoverflow.com/users/7283",
"pm_score": 6,
"selected": false,
"text": ":id => nil :scheduled_on => some_new_date"
},
{
"answer_id": 9485535,
"author": "Vaughn Draughon",
"author_id": 1238269,
"author_profile": "https://Stackoverflow.com/users/1238269",
"pm_score": 5,
"selected": false,
"text": "nullify regex prefix has_one has_many has_and_belongs_to_many gem install amoeba\n gem 'amoeba'\n dup class Post < ActiveRecord::Base\n has_many :comments\n has_and_belongs_to_many :tags\n\n amoeba do\n enable\n end\nend\n\nclass Comment < ActiveRecord::Base\n belongs_to :post\nend\n\nclass Tag < ActiveRecord::Base\n has_and_belongs_to_many :posts\nend\n\nclass PostsController < ActionController\n def some_method\n my_post = Post.find(params[:id])\n new_post = my_post.dup\n new_post.save\n end\nend\n class Post < ActiveRecord::Base\n has_many :comments\n has_and_belongs_to_many :tags\n\n amoeba do\n exclude_field :comments\n end\nend\n class Post < ActiveRecord::Base\n has_many :comments\n has_and_belongs_to_many :tags\n\n amoeba do\n include_field :tags\n prepend :title => \"Copy of \"\n append :contents => \" (copied version)\"\n regex :contents => {:replace => /dog/, :with => \"cat\"}\n end\nend\n class Post < ActiveRecord::Base\n has_many :comments\n\n amoeba do\n enable\n end\nend\n\nclass Comment < ActiveRecord::Base\n belongs_to :post\n has_many :ratings\n\n amoeba do\n enable\n end\nend\n\nclass Rating < ActiveRecord::Base\n belongs_to :comment\nend\n"
},
{
"answer_id": 33379580,
"author": "esbanarango",
"author_id": 1136821,
"author_profile": "https://Stackoverflow.com/users/1136821",
"pm_score": 0,
"selected": false,
"text": "acts_as_inheritable class Person < ActiveRecord::Base\n\n acts_as_inheritable attributes: %w(favorite_color last_name soccer_team)\n\n # Associations\n belongs_to :parent, class_name: 'Person'\n has_many :children, class_name: 'Person', foreign_key: :parent_id\nend\n\nparent = Person.create(last_name: 'Arango', soccer_team: 'Verdolaga', favorite_color:'Green')\n\nson = Person.create(parent: parent)\nson.inherit_attributes\nson.last_name # => Arango\nson.soccer_team # => Verdolaga\nson.favorite_color # => Green\n class Person < ActiveRecord::Base\n\n acts_as_inheritable associations: %w(pet)\n\n # Associations\n has_one :pet\nend\n\nparent = Person.create(last_name: 'Arango')\nparent_pet = Pet.create(person: parent, name: 'Mango', breed:'Golden Retriver')\nparent_pet.inspect #=> #<Pet id: 1, person_id: 1, name: \"Mango\", breed: \"Golden Retriver\">\n\nson = Person.create(parent: parent)\nson.inherit_relations\nson.pet.inspect # => #<Pet id: 2, person_id: 2, name: \"Mango\", breed: \"Golden Retriver\">\n"
},
{
"answer_id": 40329894,
"author": "ThienSuBS",
"author_id": 4631412,
"author_profile": "https://Stackoverflow.com/users/4631412",
"pm_score": 2,
"selected": false,
"text": "#your rails >= 3.1 (i was done it with Rails 5.0.0.1)\n o = Model.find(id)\n # (Range).each do |item|\n (1..109).each do |item|\n new_record = o.dup\n new_record.save\n end\n # if your rails < 3.1\n o = Model.find(id)\n (1..109).each do |item|\n new_record = o.clone\n new_record.save\n end \n"
},
{
"answer_id": 49322942,
"author": "Paulo Fidalgo",
"author_id": 1006863,
"author_profile": "https://Stackoverflow.com/users/1006863",
"pm_score": 0,
"selected": false,
"text": "class User < ActiveRecord::Base\n # create_table :users do |t|\n # t.string :login\n # t.string :email\n # t.timestamps null: false\n # end\n\n has_one :profile\n has_many :posts\nend\n class UserCloner < Clowne::Cloner\n adapter :active_record\n\n include_association :profile, clone_with: SpecialProfileCloner\n include_association :posts\n\n nullify :login\n\n # params here is an arbitrary Hash passed into cloner\n finalize do |_source, record, params|\n record.email = params[:email]\n end\nend\n\nclass SpecialProfileCloner < Clowne::Cloner\n adapter :active_record\n\n nullify :name\nend\n user = User.last\n#=> <#User(login: 'clown', email: '[email protected]')>\n\ncloned = UserCloner.call(user, email: '[email protected]')\ncloned.persisted?\n# => false\n\ncloned.save!\ncloned.login\n# => nil\ncloned.email\n# => \"[email protected]\"\n\n# associations:\ncloned.posts.count == user.posts.count\n# => true\ncloned.profile.name\n# => nil\n Model.new(Model.last.attributes.reject {|k,_v| k.to_s == 'id'}"
},
{
"answer_id": 51925581,
"author": "Zoran Majstorovic",
"author_id": 3452582,
"author_profile": "https://Stackoverflow.com/users/3452582",
"pm_score": 2,
"selected": false,
"text": "#dup class Offer < ApplicationRecord\n has_many :offer_items\n\n def dup\n super.tap do |new_offer|\n\n # change title of the new instance\n new_offer.title = \"Copy of #{@offer.title}\"\n\n # duplicate offer_items as well\n self.offer_items.each { |offer_item| new_offer.offer_items << offer_item.dup }\n end\n end\nend\n #dup"
},
{
"answer_id": 54035727,
"author": "Foram",
"author_id": 8649274,
"author_profile": "https://Stackoverflow.com/users/8649274",
"pm_score": 3,
"selected": false,
"text": "new_user = old_user.dup\n"
},
{
"answer_id": 66943947,
"author": "Sachin Singh",
"author_id": 13088705,
"author_profile": "https://Stackoverflow.com/users/13088705",
"pm_score": 0,
"selected": false,
"text": "dup new_record = old_record.dup.save\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] |
60,034 |
<p>I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?</p>
|
[
{
"answer_id": 60055,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": false,
"text": "sed sed sed -c s/FOO/BAR/g filename\n"
},
{
"answer_id": 60065,
"author": "Mike Schall",
"author_id": 4231,
"author_profile": "https://Stackoverflow.com/users/4231",
"pm_score": 8,
"selected": false,
"text": "(Get-Content test.txt) | ForEach-Object { $_ -replace \"foo\", \"bar\" } | Set-Content test2.txt\n"
},
{
"answer_id": 64816,
"author": "morechilli",
"author_id": 5427,
"author_profile": "https://Stackoverflow.com/users/5427",
"pm_score": 6,
"selected": false,
"text": "BatchSubstitute.bat FOR FIND CALL SET \"&<>]|^"
},
{
"answer_id": 2363075,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": false,
"text": "fart.exe -p -r -c -- C:\\tools\\perl-5.8.9\\* @@APP_DIR@@ C:\\tools\n &A & fart in.txt \"&A\" \"B\" \n"
},
{
"answer_id": 2419322,
"author": "Chad",
"author_id": 290782,
"author_profile": "https://Stackoverflow.com/users/290782",
"pm_score": 3,
"selected": false,
"text": "set value=new_value\n\n:: Setup initial configuration\n:: I use && as the delimiter in the file because it should not exist, thereby giving me the whole line\n::\necho --> Setting configuration and properties.\nfor /f \"tokens=* delims=&&\" %%a in (config\\config.txt) do ( \n call replace.bat \"%%a\" _KEY_ %value% config\\temp.txt \n)\ndel config\\config.txt\nrename config\\temp.txt config.txt\n replace.bat %%a replace.bat @echo off\n\n:: This ensures the parameters are resolved prior to the internal variable\n::\nSetLocal EnableDelayedExpansion\n\n:: Replaces Key Variables\n::\n:: Parameters:\n:: %1 = Line to search for replacement\n:: %2 = Key to replace\n:: %3 = Value to replace key with\n:: %4 = File in which to write the replacement\n::\n\n:: Read in line without the surrounding double quotes (use ~)\n::\nset line=%~1\n\n:: Write line to specified file, replacing key (%2) with value (%3)\n::\necho !line:%2=%3! >> %4\n\n:: Restore delayed expansion\n::\nEndLocal\n"
},
{
"answer_id": 3309448,
"author": "kool_guy_here",
"author_id": 399147,
"author_profile": "https://Stackoverflow.com/users/399147",
"pm_score": 3,
"selected": false,
"text": "(\ntest.txt | ForEach-Object { $_ -replace \"foo\", \"bar\" } | Set-Content test2.txt\n)\n"
},
{
"answer_id": 3801102,
"author": "user459118",
"author_id": 459118,
"author_profile": "https://Stackoverflow.com/users/459118",
"pm_score": 6,
"selected": false,
"text": "Const ForReading = 1 \nConst ForWriting = 2\n\nstrFileName = Wscript.Arguments(0)\nstrOldText = Wscript.Arguments(1)\nstrNewText = Wscript.Arguments(2)\n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(strFileName, ForReading)\nstrText = objFile.ReadAll\nobjFile.Close\n\nstrNewText = Replace(strText, strOldText, strNewText)\nSet objFile = objFSO.OpenTextFile(strFileName, ForWriting)\nobjFile.Write strNewText 'WriteLine adds extra CR/LF\nobjFile.Close\n cscript replace.vbs \"C:\\Scripts\\Text.txt\" \"Jim \" \"James \""
},
{
"answer_id": 4402290,
"author": "Faisal",
"author_id": 536948,
"author_profile": "https://Stackoverflow.com/users/536948",
"pm_score": 4,
"selected": false,
"text": "perl -pi.orig -e \"s/<textToReplace>/<textToReplaceWith>/g;\" <fileName>\n for %x in (<filePattern>) do perl -pi.orig -e \"s/<textToReplace>/<textToReplaceWith>/g;\" %x\n"
},
{
"answer_id": 6159108,
"author": "Bill Richardson",
"author_id": 773948,
"author_profile": "https://Stackoverflow.com/users/773948",
"pm_score": 7,
"selected": false,
"text": "set str=teh cat in teh hat\necho.%str%\nset str=%str:teh=the%\necho.%str%\n teh cat in teh hat\nthe cat in the hat\n"
},
{
"answer_id": 10490757,
"author": "Simon East",
"author_id": 195835,
"author_profile": "https://Stackoverflow.com/users/195835",
"pm_score": 4,
"selected": false,
"text": "type test.txt | powershell -Command \"$input | ForEach-Object { $_ -replace \\\"foo\\\", \\\"bar\\\" }\"\n type test.txt | powershell -Command \"$input | ForEach-Object { $_ -replace \\\"foo\\\", \\\"bar\\\" }\" > outputFile.txt\n"
},
{
"answer_id": 14396154,
"author": "Aman",
"author_id": 173136,
"author_profile": "https://Stackoverflow.com/users/173136",
"pm_score": 5,
"selected": false,
"text": "fnr fart fnr --cl --dir \"<Directory Path>\" --fileMask \"hibernate.*\" --useRegEx --find \"find_str_expression\" --replace \"replace_string\""
},
{
"answer_id": 16735079,
"author": "dbenham",
"author_id": 1012053,
"author_profile": "https://Stackoverflow.com/users/1012053",
"pm_score": 6,
"selected": false,
"text": "/UTF type test.txt|repl \"foo\" \"bar\" >test.txt.new\nmove /y test.txt.new test.txt\n M X M X @if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment\n\n::************ Documentation ***********\n::REPL.BAT version 6.2\n:::\n:::REPL Search Replace [Options [SourceVar]]\n:::REPL /?[REGEX|REPLACE]\n:::REPL /V\n:::\n::: Performs a global regular expression search and replace operation on\n::: each line of input from stdin and prints the result to stdout.\n:::\n::: Each parameter may be optionally enclosed by double quotes. The double\n::: quotes are not considered part of the argument. The quotes are required\n::: if the parameter contains a batch token delimiter like space, tab, comma,\n::: semicolon. The quotes should also be used if the argument contains a\n::: batch special character like &, |, etc. so that the special character\n::: does not need to be escaped with ^.\n:::\n::: If called with a single argument of /?, then prints help documentation\n::: to stdout. If a single argument of /?REGEX, then opens up Microsoft's\n::: JScript regular expression documentation within your browser. If a single\n::: argument of /?REPLACE, then opens up Microsoft's JScript REPLACE\n::: documentation within your browser.\n:::\n::: If called with a single argument of /V, case insensitive, then prints\n::: the version of REPL.BAT.\n:::\n::: Search - By default, this is a case sensitive JScript (ECMA) regular\n::: expression expressed as a string.\n:::\n::: JScript regex syntax documentation is available at\n::: http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx\n:::\n::: Replace - By default, this is the string to be used as a replacement for\n::: each found search expression. Full support is provided for\n::: substituion patterns available to the JScript replace method.\n:::\n::: For example, $& represents the portion of the source that matched\n::: the entire search pattern, $1 represents the first captured\n::: submatch, $2 the second captured submatch, etc. A $ literal\n::: can be escaped as $$.\n:::\n::: An empty replacement string must be represented as \"\".\n:::\n::: Replace substitution pattern syntax is fully documented at\n::: http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx\n:::\n::: Options - An optional string of characters used to alter the behavior\n::: of REPL. The option characters are case insensitive, and may\n::: appear in any order.\n:::\n::: A - Only print altered lines. Unaltered lines are discarded.\n::: If the S options is present, then prints the result only if\n::: there was a change anywhere in the string. The A option is\n::: incompatible with the M option unless the S option is present.\n:::\n::: B - The Search must match the beginning of a line.\n::: Mostly used with literal searches.\n:::\n::: E - The Search must match the end of a line.\n::: Mostly used with literal searches.\n:::\n::: I - Makes the search case-insensitive.\n:::\n::: J - The Replace argument represents a JScript expression.\n::: The expression may access an array like arguments object\n::: named $. However, $ is not a true array object.\n:::\n::: The $.length property contains the total number of arguments\n::: available. The $.length value is equal to n+3, where n is the\n::: number of capturing left parentheses within the Search string.\n:::\n::: $[0] is the substring that matched the Search,\n::: $[1] through $[n] are the captured submatch strings,\n::: $[n+1] is the offset where the match occurred, and\n::: $[n+2] is the original source string.\n:::\n::: Arguments $[0] through $[10] may be abbreviated as\n::: $1 through $10. Argument $[11] and above must use the square\n::: bracket notation.\n:::\n::: L - The Search is treated as a string literal instead of a\n::: regular expression. Also, all $ found in the Replace string\n::: are treated as $ literals.\n:::\n::: M - Multi-line mode. The entire contents of stdin is read and\n::: processed in one pass instead of line by line, thus enabling\n::: search for \\n. This also enables preservation of the original\n::: line terminators. If the M option is not present, then every\n::: printed line is terminated with carriage return and line feed.\n::: The M option is incompatible with the A option unless the S\n::: option is also present.\n:::\n::: Note: If working with binary data containing NULL bytes,\n::: then the M option must be used.\n:::\n::: S - The source is read from an environment variable instead of\n::: from stdin. The name of the source environment variable is\n::: specified in the next argument after the option string. Without\n::: the M option, ^ anchors the beginning of the string, and $ the\n::: end of the string. With the M option, ^ anchors the beginning\n::: of a line, and $ the end of a line.\n:::\n::: V - Search and Replace represent the name of environment\n::: variables that contain the respective values. An undefined\n::: variable is treated as an empty string.\n:::\n::: X - Enables extended substitution pattern syntax with support\n::: for the following escape sequences within the Replace string:\n:::\n::: \\\\ - Backslash\n::: \\b - Backspace\n::: \\f - Formfeed\n::: \\n - Newline\n::: \\q - Quote\n::: \\r - Carriage Return\n::: \\t - Horizontal Tab\n::: \\v - Vertical Tab\n::: \\xnn - Extended ASCII byte code expressed as 2 hex digits\n::: \\unnnn - Unicode character expressed as 4 hex digits\n:::\n::: Also enables the \\q escape sequence for the Search string.\n::: The other escape sequences are already standard for a regular\n::: expression Search string.\n:::\n::: Also modifies the behavior of \\xnn in the Search string to work\n::: properly with extended ASCII byte codes.\n:::\n::: Extended escape sequences are supported even when the L option\n::: is used. Both Search and Replace support all of the extended\n::: escape sequences if both the X and L opions are combined.\n:::\n::: Return Codes: 0 = At least one change was made\n::: or the /? or /V option was used\n:::\n::: 1 = No change was made\n:::\n::: 2 = Invalid call syntax or incompatible options\n:::\n::: 3 = JScript runtime error, typically due to invalid regex\n:::\n::: REPL.BAT was written by Dave Benham, with assistance from DosTips user Aacini\n::: to get \\xnn to work properly with extended ASCII byte codes. Also assistance\n::: from DosTips user penpen diagnosing issues reading NULL bytes, along with a\n::: workaround. REPL.BAT was originally posted at:\n::: http://www.dostips.com/forum/viewtopic.php?f=3&t=3855\n:::\n\n::************ Batch portion ***********\n@echo off\nif .%2 equ . (\n if \"%~1\" equ \"/?\" (\n <\"%~f0\" cscript //E:JScript //nologo \"%~f0\" \"^:::\" \"\" a\n exit /b 0\n ) else if /i \"%~1\" equ \"/?regex\" (\n explorer \"http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx\"\n exit /b 0\n ) else if /i \"%~1\" equ \"/?replace\" (\n explorer \"http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx\"\n exit /b 0\n ) else if /i \"%~1\" equ \"/V\" (\n <\"%~f0\" cscript //E:JScript //nologo \"%~f0\" \"^::(REPL\\.BAT version)\" \"$1\" a\n exit /b 0\n ) else (\n call :err \"Insufficient arguments\"\n exit /b 2\n )\n)\necho(%~3|findstr /i \"[^SMILEBVXAJ]\" >nul && (\n call :err \"Invalid option(s)\"\n exit /b 2\n)\necho(%~3|findstr /i \"M\"|findstr /i \"A\"|findstr /vi \"S\" >nul && (\n call :err \"Incompatible options\"\n exit /b 2\n)\ncscript //E:JScript //nologo \"%~f0\" %*\nexit /b %errorlevel%\n\n:err\n>&2 echo ERROR: %~1. Use REPL /? to get help.\nexit /b\n\n************* JScript portion **********/\nvar rtn=1;\ntry {\n var env=WScript.CreateObject(\"WScript.Shell\").Environment(\"Process\");\n var args=WScript.Arguments;\n var search=args.Item(0);\n var replace=args.Item(1);\n var options=\"g\";\n if (args.length>2) options+=args.Item(2).toLowerCase();\n var multi=(options.indexOf(\"m\")>=0);\n var alterations=(options.indexOf(\"a\")>=0);\n if (alterations) options=options.replace(/a/g,\"\");\n var srcVar=(options.indexOf(\"s\")>=0);\n if (srcVar) options=options.replace(/s/g,\"\");\n var jexpr=(options.indexOf(\"j\")>=0);\n if (jexpr) options=options.replace(/j/g,\"\");\n if (options.indexOf(\"v\")>=0) {\n options=options.replace(/v/g,\"\");\n search=env(search);\n replace=env(replace);\n }\n if (options.indexOf(\"x\")>=0) {\n options=options.replace(/x/g,\"\");\n if (!jexpr) {\n replace=replace.replace(/\\\\\\\\/g,\"\\\\B\");\n replace=replace.replace(/\\\\q/g,\"\\\"\");\n replace=replace.replace(/\\\\x80/g,\"\\\\u20AC\");\n replace=replace.replace(/\\\\x82/g,\"\\\\u201A\");\n replace=replace.replace(/\\\\x83/g,\"\\\\u0192\");\n replace=replace.replace(/\\\\x84/g,\"\\\\u201E\");\n replace=replace.replace(/\\\\x85/g,\"\\\\u2026\");\n replace=replace.replace(/\\\\x86/g,\"\\\\u2020\");\n replace=replace.replace(/\\\\x87/g,\"\\\\u2021\");\n replace=replace.replace(/\\\\x88/g,\"\\\\u02C6\");\n replace=replace.replace(/\\\\x89/g,\"\\\\u2030\");\n replace=replace.replace(/\\\\x8[aA]/g,\"\\\\u0160\");\n replace=replace.replace(/\\\\x8[bB]/g,\"\\\\u2039\");\n replace=replace.replace(/\\\\x8[cC]/g,\"\\\\u0152\");\n replace=replace.replace(/\\\\x8[eE]/g,\"\\\\u017D\");\n replace=replace.replace(/\\\\x91/g,\"\\\\u2018\");\n replace=replace.replace(/\\\\x92/g,\"\\\\u2019\");\n replace=replace.replace(/\\\\x93/g,\"\\\\u201C\");\n replace=replace.replace(/\\\\x94/g,\"\\\\u201D\");\n replace=replace.replace(/\\\\x95/g,\"\\\\u2022\");\n replace=replace.replace(/\\\\x96/g,\"\\\\u2013\");\n replace=replace.replace(/\\\\x97/g,\"\\\\u2014\");\n replace=replace.replace(/\\\\x98/g,\"\\\\u02DC\");\n replace=replace.replace(/\\\\x99/g,\"\\\\u2122\");\n replace=replace.replace(/\\\\x9[aA]/g,\"\\\\u0161\");\n replace=replace.replace(/\\\\x9[bB]/g,\"\\\\u203A\");\n replace=replace.replace(/\\\\x9[cC]/g,\"\\\\u0153\");\n replace=replace.replace(/\\\\x9[dD]/g,\"\\\\u009D\");\n replace=replace.replace(/\\\\x9[eE]/g,\"\\\\u017E\");\n replace=replace.replace(/\\\\x9[fF]/g,\"\\\\u0178\");\n replace=replace.replace(/\\\\b/g,\"\\b\");\n replace=replace.replace(/\\\\f/g,\"\\f\");\n replace=replace.replace(/\\\\n/g,\"\\n\");\n replace=replace.replace(/\\\\r/g,\"\\r\");\n replace=replace.replace(/\\\\t/g,\"\\t\");\n replace=replace.replace(/\\\\v/g,\"\\v\");\n replace=replace.replace(/\\\\x[0-9a-fA-F]{2}|\\\\u[0-9a-fA-F]{4}/g,\n function($0,$1,$2){\n return String.fromCharCode(parseInt(\"0x\"+$0.substring(2)));\n }\n );\n replace=replace.replace(/\\\\B/g,\"\\\\\");\n }\n search=search.replace(/\\\\\\\\/g,\"\\\\B\");\n search=search.replace(/\\\\q/g,\"\\\"\");\n search=search.replace(/\\\\x80/g,\"\\\\u20AC\");\n search=search.replace(/\\\\x82/g,\"\\\\u201A\");\n search=search.replace(/\\\\x83/g,\"\\\\u0192\");\n search=search.replace(/\\\\x84/g,\"\\\\u201E\");\n search=search.replace(/\\\\x85/g,\"\\\\u2026\");\n search=search.replace(/\\\\x86/g,\"\\\\u2020\");\n search=search.replace(/\\\\x87/g,\"\\\\u2021\");\n search=search.replace(/\\\\x88/g,\"\\\\u02C6\");\n search=search.replace(/\\\\x89/g,\"\\\\u2030\");\n search=search.replace(/\\\\x8[aA]/g,\"\\\\u0160\");\n search=search.replace(/\\\\x8[bB]/g,\"\\\\u2039\");\n search=search.replace(/\\\\x8[cC]/g,\"\\\\u0152\");\n search=search.replace(/\\\\x8[eE]/g,\"\\\\u017D\");\n search=search.replace(/\\\\x91/g,\"\\\\u2018\");\n search=search.replace(/\\\\x92/g,\"\\\\u2019\");\n search=search.replace(/\\\\x93/g,\"\\\\u201C\");\n search=search.replace(/\\\\x94/g,\"\\\\u201D\");\n search=search.replace(/\\\\x95/g,\"\\\\u2022\");\n search=search.replace(/\\\\x96/g,\"\\\\u2013\");\n search=search.replace(/\\\\x97/g,\"\\\\u2014\");\n search=search.replace(/\\\\x98/g,\"\\\\u02DC\");\n search=search.replace(/\\\\x99/g,\"\\\\u2122\");\n search=search.replace(/\\\\x9[aA]/g,\"\\\\u0161\");\n search=search.replace(/\\\\x9[bB]/g,\"\\\\u203A\");\n search=search.replace(/\\\\x9[cC]/g,\"\\\\u0153\");\n search=search.replace(/\\\\x9[dD]/g,\"\\\\u009D\");\n search=search.replace(/\\\\x9[eE]/g,\"\\\\u017E\");\n search=search.replace(/\\\\x9[fF]/g,\"\\\\u0178\");\n if (options.indexOf(\"l\")>=0) {\n search=search.replace(/\\\\b/g,\"\\b\");\n search=search.replace(/\\\\f/g,\"\\f\");\n search=search.replace(/\\\\n/g,\"\\n\");\n search=search.replace(/\\\\r/g,\"\\r\");\n search=search.replace(/\\\\t/g,\"\\t\");\n search=search.replace(/\\\\v/g,\"\\v\");\n search=search.replace(/\\\\x[0-9a-fA-F]{2}|\\\\u[0-9a-fA-F]{4}/g,\n function($0,$1,$2){\n return String.fromCharCode(parseInt(\"0x\"+$0.substring(2)));\n }\n );\n search=search.replace(/\\\\B/g,\"\\\\\");\n } else search=search.replace(/\\\\B/g,\"\\\\\\\\\");\n }\n if (options.indexOf(\"l\")>=0) {\n options=options.replace(/l/g,\"\");\n search=search.replace(/([.^$*+?()[{\\\\|])/g,\"\\\\$1\");\n if (!jexpr) replace=replace.replace(/\\$/g,\"$$$$\");\n }\n if (options.indexOf(\"b\")>=0) {\n options=options.replace(/b/g,\"\");\n search=\"^\"+search\n }\n if (options.indexOf(\"e\")>=0) {\n options=options.replace(/e/g,\"\");\n search=search+\"$\"\n }\n var search=new RegExp(search,options);\n var str1, str2;\n\n if (srcVar) {\n str1=env(args.Item(3));\n str2=str1.replace(search,jexpr?replFunc:replace);\n if (!alterations || str1!=str2) if (multi) {\n WScript.Stdout.Write(str2);\n } else {\n WScript.Stdout.WriteLine(str2);\n }\n if (str1!=str2) rtn=0;\n } else if (multi){\n var buf=1024;\n str1=\"\";\n while (!WScript.StdIn.AtEndOfStream) {\n str1+=WScript.StdIn.Read(buf);\n buf*=2\n }\n str2=str1.replace(search,jexpr?replFunc:replace);\n WScript.Stdout.Write(str2);\n if (str1!=str2) rtn=0;\n } else {\n while (!WScript.StdIn.AtEndOfStream) {\n str1=WScript.StdIn.ReadLine();\n str2=str1.replace(search,jexpr?replFunc:replace);\n if (!alterations || str1!=str2) WScript.Stdout.WriteLine(str2);\n if (str1!=str2) rtn=0;\n }\n }\n} catch(e) {\n WScript.Stderr.WriteLine(\"JScript runtime error: \"+e.message);\n rtn=3;\n}\nWScript.Quit(rtn);\n\nfunction replFunc($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) {\n var $=arguments;\n return(eval(replace));\n}\n jrepl \"foo\" \"bar\" /f test.txt /o -\n"
},
{
"answer_id": 20999154,
"author": "Rachel",
"author_id": 302677,
"author_profile": "https://Stackoverflow.com/users/302677",
"pm_score": 10,
"selected": true,
"text": "powershell -Command \"(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt\"\n powershell -Command \"... \" (gc myFile.txt) myFile.txt gc Get-Content -replace 'foo', 'bar' foo bar | Out-File myFile.txt myFile.txt -encoding ASCII C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0 (Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt\n"
},
{
"answer_id": 24887951,
"author": "foxidrive",
"author_id": 2299431,
"author_profile": "https://Stackoverflow.com/users/2299431",
"pm_score": 3,
"selected": false,
"text": "search and replace dbenham aacini native built-in jscript robust very swift with large files simpler Windows regular expression sed-like repl.bat L echo This is FOO here|repl \"FOO\" \"BAR\" L\necho and with a file:\ntype \"file.txt\" |repl \"FOO\" \"BAR\" L >\"newfile.txt\"\n grep-like findrepl.bat echo This is FOO here|findrepl \"FOO\" \"BAR\" \necho and with a file:\ntype \"file.txt\" |findrepl \"FOO\" \"BAR\" >\"newfile.txt\"\n when placed in a folder that is on the path case-insensitive"
},
{
"answer_id": 26894259,
"author": "Leptonator",
"author_id": 175063,
"author_profile": "https://Stackoverflow.com/users/175063",
"pm_score": 5,
"selected": false,
"text": "DEL New.txt\nsetLocal EnableDelayedExpansion\nFor /f \"tokens=* delims= \" %%a in (OLD.txt) do (\nSet str=%%a\nset str=!str:FOO=BAR!\necho !str!>>New.txt\n)\nENDLOCAL\n REM DE-DUPLICATE THE Mapping.txt FILE\nREM THE DE-DUPLICATED FILE IS STORED AS new.txt\n\nset MapFile=Mapping.txt\nset ReplaceFile=New.txt\n\ndel %ReplaceFile%\n::DelDupeText.bat\nrem https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o\nsetLocal EnableDelayedExpansion\nfor /f \"tokens=1,2 delims=,\" %%a in (%MapFile%) do (\nset str=%%a\nrem Ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString\nset str=!str:~-9!\nset str2=%%a\nset str3=%%a,%%b\n\nfind /i ^\"!str!^\" %MapFile%\nfind /i ^\"!str!^\" %ReplaceFile%\nif errorlevel 1 echo !str3!>>%ReplaceFile%\n)\nENDLOCAL\n"
},
{
"answer_id": 33149373,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 4,
"selected": false,
"text": "e? \\n\\r \"Foo\" \"Bar\" call replacer.bat \"e?C:\\content.txt\" \"\\u0022Foo\\u0022\" \"\\u0022Bar\\u0022\"\n Foo Bar call replacer.bat \"C:\\content.txt\" \"Foo\" \"Bar\"\n"
},
{
"answer_id": 33762001,
"author": "Jens A. Koch",
"author_id": 1163786,
"author_profile": "https://Stackoverflow.com/users/1163786",
"pm_score": 4,
"selected": false,
"text": "git-bash sed sed sed -i -e 's/foo/bar/g' filename\n -i -e s g git ls-files <eventual subfolders & filters> | xargs sed -i -e 's/foo/bar/g'"
},
{
"answer_id": 44577233,
"author": "Whome",
"author_id": 185565,
"author_profile": "https://Stackoverflow.com/users/185565",
"pm_score": 2,
"selected": false,
"text": "$data @REM ASCII=7bit ascii(no bom), UTF8=with bom marker\nset cmd=^\n $old = '\\$Param1\\$'; ^\n $new = 'Value1'; ^\n [string[]]$data = Get-Content 'datafile.txt'; ^\n $data = $data -replace $old, $new; ^\n out-file -InputObject $data -encoding UTF8 -filepath 'datafile.txt';\npowershell -NoLogo -Noninteractive -InputFormat none -Command \"%cmd%\"\n"
},
{
"answer_id": 49868359,
"author": "Wagner Pereira",
"author_id": 3954704,
"author_profile": "https://Stackoverflow.com/users/3954704",
"pm_score": 2,
"selected": false,
"text": "@echo off\nset ffile='myfile.txt'\nset fold='FOO'\nset fnew='BAR'\npowershell -Command \"(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8\"\n"
},
{
"answer_id": 55664924,
"author": "eQ19",
"author_id": 4058484,
"author_profile": "https://Stackoverflow.com/users/4058484",
"pm_score": 3,
"selected": false,
"text": "sed '' \"\" sed -i sed sed -e \"s/foo/bar/g\" test.txt > tmp.txt && mv tmp.txt test.txt\n"
},
{
"answer_id": 69695302,
"author": "Georgie",
"author_id": 2344075,
"author_profile": "https://Stackoverflow.com/users/2344075",
"pm_score": 2,
"selected": false,
"text": "powershell -Command \"(gc 'My file.sql' -encoding \"Default\") -replace 'String 1', 'String 2' | Out-File -encoding \"Default\" 'My file.sql'\"\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
60,046 |
<p>I'm embedding the Google Maps Flash API in Flex and it runs fine locally with the watermark on it, etc. When I upload it to the server (flex.mydomain.com) I get a sandbox security error listed below: </p>
<pre><code>SecurityError: Error #2121: Security sandbox violation: Loader.content: http://mydomain.com/main.swf?Fri, 12 Sep 2008 21:46:03 UTC cannot access http://maps.googleapis.com/maps/lib/map_1_6.swf. This may be worked around by calling Security.allowDomain.
at flash.display::Loader/get content()
at com.google.maps::ClientBootstrap/createFactory()
at com.google.maps::ClientBootstrap/executeNextFrameCalls()
</code></pre>
<p>Does anyone have any experience with embedding the Google Maps Flash API into Flex components and specifically settings security settings to make this work? I did get a new API key that is registered to my domain and am using that when it's published.</p>
<p>I've tried doing the following in the main application as well as the component:</p>
<pre><code>Security.allowDomain('*')
Security.allowDomain('maps.googleapis.com')
Security.allowDomain('mydomain.com')
</code></pre>
|
[
{
"answer_id": 60453,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "crossdomain.xml"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4760/"
] |
60,051 |
<p>My question is pertaining to the best practice for accessing a child object's parent. So let's say a class instantiates another class, that class instance is now referenced with an object. From that child object, what is the best way to reference back to the parent object? Currently I know of a couple ways that I use often, but I'm not sure if A) there is a better way to do it or B) which of them is the better practice</p>
<p>The first method is to use getDefinitionByName, which would not instantiate that class, but allow access to anything inside of it that was publicly declared.</p>
<pre><code>_class:Class = getDefinitionByName("com.site.Class") as Class;
</code></pre>
<p>And then reference that variable based on its parent to child hierarchy.<br>
Example, if the child is attempting to reference a class that's two levels up from itself:</p>
<pre><code>_class(parent.parent).function();
</code></pre>
<p>This seems to work fine, but you are required to know the level at which the child is at compared to the level of the parent you are attempting to access.</p>
<p>I can also get the following statement to trace out [object ClassName] into Flash's output.</p>
<pre><code>trace(Class);
</code></pre>
<p>I'm not 100% on the implementation of that line, I haven't persued it as a way to reference an object outside of the current object I'm in.</p>
<p>Another method I've seen used is to simply pass a reference to this into the class object you are creating and just catch it with a constructor argument</p>
<pre><code>var class:Class = new Class(this);
</code></pre>
<p>and then in the Class file</p>
<pre><code>public function Class(objectRef:Object) {
_parentRef = objectRef;
}
</code></pre>
<p>That reference also requires you to step back up using the child to parent hierarchy though.</p>
<p>I could also import that class, and then use the direct filepath to reference a method inside of that class, regardless of its the parent or not.</p>
<pre><code>import com.site.Class;
com.site.Class.method();
</code></pre>
<p>Of course there the parent to child relationship is irrelevant because I'm accessing the method or property directly through the imported class.</p>
<p>I just feel like I'm missing something really obvious here. I'm basically looking for confirmation if these are the correct ways to reference the parent, and if so which is the most ideal, or am I over-looking something else?</p>
|
[
{
"answer_id": 64085,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "private static const class:Class;\n\npublic static function setClass(_class:Class){\nclass = _class;\n}\npublic static function getClass(void):Class{\nreturn class;\n}\n"
},
{
"answer_id": 67526,
"author": "mikechambers",
"author_id": 10232,
"author_profile": "https://Stackoverflow.com/users/10232",
"pm_score": 3,
"selected": false,
"text": "//Child.as\npackage\n{\n import flash.events.EventDispatcher;\n import flash.events.Event;\n\n public class Child extends EventDispatcher\n {\n public function doSomething():void\n {\n var e:Event = new Event(Event.COMPLETE);\n dispatchEvent(e);\n }\n\n public function foo():void\n {\n trace(\"foo\");\n }\n }\n}\n\n\n//Parent.as\npackage\n{\n import flash.display.Sprite;\n import flash.events.Event;\n public class Parent extends Sprite\n {\n private var child:Child;\n public function Parent():void\n {\n c = new Child();\n c.addEventListener(Event.COMPLETE, onComplete);\n c.foo();//traces foo\n\n c.doSomething()\n }\n\n public function onComplete(e:Event):void\n {\n trace(\"Child broadcast Event.COMPLETE\");\n }\n\n }\n}\n"
},
{
"answer_id": 1077501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "ParentClass(parent).parentFunction();\n ParentClass(stage.getChildAt(0)).parentFunction();\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945/"
] |
60,070 |
<p>I am currently in an operating systems class and my teacher spent half of the class period talking about PIDs. She mentioned, as many know, that processes know their parent's ID.</p>
<p>My question is this:</p>
<p>Does a process's PCB know its child's ID? If so, what is the way to go about it obtaining it?</p>
|
[
{
"answer_id": 60075,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 2,
"selected": false,
"text": "fork()"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73/"
] |
60,093 |
<p>I have a c# asp.net web app. Breakpoints in the database layer are no longer stopping execution but the breakpoints in the UI layer are still working okay. Can anyone hazard a guess why this might be happening?</p>
<p>I've checked all the usual suspects (Debug build is on for all projects) and recompiled all projects in solution...</p>
|
[
{
"answer_id": 60106,
"author": "Tyler",
"author_id": 5642,
"author_profile": "https://Stackoverflow.com/users/5642",
"pm_score": 1,
"selected": false,
"text": "Modules View .dlls .PDBs .PDBs .dlls"
},
{
"answer_id": 1234258,
"author": "Jack Marchetti",
"author_id": 117658,
"author_profile": "https://Stackoverflow.com/users/117658",
"pm_score": 0,
"selected": false,
"text": " <location path=\".\" inheritInChildApplications=\"false\">\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
60,098 |
<p>I wrote a simple web service in C# using SharpDevelop (which I just got and I love).</p>
<p>The client wanted it in VB, and fortunately there's a Convert To VB.NET feature. It's great. Translated all the code, and it builds. (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.)</p>
<p>But I get this error when I try to load the service now.</p>
<pre>
Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'.
Source Error:
Line 1: <%@ WebService Class="flightinfo.Soap,flightinfo" %>
</pre>
<p>I have deleted the bins and rebuilt, and I have searched google (and stackoverflow). I have scoured the project files for any remnants of C#.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 60108,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<%@ WebService Class=\"flightinfo.Soap,flightinfo\" %>\n"
},
{
"answer_id": 201092,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 2,
"selected": true,
"text": "Namespace Z End Namespace namespace X.Y"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525/"
] |
60,160 |
<p>Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.</p>
|
[
{
"answer_id": 60161,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 10,
"selected": true,
"text": "Pattern.quote(\"$5\");\n"
},
{
"answer_id": 60164,
"author": "Rob Oxspring",
"author_id": 1867,
"author_profile": "https://Stackoverflow.com/users/1867",
"pm_score": 4,
"selected": false,
"text": "\\Q$5\\E Pattern.quote(s)"
},
{
"answer_id": 60172,
"author": "Pavel Feldman",
"author_id": 5507,
"author_profile": "https://Stackoverflow.com/users/5507",
"pm_score": 7,
"selected": false,
"text": "Pattern.quote Matcher.quoteReplacement s.replaceFirst(Pattern.quote(\"text to replace\"), \n Matcher.quoteReplacement(\"replacement text\"));\n"
},
{
"answer_id": 11955201,
"author": "Meower68",
"author_id": 251767,
"author_profile": "https://Stackoverflow.com/users/251767",
"pm_score": 3,
"selected": false,
"text": "java.lang.IndexOutOfBoundsException: No group 3\nat java.util.regex.Matcher.start(Matcher.java:374)\nat java.util.regex.Matcher.appendReplacement(Matcher.java:748)\nat java.util.regex.Matcher.replaceAll(Matcher.java:823)\nat java.lang.String.replaceAll(String.java:2201)\n // \"msg\" is a string from a .properties file, containing \"<userInput />\" among other tags\n// \"userInput\" is a String containing the user's input\n msg = msg.replaceAll(\"<userInput \\\\/>\", userInput);\n msg = msg.replaceAll(\"<userInput \\\\/>\", Matcher.quoteReplacement(userInput));\n"
},
{
"answer_id": 13405612,
"author": "Moscow Boy",
"author_id": 925098,
"author_profile": "https://Stackoverflow.com/users/925098",
"pm_score": 3,
"selected": false,
"text": "public class Test {\n public static void main(String[] args) {\n String str = \"y z (111)\";\n String p1 = \"x x (111)\";\n String p2 = \".* .* \\\\(111\\\\)\";\n\n p1 = escapeRE(p1);\n\n p1 = p1.replace(\"x\", \".*\");\n\n System.out.println( p1 + \"-->\" + str.matches(p1) ); \n //.*\\ .*\\ \\(111\\)-->true\n System.out.println( p2 + \"-->\" + str.matches(p2) ); \n //.* .* \\(111\\)-->true\n }\n\n public static String escapeRE(String str) {\n //Pattern escaper = Pattern.compile(\"([^a-zA-z0-9])\");\n //return escaper.matcher(str).replaceAll(\"\\\\\\\\$1\");\n return str.replaceAll(\"([^a-zA-Z0-9])\", \"\\\\\\\\$1\");\n }\n}\n"
},
{
"answer_id": 35991060,
"author": "Androidme",
"author_id": 1014693,
"author_profile": "https://Stackoverflow.com/users/1014693",
"pm_score": 5,
"selected": false,
"text": "Pattern.LITERAL Pattern.compile(textToFormat, Pattern.LITERAL);\n"
},
{
"answer_id": 45415931,
"author": "Adam111p",
"author_id": 3058581,
"author_profile": "https://Stackoverflow.com/users/3058581",
"pm_score": 3,
"selected": false,
"text": "String someText = \"Some/s/wText*/,**\";\nSystem.out.println(someText.replaceAll(\"[-\\\\[\\\\]{}()*+?.,\\\\\\\\\\\\\\\\^$|#\\\\\\\\s]\", \"\\\\\\\\$0\"));\n String someText = \"Some\\\\E/s/wText*/,**\";\nSystem.out.println(\"Pattern.quote: \"+ Pattern.quote(someText));\nSystem.out.println(\"Full escape: \"+someText.replaceAll(\"[-\\\\[\\\\]{}()*+?.,\\\\\\\\\\\\\\\\^$|#\\\\\\\\s]\", \"\\\\\\\\$0\"));\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338/"
] |
60,168 |
<p>Here is an example of what I've got going on:</p>
<pre><code>CREATE TABLE Parent (id BIGINT NOT NULL,
PRIMARY KEY (id)) ENGINE=InnoDB;
CREATE TABLE Child (id BIGINT NOT NULL,
parentid BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (parentid),
CONSTRAINT fk_parent FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE) ENGINE=InnoDB;
CREATE TABLE Uncle (id BIGINT NOT NULL,
parentid BIGINT NOT NULL,
childid BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (parentid),
KEY (childid),
CONSTRAINT fk_parent_u FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE,
CONSTRAINT fk_child FOREIGN KEY (childid) REFERENCES Child (id)) ENGINE=InnoDB;
</code></pre>
<p>Notice there is no ON DELETE CASCADE for the Uncle-Child relationship; i.e. deleting a Child does not delete its Uncle(s) and vice-versa.</p>
<p>When I have a Parent and an Uncle with the same Child, and I delete the Parent, it <em>seems</em> like InnoDB should be able to just "figure it out" and let the cascade ripple through the whole family (i.e. deleting the Parent deletes the Uncle and the Child as well). However, instead, I get the following:</p>
<pre><code> ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cascade_test/uncle`, CONSTRAINT `fk_child` FOREIGN KEY (`childid`) REFERENCES `child` (`id`))
</code></pre>
<p>InnoDB is trying to cascade-delete the Child before the Uncle(s) that refer to it.</p>
<p>Am I missing something? Is this <em>supposed</em> to fail for some reason I don't understand? Or is there some trick to making it work (or is it a bug in MySQL)?</p>
|
[
{
"answer_id": 60229,
"author": "Tony BenBrahim",
"author_id": 80075,
"author_profile": "https://Stackoverflow.com/users/80075",
"pm_score": -1,
"selected": false,
"text": "\nselect id from persons where -find all children of the grandparents\nparent id in (\n select parentid from persons --find the grandparents\n where id in (\n select parentid from persons --find the parents\n where id=THECHILD)\n )\nminus --and take out the child's parents\nselect parentid from persons\nwhere id=THECHILD\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6198/"
] |
60,174 |
<p>If user input is inserted without modification into an SQL query, then the application becomes vulnerable to <a href="https://stackoverflow.com/a/332367/">SQL injection</a>, like in the following example:</p>
<pre class="lang-php prettyprint-override"><code>$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
</code></pre>
<p>That's because the user can input something like <code>value'); DROP TABLE table;--</code>, and the query becomes:</p>
<pre><code>INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
</code></pre>
<p>What can be done to prevent this from happening?</p>
|
[
{
"answer_id": 60180,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 10,
"selected": false,
"text": "mysql_ mysqli_ pgsql_"
},
{
"answer_id": 60195,
"author": "Tanerax",
"author_id": 567,
"author_profile": "https://Stackoverflow.com/users/567",
"pm_score": 9,
"selected": false,
"text": "$safe_variable = mysqli_real_escape_string($dbConnection, $_POST[\"user-input\"]);\nmysqli_query($dbConnection, \"INSERT INTO table (column) VALUES ('\" . $safe_variable . \"')\");\n"
},
{
"answer_id": 60442,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 11,
"selected": false,
"text": "<?php\nmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n$mysqli = new mysqli(\"server\", \"username\", \"password\", \"database_name\");\n\n$variable = $_POST[\"user-input\"];\n$stmt = $mysqli->prepare(\"INSERT INTO table (column) VALUES (?)\");\n// \"s\" means the database expects a string\n$stmt->bind_param(\"s\", $variable);\n$stmt->execute();\n mysqli::prepare mysql_real_escape_string"
},
{
"answer_id": 60496,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 14,
"selected": true,
"text": "$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');\n$stmt->execute([ 'name' => $name ]);\n\nforeach ($stmt as $row) {\n // Do something with $row\n}\n $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');\n$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'\n$stmt->execute();\n\n$result = $stmt->get_result();\nwhile ($row = $result->fetch_assoc()) {\n // Do something with $row\n}\n pg_prepare() pg_execute() $dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');\n\n$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n PDOException setAttribute() charset mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting\n$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');\n$dbConnection->set_charset('utf8mb4'); // charset\n prepare ? :name execute $name 'Sarah'; DELETE FROM employees \"'Sarah'; DELETE FROM employees\" $preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');\n\n$preparedStatement->execute([ 'column' => $unsafeValue ]);\n // Value whitelist\n// $dir can only be 'DESC', otherwise it will be 'ASC'\nif (empty($dir) || $dir !== 'DESC') {\n $dir = 'ASC';\n}\n"
},
{
"answer_id": 60530,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": 9,
"selected": false,
"text": "PDO $conn PDO $stmt = $conn->prepare(\"INSERT INTO tbl VALUES(:id, :name)\");\n$stmt->bindValue(':id', $id);\n$stmt->bindValue(':name', $name);\n$stmt->execute();\n"
},
{
"answer_id": 348719,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 9,
"selected": false,
"text": "magic_quotes stripslashes"
},
{
"answer_id": 6381189,
"author": "rahularyansharma",
"author_id": 779158,
"author_profile": "https://Stackoverflow.com/users/779158",
"pm_score": 9,
"selected": false,
"text": "MySQL mysql_real_escape_string() mysql_real_escape_string() mysql_real_escape_string mysql_real_escape_string $name_bad = \"' OR 1'\"; \n\n$name_bad = mysql_real_escape_string($name_bad);\n\n$query_bad = \"SELECT * FROM customers WHERE username = '$name_bad'\";\necho \"Escaped Bad Injection: <br />\" . $query_bad . \"<br />\";\n\n\n$name_evil = \"'; DELETE FROM customers WHERE 1 or username = '\"; \n\n$name_evil = mysql_real_escape_string($name_evil);\n\n$query_evil = \"SELECT * FROM customers WHERE username = '$name_evil'\";\necho \"Escaped Evil Injection: <br />\" . $query_evil;\n"
},
{
"answer_id": 6565763,
"author": "Cedric",
"author_id": 154607,
"author_profile": "https://Stackoverflow.com/users/154607",
"pm_score": 9,
"selected": false,
"text": "MySQL mysql_real_escape_string() mysql_real_escape_string() $offset = isset($_GET['o']) ? $_GET['o'] : 0;\n$offset = mysql_real_escape_string($offset);\nRunQuery(\"SELECT userid, username FROM sql_injection_test LIMIT $offset, 10\");\n $order = isset($_GET['o']) ? $_GET['o'] : 'userid';\n$order = mysql_real_escape_string($order);\nRunQuery(\"SELECT userid, username FROM sql_injection_test ORDER BY `$order`\");\n '"
},
{
"answer_id": 8255054,
"author": "Your Common Sense",
"author_id": 285587,
"author_profile": "https://Stackoverflow.com/users/285587",
"pm_score": 10,
"selected": false,
"text": "$orders = array(\"name\", \"price\", \"qty\"); // Field names\n$key = array_search($_GET['sort'], $orders)); // if we have such a name\n$orderby = $orders[$key]; // If not, first one will be set automatically. \n$query = \"SELECT * FROM `table` ORDER BY $orderby\"; // Value is safe\n $orderby = white_list($_GET['orderby'], \"name\", [\"name\",\"price\",\"qty\"], \"Invalid field name\");\n$query = \"SELECT * FROM `table` ORDER BY `$orderby`\"; // sound and safe\n AND DESC *_escape_string"
},
{
"answer_id": 10992656,
"author": "devOp",
"author_id": 842330,
"author_profile": "https://Stackoverflow.com/users/842330",
"pm_score": 8,
"selected": false,
"text": "$unsafe_variable = $_POST['user_id'];\n\n$safe_variable = (int)$unsafe_variable ;\n\nmysqli_query($conn, \"INSERT INTO table (column) VALUES ('\" . $safe_variable . \"')\");\n"
},
{
"answer_id": 11610605,
"author": "Manish Shrivastava",
"author_id": 1133932,
"author_profile": "https://Stackoverflow.com/users/1133932",
"pm_score": 8,
"selected": false,
"text": "$query=\"select * from users where email='\".$_POST['email'].\"' and password='\".$_POST['password'].\"' \";\n $_POST['email']= [email protected]' OR '1=1\n $query=\"select * from users where email='[email protected]' OR '1=1';\n"
},
{
"answer_id": 11802479,
"author": "Nicolas Finelli",
"author_id": 1720432,
"author_profile": "https://Stackoverflow.com/users/1720432",
"pm_score": 8,
"selected": false,
"text": "mysql_real_escape_string() mysql_escape_string() SELECT * FROM users WHERE name = '\".mysql_escape_string($name_from_html_form).\"'\n mysql_escape_string wHERE 1=1 or LIMIT 1\n SELECT * FROM users WHERE name = '\".mysql_escape_string($name_from_html_form).\"' LIMIT 1\n"
},
{
"answer_id": 12426697,
"author": "Soumalya Banerjee",
"author_id": 1019484,
"author_profile": "https://Stackoverflow.com/users/1019484",
"pm_score": 7,
"selected": false,
"text": "mysql_real_escape_string() mysql_real_escape_string() \\x00 \\n \\r \\ ' \" \\x1a $iId = mysql_real_escape_string(\"1 OR 1=1\");\n $sSql = \"SELECT * FROM table WHERE id = $iId\"; $iId = (int) mysql_real_escape_string(\"1 OR 1=1\");\n $sSql = \"SELECT * FROM table WHERE id = $iId\"; mysql_real_escape_string() string mysqli_real_escape_string ( mysqli $link , string $escapestr )\n $iId = $mysqli->real_escape_string(\"1 OR 1=1\");\n$mysqli->query(\"SELECT * FROM table WHERE id = $iId\");\n"
},
{
"answer_id": 12500462,
"author": "Xeoncross",
"author_id": 99923,
"author_profile": "https://Stackoverflow.com/users/99923",
"pm_score": 8,
"selected": false,
"text": "mysql_ $count = DB::column('SELECT COUNT(*) FROM `user`');\n $pairs = DB::pairs('SELECT `id`, `username` FROM `user`');\n $user = DB::row('SELECT * FROM `user` WHERE `id` = ?', array($user_id));\n $banned_users = DB::fetch('SELECT * FROM `user` WHERE `banned` = ?', array('TRUE'));\n"
},
{
"answer_id": 12710285,
"author": "Zaffy",
"author_id": 823738,
"author_profile": "https://Stackoverflow.com/users/823738",
"pm_score": 9,
"selected": false,
"text": "sprintf(\"SELECT 1,2,3 FROM table WHERE 4 = %u\", $input); mysql_hex_string() bin2hex() mysql_real_escape_string ((2*input_length)+1) 0x UNHEX SELECT password FROM users WHERE name = 'root';\n SELECT password FROM users WHERE name = 0x726f6f74;\n SELECT password FROM users WHERE name = UNHEX('726f6f74');\n 0x char varchar text block binary '' UNHEX() mysql_real_escape_string \"SELECT title FROM article WHERE id = \" . mysql_real_escape_string($_GET[\"id\"])\n SELECT ... WHERE id = -1 UNION ALL SELECT table_name FROM information_schema.tables;\n SELECT ... WHERE id = -1 UNION ALL SELECT column_name FROM information_schema.column WHERE table_name = __0x61727469636c65__;\n SELECT ... WHERE id = UNHEX('2d312075...3635');\n"
},
{
"answer_id": 12822319,
"author": "RDK",
"author_id": 1032750,
"author_profile": "https://Stackoverflow.com/users/1032750",
"pm_score": 8,
"selected": false,
"text": "$request = $pdoConnection->(\"INSERT INTO parents (name, addr, city) values ($name, $addr, $city)\");\n $request = $pdoConnection->(\"INSERT INTO parents (name, addr, city) values (?, ?, ?);\n $request = $pdoConnection->(\"INSERT INTO parents (name, addr, city) value (:name, :addr, :city)\");\n $request = $mysqliConnection->prepare('\n SELECT * FROM trainers\n WHERE name = ?\n AND email = ?\n AND last_login > ?');\n\n $query->bind_param('first_param', 'second_param', $mail, time() - 3600);\n $query->execute();\n"
},
{
"answer_id": 13064261,
"author": "Apurv Nerlekar",
"author_id": 1266952,
"author_profile": "https://Stackoverflow.com/users/1266952",
"pm_score": 8,
"selected": false,
"text": " GRANT SELECT, INSERT, DELETE ON database TO username@'localhost' IDENTIFIED BY 'password';\n FLUSH PRIVILEGES; \n select * from mysql.user where User='username';\n"
},
{
"answer_id": 14569797,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "[1] UNION SELECT IF(SUBSTRING(Password,1,1)='2',BENCHMARK(100000,SHA1(1)),0) User,Password FROM mysql.user WHERE User = 'root'\n $user = \"''1''\"; // Malicious keyword\n$sql = 'SELECT * FROM awa_user WHERE userame =:username';\n$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));\n$sth->execute(array(':username' => $user));\n 189 Query SELECT * FROM awa_user WHERE userame ='\\'\\'1\\'\\''\n 189 Quit\n $stmt = $mysqli->prepare(\"SELECT * FROM awa_user WHERE username =?\")) {\n$stmt->bind_param(\"s\", $user);\n$user = \"''1''\";\n$stmt->execute();\n 188 Prepare SELECT * FROM awa_user WHERE username =?\n 188 Execute SELECT * FROM awa_user WHERE username ='\\'\\'1\\'\\''\n 188 Quit\n intval()"
},
{
"answer_id": 15805869,
"author": "5ervant - techintel.github.io",
"author_id": 2007055,
"author_profile": "https://Stackoverflow.com/users/2007055",
"pm_score": 7,
"selected": false,
"text": "X=Y $_GET RewriteCond %{QUERY_STRING} ([0-9]+)=([0-9]+)\nRewriteRule ^(.*) ^/track.php\n 1=1 2=2 1=2 2=1 1+1=2"
},
{
"answer_id": 16466714,
"author": "Danijel",
"author_id": 2352773,
"author_profile": "https://Stackoverflow.com/users/2352773",
"pm_score": 8,
"selected": false,
"text": "$mysqli = new mysqli('host', 'user', 'password', 'database');\n$mysqli->set_charset('charset');\n\n$string = $mysqli->real_escape_string($string);\n$mysqli->query(\"INSERT INTO table (column) VALUES ('$string')\");\n $stmt = $mysqli->prepare(\"INSERT INTO table (column1, column2) VALUES (?,?)\");\n\n$stmt->bind_param(\"is\", $integer, $string);\n\n$stmt->execute();\n mysqli_real_escape_string mysqli_stmt_bind_param mysqli_real_escape_string mysqli_real_escape_string sprintf $string = \"x' OR name LIKE '%John%\";\n$integer = '5 OR id != 0';\n\n$query = sprintf( \"SELECT id, email, pass, name FROM members WHERE email ='%s' AND id = %d\", $mysqli->real_escape_string($string), $integer);\n\necho $query;\n// SELECT id, email, pass, name FROM members WHERE email ='x\\' OR name LIKE \\'%John%' AND id = 5\n\n$integer = '99999999999999999999';\n$query = sprintf(\"SELECT id, email, pass, name FROM members WHERE email ='%s' AND id = %d\", $mysqli->real_escape_string($string), $integer);\n\necho $query;\n// SELECT id, email, pass, name FROM members WHERE email ='x\\' OR name LIKE \\'%John%' AND id = 2147483647\n"
},
{
"answer_id": 21179234,
"author": "Rakesh Sharma",
"author_id": 878888,
"author_profile": "https://Stackoverflow.com/users/878888",
"pm_score": 7,
"selected": false,
"text": "MySQL mysql_real_escape_string() $unsafe_variable = mysql_real_escape_string($_POST['user_input']);\n $unsafe_variable = (is_string($_POST['user_input']) ? $_POST['user_input'] : '');\n $unsafe_variable = (is_numeric($_POST['user_input']) ? $_POST['user_input'] : '');\n mysql_real_escape_string"
},
{
"answer_id": 21449836,
"author": "Chintan Gor",
"author_id": 2125924,
"author_profile": "https://Stackoverflow.com/users/2125924",
"pm_score": 7,
"selected": false,
"text": "$conn = oci_connect($username, $password, $connection_string);\n$stmt = oci_parse($conn, 'UPDATE table SET field = :xx WHERE ID = 123');\noci_bind_by_name($stmt, ':xx', $fieldval);\noci_execute($stmt);\n"
},
{
"answer_id": 21864784,
"author": "Calmarius",
"author_id": 58805,
"author_profile": "https://Stackoverflow.com/users/58805",
"pm_score": 6,
"selected": false,
"text": "function sqlvprintf($query, $args)\n{\n global $DB_LINK;\n $ctr = 0;\n ensureConnection(); // Connect to database if not connected already.\n $values = array();\n foreach ($args as $value)\n {\n if (is_string($value))\n {\n $value = \"'\" . mysqli_real_escape_string($DB_LINK, $value) . \"'\";\n }\n else if (is_null($value))\n {\n $value = 'NULL';\n }\n else if (!is_int($value) && !is_float($value))\n {\n die('Only numeric, string, array and NULL arguments allowed in a query. Argument '.($ctr+1).' is not a basic type, it\\'s type is '. gettype($value). '.');\n }\n $values[] = $value;\n $ctr++;\n }\n $query = preg_replace_callback(\n '/{(\\\\d+)}/', \n function($match) use ($values)\n {\n if (isset($values[$match[1]]))\n {\n return $values[$match[1]];\n }\n else\n {\n return $match[0];\n }\n },\n $query\n );\n return $query;\n}\n\nfunction runEscapedQuery($preparedQuery /*, ...*/)\n{\n $params = array_slice(func_get_args(), 1);\n $results = runQuery(sqlvprintf($preparedQuery, $params)); // Run query and fetch results. \n return $results;\n}\n runEscapedQuery(\"INSERT INTO Whatever (id, foo, bar) VALUES ({0}, {1}, {2})\", $numericVar, $stringVar1, $stringVar2);\n str_replace preg_replace_callback"
},
{
"answer_id": 22520937,
"author": "Thomas Ahle",
"author_id": 205521,
"author_profile": "https://Stackoverflow.com/users/205521",
"pm_score": 7,
"selected": false,
"text": "$user = ORM::for_table('user')\n->where_equal('username', 'j4mie')\n->find_one();\n\n$user->first_name = 'Jamie';\n$user->save();\n\n$tweets = ORM::for_table('tweet')\n ->select('tweet.*')\n ->join('user', array(\n 'user.id', '=', 'tweet.user_id'\n ))\n ->where_equal('user.username', 'j4mie')\n ->find_many();\n\nforeach ($tweets as $tweet) {\n echo $tweet->text;\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/60174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] |
60,204 |
<p>I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question:</p>
<p><a href="/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types">What is the best way to handle multiple permission types?</a></p>
<p>It sounds like an innovative approach, so instead of a many-to-many relationship users_to_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer</p>
<p>I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well.</p>
<p>Here is the original answer in the off chance the other question gets deleted:</p>
<p>"Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.</p>
<pre><code>[Flags]
public enum Permission
{
VIEWUSERS = 1, // 2^0 // 0000 0001
EDITUSERS = 2, // 2^1 // 0000 0010
VIEWPRODUCTS = 4, // 2^2 // 0000 0100
EDITPRODUCTS = 8, // 2^3 // 0000 1000
VIEWCLIENTS = 16, // 2^4 // 0001 0000
EDITCLIENTS = 32, // 2^5 // 0010 0000
DELETECLIENTS = 64, // 2^6 // 0100 0000
}
</code></pre>
<p>Then, you can combine several permissions using the AND bitwise operator. </p>
<p>For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3.
You can then store the permission of one user into a single column of your DataBase (in our case it would be 3).</p>
<p>Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not."</p>
|
[
{
"answer_id": 60206,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 2,
"selected": false,
"text": "EXISTS JOIN"
},
{
"answer_id": 60228,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 4,
"selected": true,
"text": "bool HasPermission(User user, Permission permission) {\n return (user.Permission & permission) != 0;\n}\n\nvoid SetPermission(User user, Permission permission) {\n user.Permission |= permission;\n}\n\nvoid ClearPermission(User user, Permission permission) {\n user.Permission &= ~permission;\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
60,208 |
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p>
<p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions in this scenario?</p>
|
[
{
"answer_id": 60211,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 12,
"selected": true,
"text": "match case def f(x):\n match x:\n case 'a':\n return 1\n case 'b':\n return 2\n case _:\n return 0 # 0 is the default case if x is not found\n match case def f(x):\n return {\n 'a': 1,\n 'b': 2,\n }[x]\n"
},
{
"answer_id": 60215,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 9,
"selected": false,
"text": "result = {\n 'a': lambda x: x * 5,\n 'b': lambda x: x + 7,\n 'c': lambda x: x - 2\n}[value](x)\n"
},
{
"answer_id": 60236,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 9,
"selected": false,
"text": "if elif else switch case default if x == 'a':\n # Do the thing\nelif x == 'b':\n # Do the other thing\nif x in 'bc':\n # Fall-through by not using elif, but now the default case includes case 'a'!\nelif x in 'xyz':\n # Do yet another thing\nelse:\n # Do the default\n break if"
},
{
"answer_id": 60243,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "class SMTP:\n def lookupMethod(self, command):\n return getattr(self, 'do_' + command.upper(), None)\n def do_HELO(self, rest):\n return 'Howdy ' + rest\n def do_QUIT(self, rest):\n return 'Bye'\n\nSMTP().lookupMethod('HELO')('foo.bar.com') # => 'Howdy foo.bar.com'\nSMTP().lookupMethod('QUIT')('') # => 'Bye'\n state_ self.state do_ do_ HELO twisted/mail/smtp.py class SMTP:\n # ...\n\n def do_UNKNOWN(self, rest):\n raise NotImplementedError, 'received unknown command'\n\n def state_COMMAND(self, line):\n line = line.strip()\n parts = line.split(None, 1)\n if parts:\n method = self.lookupMethod(parts[0]) or self.do_UNKNOWN\n if len(parts) == 2:\n return method(parts[1])\n else:\n return method('')\n else:\n raise SyntaxError, 'bad syntax'\n\nSMTP().state_COMMAND(' HELO foo.bar.com ') # => Howdy foo.bar.com\n ' HELO foo.bar.com ' 'QUIT' 'RCPT TO: foo' parts ['HELO', 'foo.bar.com'] parts[0] state_COMMAND getattr(self, 'state_' + self.mode)"
},
{
"answer_id": 102990,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 4,
"selected": false,
"text": "def f(x):\n try:\n return {\n 'a': 1,\n 'b': 2,\n }[x]\n except KeyError:\n return 'default'\n"
},
{
"answer_id": 103081,
"author": "Nick",
"author_id": 3233,
"author_profile": "https://Stackoverflow.com/users/3233",
"pm_score": 11,
"selected": false,
"text": "get(key[, default]) def f(x):\n return {\n 'a': 1,\n 'b': 2\n }.get(x, 9) # 9 will be returned default if x is not found\n"
},
{
"answer_id": 3129619,
"author": "thomasf1",
"author_id": 377671,
"author_profile": "https://Stackoverflow.com/users/377671",
"pm_score": 4,
"selected": false,
"text": "result = {\n 'a': lambda x: x * 5,\n 'b': lambda x: x + 7,\n 'c': lambda x: x - 2\n}.get(whatToUse, lambda x: x - 22)(value)\n .get('c', lambda x: x - 22)(23)\n \"lambda x: x - 2\" x=23 .get('xxx', lambda x: x - 22)(44)\n \"lambda x: x - 22\" x=44"
},
{
"answer_id": 3828986,
"author": "GeeF",
"author_id": 190001,
"author_profile": "https://Stackoverflow.com/users/190001",
"pm_score": 5,
"selected": false,
"text": "result = {\n 'a': obj.increment(x),\n 'b': obj.decrement(x)\n}.get(value, obj.default(x))\n func, args = {\n 'a' : (obj.increment, (x,)),\n 'b' : (obj.decrement, (x,)),\n}.get(value, (obj.default, (x,)))\n\nresult = func(*args)\n"
},
{
"answer_id": 4367749,
"author": "elp",
"author_id": 532453,
"author_profile": "https://Stackoverflow.com/users/532453",
"pm_score": 4,
"selected": false,
"text": "macro switch(arg1):\n while True:\n cont=False\n val=%arg1%\n socket case(arg2):\n if val==%arg2% or cont:\n cont=True\n socket\n socket else:\n socket\n break\n a=3\nswitch(a):\n case(0):\n print(\"Zero\")\n case(1):\n print(\"Smaller than 2\"):\n break\n else:\n print (\"greater than 1\")\n a=3\nwhile True:\n cont=False\n if a==0 or cont:\n cont=True\n print (\"Zero\")\n if a==1 or cont:\n cont=True\n print (\"Smaller than 2\")\n break\n print (\"greater than 1\")\n break\n"
},
{
"answer_id": 6606504,
"author": "adamh",
"author_id": 832936,
"author_profile": "https://Stackoverflow.com/users/832936",
"pm_score": 7,
"selected": false,
"text": "class switch(object):\n value = None\n def __new__(class_, value):\n class_.value = value\n return True\n\ndef case(*args):\n return any((arg == switch.value for arg in args))\n while switch(n):\n if case(0):\n print \"You typed zero.\"\n break\n if case(1, 4, 9):\n print \"n is a perfect square.\"\n break\n if case(2):\n print \"n is an even number.\"\n if case(2, 3, 5, 7):\n print \"n is a prime number.\"\n break\n if case(6, 8):\n print \"n is an even number.\"\n break\n print \"Only single-digit numbers are allowed.\"\n break\n n = 2\n#Result:\n#n is an even number.\n#n is a prime number.\nn = 11\n#Result:\n#Only single-digit numbers are allowed.\n"
},
{
"answer_id": 6606540,
"author": "John Doe",
"author_id": 832391,
"author_profile": "https://Stackoverflow.com/users/832391",
"pm_score": 6,
"selected": false,
"text": "class switch(object):\n def __init__(self, value):\n self.value = value\n self.fall = False\n\n def __iter__(self):\n \"\"\"Return the match method once, then stop\"\"\"\n yield self.match\n raise StopIteration\n \n def match(self, *args):\n \"\"\"Indicate whether or not to enter a case suite\"\"\"\n if self.fall or not args:\n return True\n elif self.value in args: # changed for v1.5, see below\n self.fall = True\n return True\n else:\n return False\n # The following example is pretty much the exact use-case of a dictionary,\n# but is included for its simplicity. Note that you can include statements\n# in each suite.\nv = 'ten'\nfor case in switch(v):\n if case('one'):\n print 1\n break\n if case('two'):\n print 2\n break\n if case('ten'):\n print 10\n break\n if case('eleven'):\n print 11\n break\n if case(): # default, could also just omit condition or 'if True'\n print \"something else!\"\n # No need to break here, it'll stop anyway\n\n# break is used here to look as much like the real thing as possible, but\n# elif is generally just as good and more concise.\n\n# Empty suites are considered syntax errors, so intentional fall-throughs\n# should contain 'pass'\nc = 'z'\nfor case in switch(c):\n if case('a'): pass # only necessary if the rest of the suite is empty\n if case('b'): pass\n # ...\n if case('y'): pass\n if case('z'):\n print \"c is lowercase!\"\n break\n if case('A'): pass\n # ...\n if case('Z'):\n print \"c is uppercase!\"\n break\n if case(): # default\n print \"I dunno what c was!\"\n\n# As suggested by Pierre Quentel, you can even expand upon the\n# functionality of the classic 'case' statement by matching multiple\n# cases in a single shot. This greatly benefits operations such as the\n# uppercase/lowercase example above:\nimport string\nc = 'A'\nfor case in switch(c):\n if case(*string.lowercase): # note the * for unpacking as arguments\n print \"c is lowercase!\"\n break\n if case(*string.uppercase):\n print \"c is uppercase!\"\n break\n if case('!', '?', '.'): # normal argument passing style also applies\n print \"c is a sentence terminator!\"\n break\n if case(): # default\n print \"I dunno what c was!\"\n with foo as case for case in foo class Switch:\n def __init__(self, value):\n self.value = value\n self._entered = False\n self._broken = False\n self._prev = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n return False # Allows a traceback to occur\n\n def __call__(self, *values):\n if self._broken:\n return False\n \n if not self._entered:\n if values and self.value not in values:\n return False\n self._entered, self._prev = True, values\n return True\n \n if self._prev is None:\n self._prev = values\n return True\n \n if self._prev != values:\n self._broken = True\n return False\n \n if self._prev == values:\n self._prev = None\n return False\n \n @property\n def default(self):\n return self()\n # Prints 'bar' then 'baz'.\nwith Switch(2) as case:\n while case(0):\n print('foo')\n while case(1, 2, 3):\n print('bar')\n while case(4, 5):\n print('baz')\n break\n while case.default:\n print('default')\n break\n"
},
{
"answer_id": 10272369,
"author": "Asher",
"author_id": 1164146,
"author_profile": "https://Stackoverflow.com/users/1164146",
"pm_score": 5,
"selected": false,
"text": "def first_case():\n print \"first\"\n\ndef second_case():\n print \"second\"\n\ndef third_case():\n print \"third\"\n\nmycase = {\n'first': first_case, #do not use ()\n'second': second_case, #do not use ()\n'third': third_case #do not use ()\n}\nmyfunc = mycase['first']\nmyfunc()\n"
},
{
"answer_id": 13239503,
"author": "emu",
"author_id": 797845,
"author_profile": "https://Stackoverflow.com/users/797845",
"pm_score": 3,
"selected": false,
"text": "def f(x):\n return 1 if x == 'a' else\\\n 2 if x in 'bcd' else\\\n 0 #default\n"
},
{
"answer_id": 14688688,
"author": "Alden",
"author_id": 585278,
"author_profile": "https://Stackoverflow.com/users/585278",
"pm_score": 2,
"selected": false,
"text": "def case(list): reduce(lambda b, f: (b | f[0], {False:(lambda:None),True:f[1]}[b | f[0]]())[0], list, False)\n\ncase([\n (False, lambda:print(5)),\n (True, lambda:print(4))\n])\n reduce(\n initializer=False,\n function=(lambda b, f:\n ( b | f[0]\n , { False: (lambda:None)\n , True : f[1]\n }[b | f[0]]()\n )[0]\n ),\n iterable=[\n (False, lambda:print(5)),\n (True, lambda:print(4))\n ]\n)\n"
},
{
"answer_id": 16964129,
"author": "Harry247",
"author_id": 2392636,
"author_profile": "https://Stackoverflow.com/users/2392636",
"pm_score": 1,
"selected": false,
"text": "cases = ['zero()', 'one()', 'two()', 'three()']\n\ndef zero():\n print \"method for 0 called...\"\ndef one():\n print \"method for 1 called...\"\ndef two():\n print \"method for 2 called...\"\ndef three():\n print \"method for 3 called...\"\n\ni = int(raw_input(\"Enter choice between 0-3 \"))\n\nif(i<=len(cases)):\n exec(cases[i])\nelse:\n print \"wrong choice\"\n"
},
{
"answer_id": 17865871,
"author": "William H. Hooper",
"author_id": 2619926,
"author_profile": "https://Stackoverflow.com/users/2619926",
"pm_score": 3,
"selected": false,
"text": "def switch1(value, options):\n if value in options:\n options[value]()\n def sample1(x):\n local = 'betty'\n switch1(x, {\n 'a': lambda: print(\"hello\"),\n 'b': lambda: (\n print(\"goodbye,\" + local),\n print(\"!\")),\n })\n def switch(value, *maps):\n options = {}\n for m in maps:\n options.update(m)\n if value in options:\n options[value]()\n elif None in options:\n options[None]()\n def sample(x):\n switch(x, {\n _: lambda: print(\"other\") \n for _ in 'cdef'\n }, {\n 'a': lambda: print(\"hello\"),\n 'b': lambda: (\n print(\"goodbye,\"),\n print(\"!\")),\n None: lambda: print(\"I dunno\")\n })\n"
},
{
"answer_id": 19335626,
"author": "JD Graham",
"author_id": 2874221,
"author_profile": "https://Stackoverflow.com/users/2874221",
"pm_score": 4,
"selected": false,
"text": "l = ['Dog', 'Cat', 'Bird', 'Bigfoot',\n 'Dragonfly', 'Snake', 'Bat', 'Loch Ness Monster']\n\nfor x in l:\n if x in ('Dog', 'Cat'):\n x += \" has four legs\"\n elif x in ('Bat', 'Bird', 'Dragonfly'):\n x += \" has wings.\"\n elif x in ('Snake',):\n x += \" has a forked tongue.\"\n else:\n x += \" is a big mystery by default.\"\n print(x)\n\nprint()\n\nfor x in range(10):\n if x in (0, 1):\n x = \"Values 0 and 1 caught here.\"\n elif x in (2,):\n x = \"Value 2 caught here.\"\n elif x in (3, 7, 8):\n x = \"Values 3, 7, 8 caught here.\"\n elif x in (4, 6):\n x = \"Values 4 and 6 caught here\"\n else:\n x = \"Values 5 and 9 caught in default.\"\n print(x)\n Dog has four legs\nCat has four legs\nBird has wings.\nBigfoot is a big mystery by default.\nDragonfly has wings.\nSnake has a forked tongue.\nBat has wings.\nLoch Ness Monster is a big mystery by default.\n\nValues 0 and 1 caught here.\nValues 0 and 1 caught here.\nValue 2 caught here.\nValues 3, 7, 8 caught here.\nValues 4 and 6 caught here\nValues 5 and 9 caught in default.\nValues 4 and 6 caught here\nValues 3, 7, 8 caught here.\nValues 3, 7, 8 caught here.\nValues 5 and 9 caught in default.\n"
},
{
"answer_id": 27212138,
"author": "guneysus",
"author_id": 1766716,
"author_profile": "https://Stackoverflow.com/users/1766716",
"pm_score": 3,
"selected": false,
"text": "x results[value](value) In [2]: result = {\n ...: 'a': lambda x: 'A',\n ...: 'b': lambda x: 'B',\n ...: 'c': lambda x: 'C'\n ...: }\n ...: result['a']('a')\n ...: \nOut[2]: 'A'\n\nIn [3]: result = {\n ...: 'a': lambda : 'A',\n ...: 'b': lambda : 'B',\n ...: 'c': lambda : 'C',\n ...: None: lambda : 'Nothing else matters'\n\n ...: }\n ...: result['a']()\n ...: \nOut[3]: 'A'\n None switch ; case else"
},
{
"answer_id": 27746465,
"author": "leo",
"author_id": 652066,
"author_profile": "https://Stackoverflow.com/users/652066",
"pm_score": 4,
"selected": false,
"text": "switch ...parameter...\ncase p1: v1; break;\ncase p2: v2; break;\ndefault: v3;\n (lambda x: v1 if p1(x) else v2 if p2(x) else v3)\n (lambda x:\n v1 if p1(x) else\n v2 if p2(x) else\n v3)\n"
},
{
"answer_id": 30012053,
"author": "Ian Bell",
"author_id": 4858820,
"author_profile": "https://Stackoverflow.com/users/4858820",
"pm_score": 6,
"selected": false,
"text": "class Switch:\n def __init__(self, value):\n self.value = value\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n return False # Allows a traceback to occur\n\n def __call__(self, *values):\n return self.value in values\n\n\nfrom datetime import datetime\n\nwith Switch(datetime.today().weekday()) as case:\n if case(0):\n # Basic usage of switch\n print(\"I hate mondays so much.\")\n # Note there is no break needed here\n elif case(1,2):\n # This switch also supports multiple conditions (in one line)\n print(\"When is the weekend going to be here?\")\n elif case(3,4):\n print(\"The weekend is near.\")\n else:\n # Default would occur here\n print(\"Let's go have fun!\") # Didn't use case for example purposes\n"
},
{
"answer_id": 30881320,
"author": "ChaimG",
"author_id": 2529619,
"author_profile": "https://Stackoverflow.com/users/2529619",
"pm_score": 8,
"selected": false,
"text": "match case switch/case match/case switch/case match something:\n case 1 | 2 | 3:\n # Match 1-3.\n case _:\n # Anything else.\n # \n # Match will throw an error if this is omitted \n # and it doesn't match any of the other patterns.\n match something:\n case str() | bytes(): \n # Match a string like object.\n case [str(), int()]:\n # Match a `str` and an `int` sequence \n # (`list` or a `tuple` but not a `set` or an iterator). \n case [_, _]:\n # Match a sequence of 2 variables.\n # To prevent a common mistake, sequence patterns don’t match strings.\n case {\"bandwidth\": 100, \"latency\": 300}:\n # Match this dict. Extra keys are ignored.\n match something:\n case [name, count]\n # Match a sequence of any two objects and parse them into the two variables.\n case [x, y, *rest]:\n # Match a sequence of two or more objects, \n # binding object #3 and on into the rest variable.\n case bytes() | str() as text:\n # Match any string like object and save it to the text variable.\n COLOR.RED match something:\n case 0 | 1 | 2:\n # Matches 0, 1 or 2 (value).\n print(\"Small number\")\n case [] | [_]:\n # Matches an empty or single value sequence (structure).\n # Matches lists and tuples but not sets.\n print(\"A short sequence\")\n case str() | bytes():\n # Something of `str` or `bytes` type (data type).\n print(\"Something string-like\")\n case _:\n # Anything not matched by the above.\n print(\"Something else\")\n choices = {'a': 1, 'b': 2}\nresult = choices.get(key, 'default')\n // C Language version of a simple 'switch/case'.\nswitch( key ) \n{\n case 'a' :\n result = 1;\n break;\n case 'b' :\n result = 2;\n break;\n default :\n result = -1;\n}\n choices = {'a': (1, 2, 3), 'b': (4, 5, 6)}\n(result1, result2, result3) = choices.get(key, ('default1', 'default2', 'default3'))\n"
},
{
"answer_id": 31995013,
"author": "user5224656",
"author_id": 5224656,
"author_profile": "https://Stackoverflow.com/users/5224656",
"pm_score": 4,
"selected": false,
"text": "# simple case alternative\n\nsome_value = 5.0\n\n# this while loop block simulates a case block\n\n# case\nwhile True:\n\n # case 1\n if some_value > 5:\n print ('Greater than five')\n break\n\n # case 2\n if some_value == 5:\n print ('Equal to five')\n break\n\n # else case 3\n print ( 'Must be less than 5')\n break\n"
},
{
"answer_id": 36079070,
"author": "J_Zar",
"author_id": 1351609,
"author_profile": "https://Stackoverflow.com/users/1351609",
"pm_score": 3,
"selected": false,
"text": "class ChoiceManager:\n\n def __init__(self):\n self.__choice_table = \\\n {\n \"CHOICE1\" : self.my_func1,\n \"CHOICE2\" : self.my_func2,\n }\n\n def my_func1(self, data):\n pass\n\n def my_func2(self, data):\n pass\n\n def process(self, case, data):\n return self.__choice_table[case](data)\n\nChoiceManager().process(\"CHOICE1\", my_data)\n class PacketManager:\n\n def __init__(self):\n self.__choice_table = \\\n {\n ControlMessage : self.my_func1,\n DiagnosticMessage : self.my_func2,\n }\n\n def my_func1(self, data):\n # process the control message here\n pass\n\n def my_func2(self, data):\n # process the diagnostic message here\n pass\n\n def process(self, pkt):\n return self.__choice_table[pkt.__class__](pkt)\n\npkt = GetMyPacketFromNet()\nPacketManager().process(pkt)\n\n\n# isolated test or isolated usage example\ndef test_control_packet():\n p = ControlMessage()\n PacketManager().my_func1(p)\n"
},
{
"answer_id": 37448954,
"author": "dccsillag",
"author_id": 4803382,
"author_profile": "https://Stackoverflow.com/users/4803382",
"pm_score": 2,
"selected": false,
"text": "exec {\n 1: \"\"\"\nprint ('one')\n\"\"\", \n 2: \"\"\"\nprint ('two')\n\"\"\", \n 3: \"\"\"\nprint ('three')\n\"\"\",\n}.get(value, \"\"\"\nprint ('None')\n\"\"\")\n value switch (value) {\n case 1:\n printf(\"one\");\n break;\n case 2:\n printf(\"two\");\n break;\n case 3:\n printf(\"three\");\n break;\n default:\n printf(\"None\");\n break;\n}\n def switch(value, cases, default):\n exec cases.get(value, default)\n switch(value, {\n 1: \"\"\"\nprint ('one')\n \"\"\", \n 2: \"\"\"\nprint ('two')\n \"\"\", \n 3: \"\"\"\nprint ('three')\n \"\"\",\n}, \"\"\"\nprint ('None')\n\"\"\")\n"
},
{
"answer_id": 43536282,
"author": "Tom",
"author_id": 3106539,
"author_profile": "https://Stackoverflow.com/users/3106539",
"pm_score": 3,
"selected": false,
"text": "def case(callable):\n \"\"\"switch-case decorator\"\"\"\n class case_class(object):\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def do_call(self):\n return callable(*self.args, **self.kwargs)\n\nreturn case_class\n\ndef switch(key, cases, default=None):\n \"\"\"switch-statement\"\"\"\n ret = None\n try:\n ret = case[key].do_call()\n except KeyError:\n if default:\n ret = default.do_call()\n finally:\n return ret\n @case @case\ndef case_1(arg1):\n print 'case_1: ', arg1\n\n@case\ndef case_2(arg1, arg2):\n print 'case_2'\n return arg1, arg2\n\n@case\ndef default_case(arg1, arg2, arg3):\n print 'default_case: ', arg1, arg2, arg3\n\nret = switch(somearg, {\n 1: case_1('somestring'),\n 2: case_2(13, 42)\n}, default_case(123, 'astring', 3.14))\n\nprint ret\n pip install NeoPySwitch\n"
},
{
"answer_id": 44545063,
"author": "Yster",
"author_id": 1317559,
"author_profile": "https://Stackoverflow.com/users/1317559",
"pm_score": 4,
"selected": false,
"text": "def numbers_to_strings(argument):\n switcher = {\n 0: \"zero\",\n 1: \"one\",\n 2: \"two\",\n }\n return switcher.get(argument, \"nothing\")\n function(argument){\n switch(argument) {\n case 0:\n return \"zero\";\n case 1:\n return \"one\";\n case 2:\n return \"two\";\n default:\n return \"nothing\";\n }\n}\n"
},
{
"answer_id": 45530307,
"author": "damirlj",
"author_id": 6424465,
"author_profile": "https://Stackoverflow.com/users/6424465",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/python\n\nimport sys\n\nclass Case(object):\n \"\"\"\n Base class which specifies the interface for the \"case\" handler.\n The all required arbitrary arguments inside \"execute\" method will be\n provided through the derived class\n specific constructor\n\n @note in Python, all class methods are virtual\n \"\"\"\n def __init__(self, id):\n self.id = id\n\n def pair(self):\n \"\"\"\n Pairs the given id of the \"case\" with\n the instance on which \"execute\" will be called\n \"\"\"\n return (self.id, self)\n\n def execute(self): # Base class virtual method that needs to be overridden\n pass\n\nclass Case1(Case):\n def __init__(self, id, msg):\n self.id = id\n self.msg = msg\n def execute(self): # Override the base class method\n print(\"<Case1> id={}, message: \\\"{}\\\"\".format(str(self.id), self.msg))\n\nclass Case2(Case):\n def __init__(self, id, n):\n self.id = id\n self.n = n\n def execute(self): # Override the base class method\n print(\"<Case2> id={}, n={}.\".format(str(self.id), str(self.n)))\n print(\"\\n\".join(map(str, range(self.n))))\n\n\nclass Switch(object):\n \"\"\"\n The class which delegates the jobs\n based on the given job id\n \"\"\"\n def __init__(self, cases):\n self.cases = cases # dictionary: time complexity for the access operation is 1\n def resolve(self, id):\n\n try:\n cases[id].execute()\n except KeyError as e:\n print(\"Given id: {} is wrong!\".format(str(id)))\n\n\n\nif __name__ == '__main__':\n\n # Cases\n cases=dict([Case1(0, \"switch\").pair(), Case2(1, 5).pair()])\n\n switch = Switch(cases)\n\n # id will be dynamically specified\n switch.resolve(0)\n switch.resolve(1)\n switch.resolve(2)\n"
},
{
"answer_id": 45683860,
"author": "user2233949",
"author_id": 2233949,
"author_profile": "https://Stackoverflow.com/users/2233949",
"pm_score": 5,
"selected": false,
"text": "if something:\n return \"first thing\"\nelif somethingelse:\n return \"second thing\"\nelif yetanotherthing:\n return \"third thing\"\nelse:\n return \"default thing\"\n"
},
{
"answer_id": 45981619,
"author": "The Nomadic Coder",
"author_id": 1933672,
"author_profile": "https://Stackoverflow.com/users/1933672",
"pm_score": 2,
"selected": false,
"text": "class SwitchCase(object):\n def __init__(self):\n self._cases = dict()\n\n def add_case(self,value, fn):\n self._cases[value] = fn\n\n def add_default_case(self,fn):\n self._cases['default'] = fn\n\n def switch_case(self,value):\n if value in self._cases.keys():\n return self._cases[value](value)\n else:\n return self._cases['default'](0)\n from switch_case import SwitchCase\nswitcher = SwitchCase()\nswitcher.add_case(1, lambda x:x+1)\nswitcher.add_case(2, lambda x:x+3)\nswitcher.add_default_case(lambda _:[1,2,3,4,5])\n\nprint switcher.switch_case(1) #2\nprint switcher.switch_case(2) #5\nprint switcher.switch_case(123) #[1, 2, 3, 4, 5]\n"
},
{
"answer_id": 47335084,
"author": "nrp",
"author_id": 3426366,
"author_profile": "https://Stackoverflow.com/users/3426366",
"pm_score": 1,
"selected": false,
"text": "def start():\n print(\"Start\")\n\ndef stop():\n print(\"Stop\")\n\ndef print_help():\n print(\"Help\")\n\ndef choose_action(arg):\n return {\n \"start\": start,\n \"stop\": stop,\n \"help\": print_help,\n }.get(arg, print_help)\n\nargument = sys.argv[1].strip()\nchoose_action(argument)() # calling a method from the given string\n"
},
{
"answer_id": 48013880,
"author": "M T Head",
"author_id": 6710305,
"author_profile": "https://Stackoverflow.com/users/6710305",
"pm_score": 1,
"selected": false,
"text": "def fnc_MonthSwitch(int_Month): #### Define a function take in the month variable \n str_Return =\"Not Found\" #### Set Default Value \n if int_Month==1: str_Return = \"Jan\" \n if int_Month==2: str_Return = \"Feb\" \n if int_Month==3: str_Return = \"Mar\" \n return str_Return; #### Return the month found \nprint (\"Month Test 3: \" + fnc_MonthSwitch( 3) )\nprint (\"Month Test 14: \" + fnc_MonthSwitch(14) )\n"
},
{
"answer_id": 48047214,
"author": "ramazan polat",
"author_id": 234775,
"author_profile": "https://Stackoverflow.com/users/234775",
"pm_score": 2,
"selected": false,
"text": "class Switch:\n def __init__(self, switches):\n self.switches = switches\n self.between = len(switches[0]) == 3\n\n def __call__(self, x):\n for line in self.switches:\n if self.between:\n if line[0] <= x < line[1]:\n return line[2]\n else:\n if line[0] == x:\n return line[1]\n return None\n\n\nif __name__ == '__main__':\n between_table = [\n (1, 4, 'between 1 and 4'),\n (4, 8, 'between 4 and 8')\n ]\n\n switch_between = Switch(between_table)\n\n print('Switch Between:')\n for i in range(0, 10):\n if switch_between(i):\n print('{} is {}'.format(i, switch_between(i)))\n else:\n print('No match for {}'.format(i))\n\n\n equals_table = [\n (1, 'One'),\n (2, 'Two'),\n (4, 'Four'),\n (5, 'Five'),\n (7, 'Seven'),\n (8, 'Eight')\n ]\n print('Switch Equals:')\n switch_equals = Switch(equals_table)\n for i in range(0, 10):\n if switch_equals(i):\n print('{} is {}'.format(i, switch_equals(i)))\n else:\n print('No match for {}'.format(i))\n Switch Between:\nNo match for 0\n1 is between 1 and 4\n2 is between 1 and 4\n3 is between 1 and 4\n4 is between 4 and 8\n5 is between 4 and 8\n6 is between 4 and 8\n7 is between 4 and 8\nNo match for 8\nNo match for 9\n\nSwitch Equals:\nNo match for 0\n1 is One\n2 is Two\nNo match for 3\n4 is Four\n5 is Five\nNo match for 6\n7 is Seven\n8 is Eight\nNo match for 9\n"
},
{
"answer_id": 48614894,
"author": "Solomon Ucko",
"author_id": 5445670,
"author_profile": "https://Stackoverflow.com/users/5445670",
"pm_score": 3,
"selected": false,
"text": "for case in [expression]:\n if case == 1:\n print(end='Was 1. ')\n\n if case == 2:\n print(end='Was 2. ')\n break\n\n if case in (1, 2):\n print(end='Was 1 or 2. ')\n\n print(end='Was something. ')\n Was 1. Was 1 or 2. Was something. expression 1 Was 2. expression 2 Was something. expression"
},
{
"answer_id": 48846312,
"author": "Alejandro Quintanar",
"author_id": 1242902,
"author_profile": "https://Stackoverflow.com/users/1242902",
"pm_score": 5,
"selected": false,
"text": "result = {\n 'case1': foo1, \n 'case2': foo2,\n 'case3': foo3,\n}.get(option)(parameters_optional)\n option = number['type']\nresult = {\n 'number': value_of_int, # result = value_of_int(number['value'])\n 'text': value_of_text, # result = value_of_text(number['value'])\n 'binary': value_of_bin, # result = value_of_bin(number['value'])\n}.get(option)(value['value'])\n option = number['type']\nresult = {\n 'number': func_for_number, # result = func_for_number()\n 'text': func_for_text, # result = func_for_text()\n 'binary': func_for_bin, # result = func_for_bin()\n}.get(option)()\n option = number['type']\nresult = {\n 'number': lambda: 10, # result = 10\n 'text': lambda: 'ten', # result = 'ten'\n 'binary': lambda: 0b101111, # result = 47\n}.get(option)()\n"
},
{
"answer_id": 49367931,
"author": "True",
"author_id": 4696698,
"author_profile": "https://Stackoverflow.com/users/4696698",
"pm_score": 2,
"selected": false,
"text": "if... elif... elif... else def function_1(...):\n ...\n\nfunctions = {'a': function_1,\n 'b': function_2,\n 'c': self.method_1, ...}\n\nfunc = functions[value]\nfunc()\n def visit_a(self, ...):\n ...\n...\n\ndef dispatch(self, value):\n method_name = 'visit_' + str(value)\n method = getattr(self, method_name)\n method()\n visit_"
},
{
"answer_id": 49746559,
"author": "abarnert",
"author_id": 908494,
"author_profile": "https://Stackoverflow.com/users/908494",
"pm_score": 4,
"selected": false,
"text": "elif dict visit_ def dispatch(self, value):\n method_name = 'visit_' + str(value)\n method = getattr(self, method_name)\n method()\n if x == 1: print('first')\nelif x == 2: print('second')\nelif x == 3: print('third')\nelse: print('did not place')\n dataclass enum elif"
},
{
"answer_id": 50686874,
"author": "abarnert",
"author_id": 908494,
"author_profile": "https://Stackoverflow.com/users/908494",
"pm_score": 2,
"selected": false,
"text": "d = {\n \"a1\": lambda: a(1),\n \"a2\": lambda: a(2),\n \"b\": lambda: b(\"foo\"),\n \"c\": lambda: c(),\n \"z\": lambda: z(\"bar\", 25),\n }\nreturn d[string]()\n d = {\n \"a1\": (a, 1),\n \"a2\": (a, 2),\n \"b\": (b, \"foo\"),\n \"c\": (c,)\n \"z\": (z, \"bar\", 25),\n }\nfunc, *args = d[string]\nreturn func(*args)\n lambda partial d = {\n \"a1\": partial(a, 1),\n \"a2\": partial(a, 2),\n \"b\": partial(b, \"foo\"),\n \"c\": c,\n \"z\": partial(z, \"bar\", 25),\n }\nreturn d[string]()\n d = {\n \"a1\": partial(a, 1),\n \"a2\": partial(a, 2),\n \"b\": partial(b, \"foo\"),\n \"c\": c,\n \"k\": partial(k, key=int),\n \"z\": partial(z, \"bar\", 25),\n }\nreturn d[string]()\n"
},
{
"answer_id": 50688208,
"author": "Alex Hall",
"author_id": 2482744,
"author_profile": "https://Stackoverflow.com/users/2482744",
"pm_score": 2,
"selected": false,
"text": "lambda partial class switch(object):\n NO_DEFAULT = object()\n\n def __init__(self, value, default=NO_DEFAULT):\n self._value = value\n self._result = default\n\n def __call__(self, option, func, *args, **kwargs):\n if self._value == option:\n self._result = func(*args, **kwargs)\n return self\n\n def pick(self):\n if self._result is switch.NO_DEFAULT:\n raise ValueError(self._value)\n\n return self._result\n def add(a, b):\n return a + b\n\ndef double(x):\n return 2 * x\n\ndef foo(**kwargs):\n return kwargs\n\nresult = (\n switch(3)\n (1, add, 7, 9)\n (2, double, 5)\n (3, foo, bar=0, spam=8)\n (4, lambda: double(1 / 0)) # if evaluating arguments is not safe\n).pick()\n\nprint(result)\n switch(3)(...)(...)(...) switch(5)(1, ...)(2, ...)(3, ...) switch(5, default=-1)... -1"
},
{
"answer_id": 50725576,
"author": "Tony Suffolk 66",
"author_id": 3426606,
"author_profile": "https://Stackoverflow.com/users/3426606",
"pm_score": 3,
"selected": false,
"text": "def decision_time( key, *args, **kwargs):\n def action1()\n \"\"\"This function is a closure - and has access to all the arguments\"\"\"\n pass\n def action2()\n \"\"\"This function is a closure - and has access to all the arguments\"\"\"\n pass\n def action3()\n \"\"\"This function is a closure - and has access to all the arguments\"\"\"\n pass\n\n return {1:action1, 2:action2, 3:action3}.get(key,default)()\n"
},
{
"answer_id": 51811745,
"author": "sudhir tataraju",
"author_id": 8520303,
"author_profile": "https://Stackoverflow.com/users/8520303",
"pm_score": 1,
"selected": false,
"text": "while True:\n try:\n x = int(input(\"Enter a numerical input: \"))\n except:\n print(\"Invalid input - please enter a Integer!\");\n if x==1:\n print(\"good\");\n elif x==2:\n print(\"bad\");\n elif x==3:\n break\n else:\n print (\"terrible\");\n"
},
{
"answer_id": 52106213,
"author": "Woody1193",
"author_id": 3121975,
"author_profile": "https://Stackoverflow.com/users/3121975",
"pm_score": 3,
"selected": false,
"text": "def ToUpper(lcChar):\n if (lcChar == 'a' or lcChar == 'A'):\n return 'A'\n elif (lcChar == 'b' or lcChar == 'B'):\n return 'B'\n ...\n elif (lcChar == 'z' or lcChar == 'Z'):\n return 'Z'\n else:\n return None # or something\n def ConvertToReason(code):\n if (code == 200):\n return 'Okay'\n elif (code == 400):\n return 'Bad Request'\n elif (code == 404):\n return 'Not Found'\n else:\n return None\n"
},
{
"answer_id": 52559968,
"author": "Vikhyat Agarwal",
"author_id": 8663663,
"author_profile": "https://Stackoverflow.com/users/8663663",
"pm_score": 4,
"selected": false,
"text": "def f(x):\n dictionary = {'a':1, 'b':2, 'c':3}\n return dictionary.get(x,'Not Found') \n##Returns the value for the letter x;returns 'Not Found' if x isn't a key in the dictionary\n"
},
{
"answer_id": 54549654,
"author": "Felix Martinez",
"author_id": 10967582,
"author_profile": "https://Stackoverflow.com/users/10967582",
"pm_score": 4,
"selected": false,
"text": "#!/usr/bin/env python\n\n\ndef case1():\n print(\"This is case 1\")\n\ndef case2():\n print(\"This is case 2\")\n\ndef case3():\n print(\"This is case 3\")\n\n\ntoken_dict = {\n \"case1\" : case1,\n \"case2\" : case2,\n \"case3\" : case3,\n}\n\n\ndef main():\n cases = (\"case1\", \"case3\", \"case2\", \"case1\")\n for case in cases:\n token_dict[case]()\n\n\nif __name__ == '__main__':\n main()\n This is case 1\nThis is case 3\nThis is case 2\nThis is case 1\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4907/"
] |
60,221 |
<p>I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:</p>
<blockquote>
<p>[======> ] 37%</p>
</blockquote>
<p>and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?</p>
|
[
{
"answer_id": 60226,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 7,
"selected": true,
"text": "curses void DrawProgressBar(int len, double percent) {\n cout << \"\\x1B[2K\"; // Erase the entire current line.\n cout << \"\\x1B[0E\"; // Move to the beginning of the current line.\n string progress;\n for (int i = 0; i < len; ++i) {\n if (i < static_cast<int>(len * percent)) {\n progress += \"=\";\n } else {\n progress += \" \";\n }\n }\n cout << \"[\" << progress << \"] \" << (static_cast<int>(100 * percent)) << \"%\";\n flush(cout); // Required.\n}\n"
},
{
"answer_id": 60227,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": false,
"text": "def status(percent):\n sys.stdout.write(\"%3d%%\\r\" % percent)\n sys.stdout.flush()\n sys.stdout.write print print flush() sys.stdout"
},
{
"answer_id": 11173569,
"author": "Blaker",
"author_id": 1048120,
"author_profile": "https://Stackoverflow.com/users/1048120",
"pm_score": 2,
"selected": false,
"text": "def status(msgs):\n assert isinstance(msgs, (list, tuple))\n\n sys.stdout.write(''.join(msg + '\\n' for msg in msgs[:-1]) + msgs[-1] + ('\\x1b[A' * (len(msgs) - 1)) + '\\r')\n sys.stdout.flush()\n"
},
{
"answer_id": 11325990,
"author": "naren",
"author_id": 1193863,
"author_profile": "https://Stackoverflow.com/users/1193863",
"pm_score": 2,
"selected": false,
"text": "def disp_status(timelapse, timeout):\n if timelapse and timeout:\n percent = 100 * (float(timelapse)/float(timeout))\n sys.stdout.write(\"progress : [\"+\"*\"*int(percent)+\" \"*(100-int(percent-1))+\"]\"+str(percent)+\" %\")\n sys.stdout.flush()\n stdout.write(\"\\r \\r\")\n"
},
{
"answer_id": 13738348,
"author": "hustljian",
"author_id": 1048072,
"author_profile": "https://Stackoverflow.com/users/1048072",
"pm_score": 2,
"selected": false,
"text": "/*\n* file: ProgressBarConsole.cpp\n* description: a console progress bar Demo\n* author: lijian <[email protected]>\n* version: 1.0\n* date: 2012-12-06\n*/\n#include <stdio.h>\n#include <windows.h>\n\nHANDLE hOut;\nCONSOLE_SCREEN_BUFFER_INFO bInfo;\nchar charProgress[80] = \n {\"================================================================\"};\nchar spaceProgress = ' ';\n\n/*\n* show a progress in the [row] line\n* row start from 0 to the end\n*/\nint ProgressBar(char *task, int row, int progress)\n{\n char str[100];\n int len, barLen,progressLen;\n COORD crStart, crCurr;\n GetConsoleScreenBufferInfo(hOut, &bInfo);\n crCurr = bInfo.dwCursorPosition; //the old position\n len = bInfo.dwMaximumWindowSize.X;\n barLen = len - 17;//minus the extra char\n progressLen = (int)((progress/100.0)*barLen);\n crStart.X = 0;\n crStart.Y = row;\n\n sprintf(str,\"%-10s[%-.*s>%*c]%3d%%\", task,progressLen,charProgress, barLen-progressLen,spaceProgress,50);\n#if 0 //use stdand libary\n SetConsoleCursorPosition(hOut, crStart);\n printf(\"%s\\n\", str);\n#else\n WriteConsoleOutputCharacter(hOut, str, len,crStart,NULL);\n#endif\n SetConsoleCursorPosition(hOut, crCurr);\n return 0;\n}\nint main(int argc, char* argv[])\n{\n int i;\n hOut = GetStdHandle(STD_OUTPUT_HANDLE);\n GetConsoleScreenBufferInfo(hOut, &bInfo);\n\n for (i=0;i<100;i++)\n {\n ProgressBar(\"test\", 0, i);\n Sleep(50);\n }\n\n return 0;\n}\n"
},
{
"answer_id": 26219138,
"author": "icenac",
"author_id": 3910576,
"author_profile": "https://Stackoverflow.com/users/3910576",
"pm_score": 5,
"selected": false,
"text": "[ ]\n \\r[= ]\n\n\\r[== ]\n\n...\n\n\\r[==========]\n \\r[done ]\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] |
60,244 |
<p>I need to join two binary files with a <code>*.bat</code> script on Windows.</p>
<p>How can I achieve that?</p>
|
[
{
"answer_id": 60248,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": false,
"text": "copy /b copy /b file1+file2 destfile\n"
},
{
"answer_id": 60249,
"author": "simon",
"author_id": 6040,
"author_profile": "https://Stackoverflow.com/users/6040",
"pm_score": 3,
"selected": false,
"text": "copy file1+file2 appendedfile\n"
},
{
"answer_id": 60254,
"author": "Nathan Jones",
"author_id": 5848,
"author_profile": "https://Stackoverflow.com/users/5848",
"pm_score": 10,
"selected": true,
"text": "type cat type file1 file2 > file3\n cat file1 file2 > file3\n type *.vcf > all_in_one.vcf \n"
},
{
"answer_id": 60257,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 4,
"selected": false,
"text": "Get-Content file1,file2\n type type file1,file2\n"
},
{
"answer_id": 23946721,
"author": "Jahmic",
"author_id": 573927,
"author_profile": "https://Stackoverflow.com/users/573927",
"pm_score": 1,
"selected": false,
"text": "echo new text >>existingFile.txt\n"
},
{
"answer_id": 26384080,
"author": "Noelkd",
"author_id": 1663352,
"author_profile": "https://Stackoverflow.com/users/1663352",
"pm_score": 0,
"selected": false,
"text": "1>2# : ^\n'''\n@echo off\npython \"%~nx0\" \" %~nx1\" \"%~nx2\" \"%~nx3\"\nexit /b\nrem ^\n'''\nimport sys\nimport os\n\nsys.argv = [argv.strip() for argv in sys.argv]\nif len(sys.argv) != 4:\n sys.exit(1)\n\n_, file_one, file_two, out_file = sys.argv\n\nfor file_name in [file_one, file_two]:\n if not os.path.isfile(file_name):\n print \"Can't find: {0}\".format(file_name)\n sys.exit(1)\n\nif os.path.isfile(out_file):\n print \"Output file exists and will be overwritten\"\n\nwith open(out_file, \"wb\") as out:\n with open(file_one, \"rb\") as f1:\n out.write(f1.read())\n\n with open(file_two, \"rb\") as f2:\n out.write(f2.read())\n join.bat file_one.bin file_two.bin out_file.bin\n"
},
{
"answer_id": 53236194,
"author": "Aaron Xu",
"author_id": 10631886,
"author_profile": "https://Stackoverflow.com/users/10631886",
"pm_score": 0,
"selected": false,
"text": "type cmd.exe type bat"
},
{
"answer_id": 54167784,
"author": "Ricky Divjakovski",
"author_id": 2884140,
"author_profile": "https://Stackoverflow.com/users/2884140",
"pm_score": 1,
"selected": false,
"text": "Usage: cat file1 file2 file3 file4 -o output.txt\n-o | Specifies the next arg is the output, we must use this rather than \">>\" to preserve the line endings\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] |
60,259 |
<p>Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding.
Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI.</p>
<p>Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source? </p>
<p>Code snippets would be great.</p>
<p>Update: To make it more clear,
Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls. </p>
|
[
{
"answer_id": 395358,
"author": "Paul Osterhout",
"author_id": 30976,
"author_profile": "https://Stackoverflow.com/users/30976",
"pm_score": 3,
"selected": true,
"text": "XmlDataProvider provider = new XmlDataProvider();\n\nif (provider != null)\n{\n System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\n doc.Load(fileName);\n provider.Document = doc;\n provider.XPath = \"/opml/body/outline\";\n FeedListTreeView.DataContext = provider;\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1747/"
] |
60,260 |
<p>I've been working through <a href="http://gigamonkeys.com/book" rel="nofollow noreferrer">Practical Common Lisp</a> and as an exercise decided to write a macro to determine if a number is a multiple of another number:</p>
<p><code>(defmacro multp (value factor)<br>
`(= (rem ,value ,factor) 0))</code></p>
<p>so that :
<code>(multp 40 10)</code>
evaluates to true whilst
<code>(multp 40 13)</code>
does not </p>
<p>The question is does this macro <a href="http://gigamonkeys.com/book/macros-defining-your-own.html#plugging-the-leaks" rel="nofollow noreferrer">leak</a> in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used?</p>
|
[
{
"answer_id": 60267,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "value factor rem (defun multp (value factor)\n (zerop (rem value factor)))\n zerop (= ... 0)"
},
{
"answer_id": 81824,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 1,
"selected": false,
"text": "(flet ((= (&rest args) nil))\n (multp 40 10))\n"
},
{
"answer_id": 268416,
"author": "Vatine",
"author_id": 34771,
"author_profile": "https://Stackoverflow.com/users/34771",
"pm_score": 0,
"selected": false,
"text": "(defmacro ana-and (&rest forms)\n (loop for form in (reverse forms)\n for completion = form then `(let ((it ,form))\n (when it\n ,completion))\n finally (return completion)))\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303/"
] |
60,269 |
<p>How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.</p>
<p><strong>EDIT</strong>: <a href="http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html" rel="noreferrer">The Java Tutorials - Drag and Drop and Data Transfer</a>.</p>
|
[
{
"answer_id": 60279,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 3,
"selected": false,
"text": "class DnDTabbedPane extends JTabbedPane {\n private static final int LINEWIDTH = 3;\n private static final String NAME = \"test\";\n private final GhostGlassPane glassPane = new GhostGlassPane();\n private final Rectangle2D lineRect = new Rectangle2D.Double();\n private final Color lineColor = new Color(0, 100, 255);\n //private final DragSource dragSource = new DragSource();\n //private final DropTarget dropTarget;\n private int dragTabIndex = -1;\n\n public DnDTabbedPane() {\n super();\n final DragSourceListener dsl = new DragSourceListener() {\n public void dragEnter(DragSourceDragEvent e) {\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n }\n public void dragExit(DragSourceEvent e) {\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);\n lineRect.setRect(0,0,0,0);\n glassPane.setPoint(new Point(-1000,-1000));\n glassPane.repaint();\n }\n public void dragOver(DragSourceDragEvent e) {\n //e.getLocation()\n //This method returns a Point indicating the cursor location in screen coordinates at the moment\n Point tabPt = e.getLocation();\n SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);\n Point glassPt = e.getLocation();\n SwingUtilities.convertPointFromScreen(glassPt, glassPane);\n int targetIdx = getTargetTabIndex(glassPt);\n if(getTabAreaBound().contains(tabPt) && targetIdx>=0 &&\n targetIdx!=dragTabIndex && targetIdx!=dragTabIndex+1) {\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n }else{\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);\n }\n }\n public void dragDropEnd(DragSourceDropEvent e) {\n lineRect.setRect(0,0,0,0);\n dragTabIndex = -1;\n if(hasGhost()) {\n glassPane.setVisible(false);\n glassPane.setImage(null);\n }\n }\n public void dropActionChanged(DragSourceDragEvent e) {}\n };\n final Transferable t = new Transferable() {\n private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);\n public Object getTransferData(DataFlavor flavor) {\n return DnDTabbedPane.this;\n }\n public DataFlavor[] getTransferDataFlavors() {\n DataFlavor[] f = new DataFlavor[1];\n f[0] = this.FLAVOR;\n return f;\n }\n public boolean isDataFlavorSupported(DataFlavor flavor) {\n return flavor.getHumanPresentableName().equals(NAME);\n }\n };\n final DragGestureListener dgl = new DragGestureListener() {\n public void dragGestureRecognized(DragGestureEvent e) {\n Point tabPt = e.getDragOrigin();\n dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);\n if(dragTabIndex<0) return;\n initGlassPane(e.getComponent(), e.getDragOrigin());\n try{\n e.startDrag(DragSource.DefaultMoveDrop, t, dsl);\n }catch(InvalidDnDOperationException idoe) {\n idoe.printStackTrace();\n }\n }\n };\n //dropTarget =\n new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true);\n new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);\n }\n\n class CDropTargetListener implements DropTargetListener{\n public void dragEnter(DropTargetDragEvent e) {\n if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction());\n else e.rejectDrag();\n }\n public void dragExit(DropTargetEvent e) {}\n public void dropActionChanged(DropTargetDragEvent e) {}\n public void dragOver(final DropTargetDragEvent e) {\n if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) {\n initTargetLeftRightLine(getTargetTabIndex(e.getLocation()));\n }else{\n initTargetTopBottomLine(getTargetTabIndex(e.getLocation()));\n }\n repaint();\n if(hasGhost()) {\n glassPane.setPoint(e.getLocation());\n glassPane.repaint();\n }\n }\n\n public void drop(DropTargetDropEvent e) {\n if(isDropAcceptable(e)) {\n convertTab(dragTabIndex, getTargetTabIndex(e.getLocation()));\n e.dropComplete(true);\n }else{\n e.dropComplete(false);\n }\n repaint();\n }\n public boolean isDragAcceptable(DropTargetDragEvent e) {\n Transferable t = e.getTransferable();\n if(t==null) return false;\n DataFlavor[] f = e.getCurrentDataFlavors();\n if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {\n return true;\n }\n return false;\n }\n public boolean isDropAcceptable(DropTargetDropEvent e) {\n Transferable t = e.getTransferable();\n if(t==null) return false;\n DataFlavor[] f = t.getTransferDataFlavors();\n if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {\n return true;\n }\n return false;\n }\n }\n\n private boolean hasGhost = true;\n public void setPaintGhost(boolean flag) {\n hasGhost = flag;\n }\n public boolean hasGhost() {\n return hasGhost;\n }\n private int getTargetTabIndex(Point glassPt) {\n Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);\n boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM;\n for(int i=0;i<getTabCount();i++) {\n Rectangle r = getBoundsAt(i);\n if(isTB) r.setRect(r.x-r.width/2, r.y, r.width, r.height);\n else r.setRect(r.x, r.y-r.height/2, r.width, r.height);\n if(r.contains(tabPt)) return i;\n }\n Rectangle r = getBoundsAt(getTabCount()-1);\n if(isTB) r.setRect(r.x+r.width/2, r.y, r.width, r.height);\n else r.setRect(r.x, r.y+r.height/2, r.width, r.height);\n return r.contains(tabPt)?getTabCount():-1;\n }\n private void convertTab(int prev, int next) {\n if(next<0 || prev==next) {\n //System.out.println(\"press=\"+prev+\" next=\"+next);\n return;\n }\n Component cmp = getComponentAt(prev);\n String str = getTitleAt(prev);\n if(next==getTabCount()) {\n //System.out.println(\"last: press=\"+prev+\" next=\"+next);\n remove(prev);\n addTab(str, cmp);\n setSelectedIndex(getTabCount()-1);\n }else if(prev>next) {\n //System.out.println(\" >: press=\"+prev+\" next=\"+next);\n remove(prev);\n insertTab(str, null, cmp, null, next);\n setSelectedIndex(next);\n }else{\n //System.out.println(\" <: press=\"+prev+\" next=\"+next);\n remove(prev);\n insertTab(str, null, cmp, null, next-1);\n setSelectedIndex(next-1);\n }\n }\n\n private void initTargetLeftRightLine(int next) {\n if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {\n lineRect.setRect(0,0,0,0);\n }else if(next==getTabCount()) {\n Rectangle rect = getBoundsAt(getTabCount()-1);\n lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n }else if(next==0) {\n Rectangle rect = getBoundsAt(0);\n lineRect.setRect(-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n }else{\n Rectangle rect = getBoundsAt(next-1);\n lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n }\n }\n private void initTargetTopBottomLine(int next) {\n if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {\n lineRect.setRect(0,0,0,0);\n }else if(next==getTabCount()) {\n Rectangle rect = getBoundsAt(getTabCount()-1);\n lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);\n }else if(next==0) {\n Rectangle rect = getBoundsAt(0);\n lineRect.setRect(rect.x,-LINEWIDTH/2,rect.width,LINEWIDTH);\n }else{\n Rectangle rect = getBoundsAt(next-1);\n lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);\n }\n }\n\n private void initGlassPane(Component c, Point tabPt) {\n //Point p = (Point) pt.clone();\n getRootPane().setGlassPane(glassPane);\n if(hasGhost()) {\n Rectangle rect = getBoundsAt(dragTabIndex);\n BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);\n Graphics g = image.getGraphics();\n c.paint(g);\n image = image.getSubimage(rect.x,rect.y,rect.width,rect.height);\n glassPane.setImage(image);\n }\n Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane);\n glassPane.setPoint(glassPt);\n glassPane.setVisible(true);\n }\n\n private Rectangle getTabAreaBound() {\n Rectangle lastTab = getUI().getTabBounds(this, getTabCount()-1);\n return new Rectangle(0,0,getWidth(),lastTab.y+lastTab.height);\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n if(dragTabIndex>=0) {\n Graphics2D g2 = (Graphics2D)g;\n g2.setPaint(lineColor);\n g2.fill(lineRect);\n }\n }\n}\n\nclass GhostGlassPane extends JPanel {\n private final AlphaComposite composite;\n private Point location = new Point(0, 0);\n private BufferedImage draggingGhost = null;\n public GhostGlassPane() {\n setOpaque(false);\n composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);\n }\n public void setImage(BufferedImage draggingGhost) {\n this.draggingGhost = draggingGhost;\n }\n public void setPoint(Point location) {\n this.location = location;\n }\n public void paintComponent(Graphics g) {\n if(draggingGhost == null) return;\n Graphics2D g2 = (Graphics2D) g;\n g2.setComposite(composite);\n double xx = location.getX() - (draggingGhost.getWidth(this) /2d);\n double yy = location.getY() - (draggingGhost.getHeight(this)/2d);\n g2.drawImage(draggingGhost, (int)xx, (int)yy , null);\n }\n}\n"
},
{
"answer_id": 60306,
"author": "Tom Martin",
"author_id": 5303,
"author_profile": "https://Stackoverflow.com/users/5303",
"pm_score": 5,
"selected": false,
"text": "import java.awt.Component;\nimport java.awt.Graphics;\nimport java.awt.Image;\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseMotionAdapter;\nimport java.awt.image.BufferedImage;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JTabbedPane;\n\n\npublic class DraggableTabbedPane extends JTabbedPane {\n\n private boolean dragging = false;\n private Image tabImage = null;\n private Point currentMouseLocation = null;\n private int draggedTabIndex = 0;\n\n public DraggableTabbedPane() {\n super();\n addMouseMotionListener(new MouseMotionAdapter() {\n public void mouseDragged(MouseEvent e) {\n\n if(!dragging) {\n // Gets the tab index based on the mouse position\n int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY());\n\n if(tabNumber >= 0) {\n draggedTabIndex = tabNumber;\n Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber);\n\n\n // Paint the tabbed pane to a buffer\n Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);\n Graphics totalGraphics = totalImage.getGraphics();\n totalGraphics.setClip(bounds);\n // Don't be double buffered when painting to a static image.\n setDoubleBuffered(false);\n paintComponent(totalGraphics);\n\n // Paint just the dragged tab to the buffer\n tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);\n Graphics graphics = tabImage.getGraphics();\n graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this);\n\n dragging = true;\n repaint();\n }\n } else {\n currentMouseLocation = e.getPoint();\n\n // Need to repaint\n repaint();\n }\n\n super.mouseDragged(e);\n }\n });\n\n addMouseListener(new MouseAdapter() {\n public void mouseReleased(MouseEvent e) {\n\n if(dragging) {\n int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10);\n\n if(tabNumber >= 0) {\n Component comp = getComponentAt(draggedTabIndex);\n String title = getTitleAt(draggedTabIndex);\n removeTabAt(draggedTabIndex);\n insertTab(title, null, comp, null, tabNumber);\n }\n }\n\n dragging = false;\n tabImage = null;\n }\n });\n }\n\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n\n // Are we dragging?\n if(dragging && currentMouseLocation != null && tabImage != null) {\n // Draw the dragged tab\n g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this);\n }\n }\n\n public static void main(String[] args) {\n JFrame test = new JFrame(\"Tab test\");\n test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n test.setSize(400, 400);\n\n DraggableTabbedPane tabs = new DraggableTabbedPane();\n tabs.addTab(\"One\", new JButton(\"One\"));\n tabs.addTab(\"Two\", new JButton(\"Two\"));\n tabs.addTab(\"Three\", new JButton(\"Three\"));\n tabs.addTab(\"Four\", new JButton(\"Four\"));\n\n test.add(tabs);\n test.setVisible(true);\n }\n}\n"
},
{
"answer_id": 61982,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 5,
"selected": true,
"text": "setAcceptor(TabAcceptor a_acceptor) true /** Modified DnDTabbedPane.java\n * http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html\n * originally written by Terai Atsuhiro.\n * so that tabs can be transfered from one pane to another.\n * eed3si9n.\n */\n\nimport java.awt.*;\nimport java.awt.datatransfer.*;\nimport java.awt.dnd.*;\nimport java.awt.geom.*;\nimport java.awt.image.*;\nimport javax.swing.*;\n\npublic class DnDTabbedPane extends JTabbedPane {\n public static final long serialVersionUID = 1L;\n private static final int LINEWIDTH = 3;\n private static final String NAME = \"TabTransferData\";\n private final DataFlavor FLAVOR = new DataFlavor(\n DataFlavor.javaJVMLocalObjectMimeType, NAME);\n private static GhostGlassPane s_glassPane = new GhostGlassPane();\n\n private boolean m_isDrawRect = false;\n private final Rectangle2D m_lineRect = new Rectangle2D.Double();\n\n private final Color m_lineColor = new Color(0, 100, 255);\n private TabAcceptor m_acceptor = null;\n\n public DnDTabbedPane() {\n super();\n final DragSourceListener dsl = new DragSourceListener() {\n public void dragEnter(DragSourceDragEvent e) {\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n }\n\n public void dragExit(DragSourceEvent e) {\n e.getDragSourceContext()\n .setCursor(DragSource.DefaultMoveNoDrop);\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n s_glassPane.setPoint(new Point(-1000, -1000));\n s_glassPane.repaint();\n }\n\n public void dragOver(DragSourceDragEvent e) {\n //e.getLocation()\n //This method returns a Point indicating the cursor location in screen coordinates at the moment\n\n TabTransferData data = getTabTransferData(e);\n if (data == null) {\n e.getDragSourceContext().setCursor(\n DragSource.DefaultMoveNoDrop);\n return;\n } // if\n\n /*\n Point tabPt = e.getLocation();\n SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);\n if (DnDTabbedPane.this.contains(tabPt)) {\n int targetIdx = getTargetTabIndex(tabPt);\n int sourceIndex = data.getTabIndex();\n if (getTabAreaBound().contains(tabPt)\n && (targetIdx >= 0)\n && (targetIdx != sourceIndex)\n && (targetIdx != sourceIndex + 1)) {\n e.getDragSourceContext().setCursor(\n DragSource.DefaultMoveDrop);\n\n return;\n } // if\n\n e.getDragSourceContext().setCursor(\n DragSource.DefaultMoveNoDrop);\n return;\n } // if\n */\n\n e.getDragSourceContext().setCursor(\n DragSource.DefaultMoveDrop);\n }\n\n public void dragDropEnd(DragSourceDropEvent e) {\n m_isDrawRect = false;\n m_lineRect.setRect(0, 0, 0, 0);\n // m_dragTabIndex = -1;\n\n if (hasGhost()) {\n s_glassPane.setVisible(false);\n s_glassPane.setImage(null);\n }\n }\n\n public void dropActionChanged(DragSourceDragEvent e) {\n }\n };\n\n final DragGestureListener dgl = new DragGestureListener() {\n public void dragGestureRecognized(DragGestureEvent e) {\n // System.out.println(\"dragGestureRecognized\");\n\n Point tabPt = e.getDragOrigin();\n int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);\n if (dragTabIndex < 0) {\n return;\n } // if\n\n initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);\n try {\n e.startDrag(DragSource.DefaultMoveDrop, \n new TabTransferable(DnDTabbedPane.this, dragTabIndex), dsl);\n } catch (InvalidDnDOperationException idoe) {\n idoe.printStackTrace();\n }\n }\n };\n\n //dropTarget =\n new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,\n new CDropTargetListener(), true);\n new DragSource().createDefaultDragGestureRecognizer(this,\n DnDConstants.ACTION_COPY_OR_MOVE, dgl);\n m_acceptor = new TabAcceptor() {\n public boolean isDropAcceptable(DnDTabbedPane a_component, int a_index) {\n return true;\n }\n };\n }\n\n public TabAcceptor getAcceptor() {\n return m_acceptor;\n }\n\n public void setAcceptor(TabAcceptor a_value) {\n m_acceptor = a_value;\n }\n\n private TabTransferData getTabTransferData(DropTargetDropEvent a_event) { \n try {\n TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR); \n return data;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n private TabTransferData getTabTransferData(DropTargetDragEvent a_event) {\n try {\n TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR); \n return data;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {\n try {\n TabTransferData data = (TabTransferData) a_event.getDragSourceContext()\n .getTransferable().getTransferData(FLAVOR); \n return data;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null; \n }\n\n class TabTransferable implements Transferable {\n private TabTransferData m_data = null;\n\n public TabTransferable(DnDTabbedPane a_tabbedPane, int a_tabIndex) {\n m_data = new TabTransferData(DnDTabbedPane.this, a_tabIndex);\n }\n\n public Object getTransferData(DataFlavor flavor) {\n return m_data;\n // return DnDTabbedPane.this;\n }\n\n public DataFlavor[] getTransferDataFlavors() {\n DataFlavor[] f = new DataFlavor[1];\n f[0] = FLAVOR;\n return f;\n }\n\n public boolean isDataFlavorSupported(DataFlavor flavor) {\n return flavor.getHumanPresentableName().equals(NAME);\n } \n }\n\n class TabTransferData {\n private DnDTabbedPane m_tabbedPane = null;\n private int m_tabIndex = -1;\n\n public TabTransferData() {\n }\n\n public TabTransferData(DnDTabbedPane a_tabbedPane, int a_tabIndex) {\n m_tabbedPane = a_tabbedPane;\n m_tabIndex = a_tabIndex;\n }\n\n public DnDTabbedPane getTabbedPane() {\n return m_tabbedPane;\n }\n\n public void setTabbedPane(DnDTabbedPane pane) {\n m_tabbedPane = pane;\n }\n\n public int getTabIndex() {\n return m_tabIndex;\n }\n\n public void setTabIndex(int index) {\n m_tabIndex = index;\n }\n }\n\n private Point buildGhostLocation(Point a_location) {\n Point retval = new Point(a_location);\n\n switch (getTabPlacement()) {\n case JTabbedPane.TOP: {\n retval.y = 1;\n retval.x -= s_glassPane.getGhostWidth() / 2;\n } break;\n\n case JTabbedPane.BOTTOM: {\n retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();\n retval.x -= s_glassPane.getGhostWidth() / 2;\n } break;\n\n case JTabbedPane.LEFT: {\n retval.x = 1;\n retval.y -= s_glassPane.getGhostHeight() / 2;\n } break;\n\n case JTabbedPane.RIGHT: {\n retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();\n retval.y -= s_glassPane.getGhostHeight() / 2;\n } break;\n } // switch\n\n retval = SwingUtilities.convertPoint(DnDTabbedPane.this,\n retval, s_glassPane);\n return retval;\n }\n\n class CDropTargetListener implements DropTargetListener {\n public void dragEnter(DropTargetDragEvent e) {\n // System.out.println(\"DropTarget.dragEnter: \" + DnDTabbedPane.this);\n\n if (isDragAcceptable(e)) {\n e.acceptDrag(e.getDropAction());\n } else {\n e.rejectDrag();\n } // if\n }\n\n public void dragExit(DropTargetEvent e) {\n // System.out.println(\"DropTarget.dragExit: \" + DnDTabbedPane.this);\n m_isDrawRect = false;\n }\n\n public void dropActionChanged(DropTargetDragEvent e) {\n }\n\n public void dragOver(final DropTargetDragEvent e) {\n TabTransferData data = getTabTransferData(e);\n\n if (getTabPlacement() == JTabbedPane.TOP\n || getTabPlacement() == JTabbedPane.BOTTOM) {\n initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data);\n } else {\n initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data);\n } // if-else\n\n repaint();\n if (hasGhost()) {\n s_glassPane.setPoint(buildGhostLocation(e.getLocation()));\n s_glassPane.repaint();\n }\n }\n\n public void drop(DropTargetDropEvent a_event) {\n // System.out.println(\"DropTarget.drop: \" + DnDTabbedPane.this);\n\n if (isDropAcceptable(a_event)) {\n convertTab(getTabTransferData(a_event),\n getTargetTabIndex(a_event.getLocation()));\n a_event.dropComplete(true);\n } else {\n a_event.dropComplete(false);\n } // if-else\n\n m_isDrawRect = false;\n repaint();\n }\n\n public boolean isDragAcceptable(DropTargetDragEvent e) {\n Transferable t = e.getTransferable();\n if (t == null) {\n return false;\n } // if\n\n DataFlavor[] flavor = e.getCurrentDataFlavors();\n if (!t.isDataFlavorSupported(flavor[0])) {\n return false;\n } // if\n\n TabTransferData data = getTabTransferData(e);\n\n if (DnDTabbedPane.this == data.getTabbedPane()\n && data.getTabIndex() >= 0) {\n return true;\n } // if\n\n if (DnDTabbedPane.this != data.getTabbedPane()) {\n if (m_acceptor != null) {\n return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());\n } // if\n } // if\n\n return false;\n }\n\n public boolean isDropAcceptable(DropTargetDropEvent e) {\n Transferable t = e.getTransferable();\n if (t == null) {\n return false;\n } // if\n\n DataFlavor[] flavor = e.getCurrentDataFlavors();\n if (!t.isDataFlavorSupported(flavor[0])) {\n return false;\n } // if\n\n TabTransferData data = getTabTransferData(e);\n\n if (DnDTabbedPane.this == data.getTabbedPane()\n && data.getTabIndex() >= 0) {\n return true;\n } // if\n\n if (DnDTabbedPane.this != data.getTabbedPane()) {\n if (m_acceptor != null) {\n return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());\n } // if\n } // if\n\n return false;\n }\n }\n\n private boolean m_hasGhost = true;\n\n public void setPaintGhost(boolean flag) {\n m_hasGhost = flag;\n }\n\n public boolean hasGhost() {\n return m_hasGhost;\n }\n\n /**\n * returns potential index for drop.\n * @param a_point point given in the drop site component's coordinate\n * @return returns potential index for drop.\n */\n private int getTargetTabIndex(Point a_point) {\n boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP\n || getTabPlacement() == JTabbedPane.BOTTOM;\n\n // if the pane is empty, the target index is always zero.\n if (getTabCount() == 0) {\n return 0;\n } // if\n\n for (int i = 0; i < getTabCount(); i++) {\n Rectangle r = getBoundsAt(i);\n if (isTopOrBottom) {\n r.setRect(r.x - r.width / 2, r.y, r.width, r.height);\n } else {\n r.setRect(r.x, r.y - r.height / 2, r.width, r.height);\n } // if-else\n\n if (r.contains(a_point)) {\n return i;\n } // if\n } // for\n\n Rectangle r = getBoundsAt(getTabCount() - 1);\n if (isTopOrBottom) {\n int x = r.x + r.width / 2;\n r.setRect(x, r.y, getWidth() - x, r.height);\n } else {\n int y = r.y + r.height / 2;\n r.setRect(r.x, y, r.width, getHeight() - y);\n } // if-else\n\n return r.contains(a_point) ? getTabCount() : -1;\n }\n\n private void convertTab(TabTransferData a_data, int a_targetIndex) {\n DnDTabbedPane source = a_data.getTabbedPane();\n int sourceIndex = a_data.getTabIndex();\n if (sourceIndex < 0) {\n return;\n } // if\n\n Component cmp = source.getComponentAt(sourceIndex);\n String str = source.getTitleAt(sourceIndex);\n if (this != source) {\n source.remove(sourceIndex);\n\n if (a_targetIndex == getTabCount()) {\n addTab(str, cmp);\n } else {\n if (a_targetIndex < 0) {\n a_targetIndex = 0;\n } // if\n\n insertTab(str, null, cmp, null, a_targetIndex);\n\n } // if\n\n setSelectedComponent(cmp);\n // System.out.println(\"press=\"+sourceIndex+\" next=\"+a_targetIndex);\n return;\n } // if\n\n if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {\n //System.out.println(\"press=\"+prev+\" next=\"+next);\n return;\n } // if\n\n if (a_targetIndex == getTabCount()) {\n //System.out.println(\"last: press=\"+prev+\" next=\"+next);\n source.remove(sourceIndex);\n addTab(str, cmp);\n setSelectedIndex(getTabCount() - 1);\n } else if (sourceIndex > a_targetIndex) {\n //System.out.println(\" >: press=\"+prev+\" next=\"+next);\n source.remove(sourceIndex);\n insertTab(str, null, cmp, null, a_targetIndex);\n setSelectedIndex(a_targetIndex);\n } else {\n //System.out.println(\" <: press=\"+prev+\" next=\"+next);\n source.remove(sourceIndex);\n insertTab(str, null, cmp, null, a_targetIndex - 1);\n setSelectedIndex(a_targetIndex - 1);\n }\n }\n\n private void initTargetLeftRightLine(int next, TabTransferData a_data) { \n if (next < 0) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n return;\n } // if\n\n if ((a_data.getTabbedPane() == this)\n && (a_data.getTabIndex() == next\n || next - a_data.getTabIndex() == 1)) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n } else if (getTabCount() == 0) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n return;\n } else if (next == 0) {\n Rectangle rect = getBoundsAt(0);\n m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);\n m_isDrawRect = true;\n } else if (next == getTabCount()) {\n Rectangle rect = getBoundsAt(getTabCount() - 1);\n m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,\n LINEWIDTH, rect.height);\n m_isDrawRect = true;\n } else {\n Rectangle rect = getBoundsAt(next - 1);\n m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,\n LINEWIDTH, rect.height);\n m_isDrawRect = true;\n }\n }\n\n private void initTargetTopBottomLine(int next, TabTransferData a_data) {\n if (next < 0) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n return;\n } // if\n\n if ((a_data.getTabbedPane() == this)\n && (a_data.getTabIndex() == next\n || next - a_data.getTabIndex() == 1)) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n } else if (getTabCount() == 0) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n return;\n } else if (next == getTabCount()) {\n Rectangle rect = getBoundsAt(getTabCount() - 1);\n m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,\n rect.width, LINEWIDTH);\n m_isDrawRect = true;\n } else if (next == 0) {\n Rectangle rect = getBoundsAt(0);\n m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);\n m_isDrawRect = true;\n } else {\n Rectangle rect = getBoundsAt(next - 1);\n m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,\n rect.width, LINEWIDTH);\n m_isDrawRect = true;\n }\n }\n\n private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {\n //Point p = (Point) pt.clone();\n getRootPane().setGlassPane(s_glassPane);\n if (hasGhost()) {\n Rectangle rect = getBoundsAt(a_tabIndex);\n BufferedImage image = new BufferedImage(c.getWidth(),\n c.getHeight(), BufferedImage.TYPE_INT_ARGB);\n Graphics g = image.getGraphics();\n c.paint(g);\n image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);\n s_glassPane.setImage(image); \n } // if\n\n s_glassPane.setPoint(buildGhostLocation(tabPt));\n s_glassPane.setVisible(true);\n }\n\n private Rectangle getTabAreaBound() {\n Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);\n return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n\n if (m_isDrawRect) {\n Graphics2D g2 = (Graphics2D) g;\n g2.setPaint(m_lineColor);\n g2.fill(m_lineRect);\n } // if\n }\n\n public interface TabAcceptor {\n boolean isDropAcceptable(DnDTabbedPane a_component, int a_index);\n }\n}\n\nclass GhostGlassPane extends JPanel {\n public static final long serialVersionUID = 1L;\n private final AlphaComposite m_composite;\n\n private Point m_location = new Point(0, 0);\n\n private BufferedImage m_draggingGhost = null;\n\n public GhostGlassPane() {\n setOpaque(false);\n m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);\n }\n\n public void setImage(BufferedImage draggingGhost) {\n m_draggingGhost = draggingGhost;\n }\n\n public void setPoint(Point a_location) {\n m_location.x = a_location.x;\n m_location.y = a_location.y;\n }\n\n public int getGhostWidth() {\n if (m_draggingGhost == null) {\n return 0;\n } // if\n\n return m_draggingGhost.getWidth(this);\n }\n\n public int getGhostHeight() {\n if (m_draggingGhost == null) {\n return 0;\n } // if\n\n return m_draggingGhost.getHeight(this);\n }\n\n public void paintComponent(Graphics g) {\n if (m_draggingGhost == null) {\n return;\n } // if \n\n Graphics2D g2 = (Graphics2D) g;\n g2.setComposite(m_composite);\n\n g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null);\n }\n}\n"
},
{
"answer_id": 8610017,
"author": "Jay Warrick",
"author_id": 1112480,
"author_profile": "https://Stackoverflow.com/users/1112480",
"pm_score": 3,
"selected": false,
"text": " private void convertTab(TabTransferData a_data, int a_targetIndex) {\n\n DnDTabbedPane source = a_data.getTabbedPane();\n System.out.println(\"this=source? \" + (this == source));\n int sourceIndex = a_data.getTabIndex();\n if (sourceIndex < 0) {\n return;\n } // if\n //Save the tab's component, title, and TabComponent.\n Component cmp = source.getComponentAt(sourceIndex);\n String str = source.getTitleAt(sourceIndex);\n Component tcmp = source.getTabComponentAt(sourceIndex);\n\n if (this != source) {\n source.remove(sourceIndex);\n\n if (a_targetIndex == getTabCount()) {\n addTab(str, cmp);\n setTabComponentAt(getTabCount()-1, tcmp);\n } else {\n if (a_targetIndex < 0) {\n a_targetIndex = 0;\n } // if\n\n insertTab(str, null, cmp, null, a_targetIndex);\n setTabComponentAt(a_targetIndex, tcmp);\n } // if\n\n setSelectedComponent(cmp);\n return;\n } // if\n if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {\n return;\n } // if\n if (a_targetIndex == getTabCount()) { \n source.remove(sourceIndex);\n addTab(str, cmp);\n setTabComponentAt(getTabCount() - 1, tcmp);\n setSelectedIndex(getTabCount() - 1);\n } else if (sourceIndex > a_targetIndex) {\n source.remove(sourceIndex);\n insertTab(str, null, cmp, null, a_targetIndex);\n setTabComponentAt(a_targetIndex, tcmp);\n setSelectedIndex(a_targetIndex);\n } else {\n source.remove(sourceIndex);\n insertTab(str, null, cmp, null, a_targetIndex - 1);\n setTabComponentAt(a_targetIndex - 1, tcmp);\n setSelectedIndex(a_targetIndex - 1);\n }\n\n }\n"
},
{
"answer_id": 20433634,
"author": "Pascal",
"author_id": 3076046,
"author_profile": "https://Stackoverflow.com/users/3076046",
"pm_score": 2,
"selected": false,
"text": "boolean transferDataFlavorFound = false;\nfor (DataFlavor transferDataFlavor : t.getTransferDataFlavors()) {\n if (FLAVOR.equals(transferDataFlavor)) {\n transferDataFlavorFound = true;\n break;\n }\n}\nif (transferDataFlavorFound == false) {\n return false;\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] |
60,271 |
<p>What is the best way to write a Safari extension? I've written a couple XUL extensions for Firefox, and now I'd like to write versions of them for Safari. Is there a way that would allow you to add buttons or forms to the browser UI, since this is not possible with an Input manager or Service menu?</p>
|
[
{
"answer_id": 1256724,
"author": "Quinn Taylor",
"author_id": 120292,
"author_profile": "https://Stackoverflow.com/users/120292",
"pm_score": 3,
"selected": false,
"text": "/Library/Internet Plug-ins/"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4939/"
] |
60,278 |
<p>In all the Git tutorials I've read they say that you can do:</p>
<pre><code>git init
git add .
git commit
</code></pre>
<p>When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.</p>
|
[
{
"answer_id": 60283,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 3,
"selected": false,
"text": "git commit EDITOR"
},
{
"answer_id": 60284,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "-m git commit -m \"my first commit\"\n"
},
{
"answer_id": 60311,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 6,
"selected": false,
"text": "-m \"...\" EDITOR ~/.gitconfig [core]\n editor = emacs\n excludesfile = /Users/will/.gitignore\n ~/.gitignore"
},
{
"answer_id": 60320,
"author": "Tom Martin",
"author_id": 5303,
"author_profile": "https://Stackoverflow.com/users/5303",
"pm_score": 1,
"selected": false,
"text": "nano git diff --name-only\n"
},
{
"answer_id": 532094,
"author": "vikhyat",
"author_id": 257349,
"author_profile": "https://Stackoverflow.com/users/257349",
"pm_score": 7,
"selected": false,
"text": "git config --global core.editor \"nano\"\n"
},
{
"answer_id": 1077672,
"author": "PHLAK",
"author_id": 27025,
"author_profile": "https://Stackoverflow.com/users/27025",
"pm_score": 0,
"selected": false,
"text": "git commit -a -m \"Type your commit message here...\"\n"
},
{
"answer_id": 1385246,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "git config --global core.editor \"bbedit -w\"\n"
},
{
"answer_id": 5747603,
"author": "MatthiasS",
"author_id": 163725,
"author_profile": "https://Stackoverflow.com/users/163725",
"pm_score": 4,
"selected": false,
"text": ":x\n"
},
{
"answer_id": 10051167,
"author": "JiuJitsuCoder",
"author_id": 1318525,
"author_profile": "https://Stackoverflow.com/users/1318525",
"pm_score": 2,
"selected": false,
"text": "git config --global core.editor \"open -t -W\" git config --global core.editor \"open -e -W\""
},
{
"answer_id": 15530614,
"author": "nothankyou",
"author_id": 1388224,
"author_profile": "https://Stackoverflow.com/users/1388224",
"pm_score": 3,
"selected": false,
"text": "# Gitignore index.pyc\n\nIgnore gunicorn generated binary file\n# Please enter the commit message for your changes. Lines starting\n# with '#' will be ignored, and an empty message aborts the commit.\n# On branch dev\n# Your branch is ahead of 'origin/dev' by 10 commits.\n# (use \"git push\" to publish your local commits)\n#\n# Changes to be committed:\n# (use \"git reset HEAD <file>...\" to unstage)\n#\n# modified: .gitignore\n#\n git config --global core.editor \"vim\"\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
60,285 |
<p>If it's possible, I'm interested in being able to embed a PostgreSQL database, similar to <a href="http://www.sqlite.org/" rel="noreferrer">sqllite</a>. I've read that it's <a href="http://bytes.com/forum/thread647637.html" rel="noreferrer">not possible</a>. I'm no database expert though, so I want to hear from you.</p>
<p>Essentially I want PostgreSQL without all the configuration and installation. If it's possible, tell me how.</p>
|
[
{
"answer_id": 69473393,
"author": "elikesprogramming",
"author_id": 5141196,
"author_profile": "https://Stackoverflow.com/users/5141196",
"pm_score": 0,
"selected": false,
"text": "R duckdb"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525/"
] |
60,290 |
<p>Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?</p>
|
[
{
"answer_id": 60295,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": true,
"text": "<img src=\"image.png\" style=\"opacity: 0.5; filter: alpha(opacity=50)\" />\n"
},
{
"answer_id": 60322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "background-position #test {\n display: block;\n width: 250px; /* window */\n height: 337px; /* size */\n background: url(http://vi.sualize.us/thumbs/08/09/01/fashion,indie,inspiration,portrait-f825c152cc04c3dbbb6a38174a32a00f_h.jpg) no-repeat; /* put the image */\n border: 1px solid red; /* for debugging */\n text-indent: -1000px; /* hide the text */\n}\n\n#test:hover {\n background-position: -250px 0; /* on mouse over move the window to a different part of the image */\n} <a href=\"#\" id=\"test\">a button</a>"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] |
60,293 |
<p>I have a little problem with a Listview.</p>
<p>I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error]. There is a a narrow strip that doesn't paint. The width of that strip is approximately the same as a row header would be if I had a row header. </p>
<p>If you have a thought on what can be done to make the background draw I'd love to hear it. </p>
<p>Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view. [I love legacy code.]</p>
<p><strong>Edit:</strong></p>
<p>Here is a sample that exhibits the problem.</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListView lv = new ListView();
lv.Dock = System.Windows.Forms.DockStyle.Fill;
lv.FullRowSelect = true;
lv.GridLines = true;
lv.HideSelection = false;
lv.Location = new System.Drawing.Point(0, 0);
lv.TabIndex = 0;
lv.View = System.Windows.Forms.View.Details;
lv.AllowColumnReorder = true;
this.Controls.Add(lv);
lv.MultiSelect = true;
ColumnHeader ch = new ColumnHeader();
ch.Name = "Foo";
ch.Text = "Foo";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch);
ColumnHeader ch2 = new ColumnHeader();
ch.Name = "Bar";
ch.Text = "Bar";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch2);
lv.BeginUpdate();
for (int i = 0; i < 3; i++)
{
ListViewItem lvi = new ListViewItem("1", "2");
lvi.BackColor = Color.Black;
lvi.ForeColor = Color.White;
lv.Items.Add(lvi);
}
lv.EndUpdate();
}
}
</code></pre>
|
[
{
"answer_id": 60339,
"author": "moobaa",
"author_id": 3569,
"author_profile": "https://Stackoverflow.com/users/3569",
"pm_score": 4,
"selected": true,
"text": " ...\n lv.OwnerDraw = true;\n lv.DrawItem += new DrawListViewItemEventHandler( lv_DrawItem );\n ...\n\nvoid lv_DrawItem( object sender, DrawListViewItemEventArgs e )\n{\n Rectangle foo = e.Bounds;\n foo.Offset( -10, 0 );\n e.Graphics.FillRectangle( new SolidBrush( e.Item.BackColor ), foo );\n e.DrawDefault = true;\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327/"
] |
60,302 |
<p>If I start a process via Java's <a href="http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html" rel="noreferrer">ProcessBuilder</a> class, I have full access to that process's standard in, standard out, and standard error streams as Java <code>InputStreams</code> and <code>OutputStreams</code>. However, I can't find a way to seamlessly connect those streams to <code>System.in</code>, <code>System.out</code>, and <code>System.err</code>.</p>
<p>It's possible to use <code>redirectErrorStream()</code> to get a single <code>InputStream</code> that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C <code>system()</code> call.</p>
<p>This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of <a href="http://www.opengroup.org/onlinepubs/009695399/functions/isatty.html" rel="noreferrer"><code>isatty()</code></a> in the child process carries through the redirection.</p>
|
[
{
"answer_id": 60578,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 5,
"selected": true,
"text": "// Assume you already have a processBuilder all configured and ready to go\nfinal Process process = processBuilder.start();\nnew Thread(new Runnable() {public void run() {\n IOUtils.copy(process.getOutputStream(), System.out);\n} } ).start();\nnew Thread(new Runnable() {public void run() {\n IOUtils.copy(process.getErrorStream(), System.err);\n} } ).start();\nnew Thread(new Runnable() {public void run() {\n IOUtils.copy(System.in, process.getInputStream());\n} } ).start();\n"
},
{
"answer_id": 1570269,
"author": "Eelco",
"author_id": 445367,
"author_profile": "https://Stackoverflow.com/users/445367",
"pm_score": 4,
"selected": false,
"text": "private static void pipeOutput(Process process) {\n pipe(process.getErrorStream(), System.err);\n pipe(process.getInputStream(), System.out);\n}\n\nprivate static void pipe(final InputStream src, final PrintStream dest) {\n new Thread(new Runnable() {\n public void run() {\n try {\n byte[] buffer = new byte[1024];\n for (int n = 0; n != -1; n = src.read(buffer)) {\n dest.write(buffer, 0, n);\n }\n } catch (IOException e) { // just exit\n }\n }\n }).start();\n}\n"
},
{
"answer_id": 6303744,
"author": "claude",
"author_id": 792382,
"author_profile": "https://Stackoverflow.com/users/792382",
"pm_score": 2,
"selected": false,
"text": "System.in pipein() pipe() pipein(System.in, p.getOutputStream());\n private static void pipein(final InputStream src, final OutputStream dest) {\n\n new Thread(new Runnable() {\n public void run() {\n try {\n int ret = -1;\n while ((ret = System.in.read()) != -1) {\n dest.write(ret);\n dest.flush();\n }\n } catch (IOException e) { // just exit\n }\n }\n }).start();\n\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5696/"
] |
60,352 |
<p>If all of my <code>__init__.py</code> files are empty, do I have to store them into version control, or is there a way to make <code>distutils</code> create empty <code>__init__.py</code> files during installation?</p>
|
[
{
"answer_id": 60431,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "__init__.py __init__.py"
},
{
"answer_id": 60506,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": true,
"text": "__init__.py import __init__.py setup.py distutils.setup setup from distutils import setup\nimport os\n\nfor path in [my_package_directories]:\n filename = os.path.join(pagh, '__init__.py')\n if not os.path.exists(filename):\n init = open(filename, 'w')\n init.close()\n\nsetup(\n...\n)\n __init__.py"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
] |
60,360 |
<p>What experience can you share about using multiple AJAX libraries?</p>
<p>There are useful features in Prototype, some in jQuery, the Yahoo library, etc. Is it possible to include all libraries and use what you want from each, do they generally all play nicely together with name spaces, etc. For the sake of speed is there a practical limit to the size/number of libraries to include or is this negligible? Are there pairs that work particularly well together (e.g. Prototype/Scriptaculous) or pairs that don't?</p>
|
[
{
"answer_id": 60432,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "$('#foobar').whatever();\n var jq = jQuery.noConflict();\njq('#foobar').whatever();\n"
},
{
"answer_id": 61881,
"author": "Walter Rumsby",
"author_id": 1654,
"author_profile": "https://Stackoverflow.com/users/1654",
"pm_score": 2,
"selected": false,
"text": "Array"
},
{
"answer_id": 192331,
"author": "Caged",
"author_id": 26876,
"author_profile": "https://Stackoverflow.com/users/26876",
"pm_score": 1,
"selected": false,
"text": "$.getJSON('http://anothersite.com/mashup.json?callback=?', function(data) { });\n var Foo = Class.create({ \n initialize: function(name) {\n this.name = name;\n } \n});\n\nvar Bar = Class.create(Foo, {\n initialize: function($super, name) {\n $super(name);\n }\n});\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
60,369 |
<p>I'm currently playing around with <a href="http://pear.php.net/package/HTML_QuickForm" rel="noreferrer">HTML_QuickForm</a> for generating forms in PHP. It seems kind of limited in that it's hard to insert my own javascript or customizing the display and grouping of certain elements.</p>
<p>Are there any alternatives to QuickForm that might provide more flexibility?</p>
|
[
{
"answer_id": 60372,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "$('myFormControl').observe('click', myClickFunction)\n"
},
{
"answer_id": 62035,
"author": "Andrew Taylor",
"author_id": 1776,
"author_profile": "https://Stackoverflow.com/users/1776",
"pm_score": 1,
"selected": false,
"text": "[main]\nvessel.form.method = \"post\"\n\nvessel.form.elements.name.type = \"text\"\nvessel.form.elements.name.name = \"name\"\nvessel.form.elements.name.options.label = \"Name: \"\nvessel.form.elements.name.options.required = true\n\nvessel.form.elements.identifier_type.type = \"select\"\nvessel.form.elements.identifier_type.name = \"identifier_type\"\nvessel.form.elements.identifier_type.options.label = \"Identifier type: \"\nvessel.form.elements.identifier_type.options.required = true\nvessel.form.elements.identifier_type.options.multioptions.IMO Number = \"IMO Number\";\nvessel.form.elements.identifier_type.options.multioptions.Registry organisation and Number = \"Registry organisation and Number\";\nvessel.form.elements.identifier_type.options.multioptions.SSR Number = \"SSR Number\";\n\nvessel.form.elements.identifier.type = \"text\"\nvessel.form.elements.identifier.name = \"identifier\"\nvessel.form.elements.identifier.options.label = \"Identifier: \"\nvessel.form.elements.identifier.options.required = true\nvessel.form.elements.identifier.options.filters.lower.filter = \"StringToUpper\"\n\nvessel.form.elements.email.type = \"text\"\nvessel.form.elements.email.name = \"email\"\nvessel.form.elements.email.options.label = \"Email: \"\nvessel.form.elements.email.options.required = true\n\nvessel.form.elements.owner_id.type = \"hidden\"\nvessel.form.elements.owner_id.name = \"owner_id\"\nvessel.form.elements.owner_id.options.required = true\n\n; submit button\nvessel.form.elements.submit.type = \"submit\"\nvessel.form.elements.submit.name = \"Update\"\nvessel.form.elements.submit.option.value = \"Update\"\n"
},
{
"answer_id": 663432,
"author": "blockhead",
"author_id": 60223,
"author_profile": "https://Stackoverflow.com/users/60223",
"pm_score": 1,
"selected": false,
"text": "$this->form->setDecorators( array(array('ViewScript', array('viewScript' => 'forms/aform.phtml'))));\n <?=$this->element->title->renderViewHelper()?>\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
60,409 |
<p>I know in php you can embed variables inside variables, like:</p>
<pre><code><? $var1 = "I\'m including {$var2} in this variable.."; ?>
</code></pre>
<p>But I was wondering how, and if it was possible to include a function inside a variable.
I know I could just write:</p>
<pre><code><?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
</code></pre>
<p>But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions:</p>
<pre><code><?php
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
-somefunc() doesn't work
-{somefunc()} doesn't work
-$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
-more non-working: ${somefunc()}
</body>
</html>
EOF;
?>
</code></pre>
<p>Or I want dynamic changes in that load of code:</p>
<pre><code><?
function somefunc($stuff) {
$output = "my bold text <b>{$stuff}</b>.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
somefunc("is awesome!")
somefunc("is actually not so awesome..")
because somefunc("won\'t work due to my problem.")
</body>
</html>
EOF;
?>
</code></pre>
<p>Well?</p>
|
[
{
"answer_id": 60420,
"author": "Jason Weathered",
"author_id": 3736,
"author_profile": "https://Stackoverflow.com/users/3736",
"pm_score": 6,
"selected": true,
"text": "<?\nfunction somefunc($stuff)\n{\n $output = \"<b>{$stuff}</b>\";\n return $output;\n}\n$somefunc='somefunc';\necho \"foo {$somefunc(\"bar\")} baz\";\n?>\n foo <b>bar</b> baz <?\necho \"foo \" . somefunc(\"bar\") . \" baz\";\n?>\n <?\n$bar = somefunc(\"bar\");\necho \"foo {$bar} baz\";\n?>\n"
},
{
"answer_id": 60421,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "\"bla bla bla\".function(\"blub\").\" and on it goes\""
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4867/"
] |
60,438 |
<p>I am using jQuery. I call a JavaScript function with next html:</p>
<pre><code><li><span><a href="javascript:uncheckEl('tagVO-$id')">$tagname</a></span></li>
</code></pre>
<p>I would like to remove the <code>li</code> element and I thought this would be easy with the <code>$(this)</code> object. This is my JavaScript function:</p>
<pre><code>function uncheckEl(id) {
$("#"+id+"").attr("checked","");
$("#"+id+"").parent("li").css("color","black");
$(this).parent("li").remove(); // This is not working
retrieveItems();
}
</code></pre>
<p>But <code>$(this)</code> is undefined. Any ideas?</p>
|
[
{
"answer_id": 60449,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 3,
"selected": true,
"text": "<li> function unCheckEl(id, ref) {\n (...)\n $(ref).parent().parent().hide(); // this should be your <li>\n}\n <a href=\"javascript:uncheckEl('tagVO-$id', \\$(this))\">\n $(this) $(this) <a>"
},
{
"answer_id": 74712,
"author": "Parand",
"author_id": 13055,
"author_profile": "https://Stackoverflow.com/users/13055",
"pm_score": 1,
"selected": false,
"text": "<li id=\"uncheck_tagVO-$id\">$tagname</li>\n $('li').click( function() {\n var id = this.id.split(\"_\")[1];\n $('#'+id).attr(\"checked\",\"\").parent(\"li\").css(\"color\",\"black\"); \n $(this).remove();\n retrieveItems();\n});\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
60,455 |
<p>Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server?</p>
<p>I'm not so concerned with browser security issues. etc. as the implementation would be for <a href="http://msdn.microsoft.com/en-us/library/ms536471(vs.85).aspx" rel="noreferrer">HTA</a>. But is it possible?</p>
|
[
{
"answer_id": 63506,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 6,
"selected": true,
"text": "Declare Sub keybd_event Lib \"user32\" _\n(ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)\n\nPublic Const CaptWindow = 2\n\nPublic Sub ScreenGrab()\n keybd_event &H12, 0, 0, 0\n keybd_event &H2C, CaptWindow, 0, 0\n keybd_event &H2C, CaptWindow, &H2, 0\n keybd_event &H12, 0, &H2, 0\nEnd Sub\n"
},
{
"answer_id": 3936602,
"author": "xmedeko",
"author_id": 254109,
"author_profile": "https://Stackoverflow.com/users/254109",
"pm_score": 2,
"selected": false,
"text": "java.awt.Robot"
},
{
"answer_id": 4340297,
"author": "RobertPitt",
"author_id": 353790,
"author_profile": "https://Stackoverflow.com/users/353790",
"pm_score": 3,
"selected": false,
"text": "public Bitmap GenerateScreenshot(string url)\n{\n // This method gets a screenshot of the webpage\n // rendered at its full size (height and width)\n return GenerateScreenshot(url, -1, -1);\n}\n\npublic Bitmap GenerateScreenshot(string url, int width, int height)\n{\n // Load the webpage into a WebBrowser control\n WebBrowser wb = new WebBrowser();\n wb.ScrollBarsEnabled = false;\n wb.ScriptErrorsSuppressed = true;\n wb.Navigate(url);\n while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }\n\n\n // Set the size of the WebBrowser control\n wb.Width = width;\n wb.Height = height;\n\n if (width == -1)\n {\n // Take Screenshot of the web pages full width\n wb.Width = wb.Document.Body.ScrollRectangle.Width;\n }\n\n if (height == -1)\n {\n // Take Screenshot of the web pages full height\n wb.Height = wb.Document.Body.ScrollRectangle.Height;\n }\n\n // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control\n Bitmap bitmap = new Bitmap(wb.Width, wb.Height);\n wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));\n wb.Dispose();\n\n return bitmap;\n}\n exec(\"CreateScreenShot.exe -url http://.... -save C:/shots domain_page.png\");"
},
{
"answer_id": 44859895,
"author": "Johnny",
"author_id": 2811258,
"author_profile": "https://Stackoverflow.com/users/2811258",
"pm_score": 0,
"selected": false,
"text": "// include the grabzit.min.js library in the web page you want the capture to appear\n<script src=\"grabzit.min.js\"></script>\n\n//use the key and the secret to login, capture the url\n<script>\nGrabzIt(\"KEY\", \"SECRET\").ConvertURL(\"http://www.google.com\").Create();\n</script>\n GrabzIt(\"KEY\", \"SECRET\").ConvertURL(\"http://www.google.com\", \n{\"width\": 400, \"height\": 400, \"format\": \"png\", \"delay\", 10000}).Create();\n</script>\n"
},
{
"answer_id": 53336136,
"author": "Ekin Koc",
"author_id": 257925,
"author_profile": "https://Stackoverflow.com/users/257925",
"pm_score": 1,
"selected": false,
"text": "const puppeteer = require('puppeteer');\n\n(async () => {\n const browser = await puppeteer.launch();\n const page = await browser.newPage();\n await page.goto('https://example.com');\n await page.screenshot({path: 'example.png'});\n\n await browser.close();\n})();\n"
},
{
"answer_id": 59056978,
"author": "shaedrich",
"author_id": 7451109,
"author_profile": "https://Stackoverflow.com/users/7451109",
"pm_score": 2,
"selected": false,
"text": "getDisplayMedia"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1915/"
] |
60,456 |
<p>I have this in a page :</p>
<pre><code><textarea id="taEditableContent" runat="server" rows="5"></textarea>
<ajaxToolkit:DynamicPopulateExtender ID="dpeEditPopulate" runat="server" TargetControlID="taEditableContent"
ClearContentsDuringUpdate="true" PopulateTriggerControlID="hLink" ServicePath="/Content.asmx"
ServiceMethod="EditContent" ContextKey='<%=ContextKey %>' />
</code></pre>
<p>Basically, a DynamicPopulateExtender that fills the contents of a textarea from a webservice. Problem is, no matter how I return the line breaks, the text in the text area will have no line feeds.</p>
<p>If I return the newlines as "br/" the entire text area remains empty. If I return new lines as "/r/n" , I get all the text as one continous line. The webservice returns the string correctly:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://rprealm.com/">First line
Third line
Fourth line</string>
</code></pre>
<p>But what I get in the text area is :</p>
<pre><code>First line Third line Fourth line
</code></pre>
|
[
{
"answer_id": 321353,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 1,
"selected": false,
"text": "xml:space=\"preserve\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\""
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
] |
60,464 |
<p>I am fairly new to Emacs and I have been trying to figure out how to change the default folder for <kbd>C-x C-f</kbd> on start-up. For instance when I first load Emacs and hit <kbd>C-x C-f</kbd> its default folder is <code>C:\emacs\emacs-21.3\bin</code>, but I would rather it be the desktop. I believe there is some way to customize the <code>.emacs</code> file to do this, but I am still unsure what that is.</p>
<p>Update: There are three solutions to the problem that I found to work, however I believe solution 3 is Windows only.</p>
<ul>
<li><p>Solution 1: Add <code>(cd "C:/Users/Name/Desktop")</code> to the <code>.emacs</code> file</p></li>
<li><p>Solution 2: Add <code>(setq default-directory "C:/Documents and Settings/USER_NAME/Desktop/")</code> to the <code>.emacs</code> file</p></li>
<li><p>Solution 3: Right click the Emacs short cut, hit properties and change the start in field to the desired directory.</p></li>
</ul>
|
[
{
"answer_id": 60481,
"author": "vava",
"author_id": 6258,
"author_profile": "https://Stackoverflow.com/users/6258",
"pm_score": 5,
"selected": false,
"text": "(cd \"c:/cvsroot/\")\n"
},
{
"answer_id": 60482,
"author": "Bart",
"author_id": 4343,
"author_profile": "https://Stackoverflow.com/users/4343",
"pm_score": 8,
"selected": true,
"text": "default-directory default-directory Properties Start In default-directory"
},
{
"answer_id": 60483,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": false,
"text": "C:\\emacs\\emacs-21.3\\bin\\runemacs.exe Start In:"
},
{
"answer_id": 60531,
"author": "Eric Hansander",
"author_id": 5039,
"author_profile": "https://Stackoverflow.com/users/5039",
"pm_score": 3,
"selected": false,
"text": "C:\\dir_a C:\\dir_a M-x cd C-x C-f *scratch* M-x cd *scratch* (cd \"c:/dir_a/\")\n .emacs"
},
{
"answer_id": 65411,
"author": "Michael",
"author_id": 9316,
"author_profile": "https://Stackoverflow.com/users/9316",
"pm_score": 6,
"selected": false,
"text": "(setq default-directory \"C:/Documents and Settings/USER NAME/Desktop/\" )\n"
},
{
"answer_id": 68941874,
"author": "Gangula",
"author_id": 6908282,
"author_profile": "https://Stackoverflow.com/users/6908282",
"pm_score": 1,
"selected": false,
"text": "runemacs.exe Start In Start In"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340/"
] |
60,470 |
<p>If I'm running a signed Java applet. Can I load additional classes from remote sources, in the same domain or maybe even the same host, and run them?</p>
<p>I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once.</p>
<p>Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status?</p>
|
[
{
"answer_id": 60615,
"author": "jassuncao",
"author_id": 1009,
"author_profile": "https://Stackoverflow.com/users/1009",
"pm_score": 4,
"selected": true,
"text": "ClassLoader loader = this.getClass().getClassLoader();\nClass clazz = loader.loadClass(\"acme.AppletAddon\");\n URL[] urls = new URL[]{new URL(\"http://localhost:8080/addon.jar\")};\nURLClassLoader loader = URLClassLoader.newInstance(urls,this.getClass().getClassLoader());\nClass clazz = loader.loadClass(\"acme.AppletAddon\");\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
60,507 |
<p>Say I have:</p>
<pre><code>void Render(void(*Call)())
{
D3dDevice->BeginScene();
Call();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
</code></pre>
<p>This is fine as long as the function I want to use to render is a function or a <code>static</code> member function:</p>
<pre><code>Render(MainMenuRender);
Render(MainMenu::Render);
</code></pre>
<p>However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g.</p>
<pre><code>Render(MainMenu->Render);
</code></pre>
<p>However I really have no idea how to do this, and still allow functions and <code>static</code> member functions to be used.</p>
|
[
{
"answer_id": 60512,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "void Wrap(T *t) t->Call() Render void Wrap(T *t)\n{\n t->Call();\n}\n\nvoid Render(void (*f)(T *), T *t)\n{\n ...\n f(t);\n ...\n}\n"
},
{
"answer_id": 60513,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 5,
"selected": true,
"text": "#include <boost/bind.hpp>\n#include <boost/function.hpp>\n\nvoid Render(boost::function0<void> Call)\n{\n // as before...\n}\n\nRender(boost::bind(&MainMenu::Render, myMainMenuInstance));\n"
},
{
"answer_id": 60515,
"author": "cjanssen",
"author_id": 2950,
"author_profile": "https://Stackoverflow.com/users/2950",
"pm_score": 1,
"selected": false,
"text": "void CallRender(myclass *Instance)\n{\n Instance->Render();\n}\n void Render(void (*Call)(myclass*), myclass* Instance)\n{\n ...\n Call(Instance);\n ...\n}\n Render(CallRender, &MainMenu);\n"
},
{
"answer_id": 60527,
"author": "Tom Martin",
"author_id": 5303,
"author_profile": "https://Stackoverflow.com/users/5303",
"pm_score": 1,
"selected": false,
"text": "((object).*(ptrToMember)) \n\nvoid Render(IRenderer *Renderer)\n{\n D3dDevice->BeginScene();\n Renderer->Render();\n D3dDevice->EndScene();\n D3dDevice->Present(0,0,0,0);\n}\n\n// The \"interface\"\npublic class IRenderer \n{\npublic:\n virtual void Render();\n};\n\npublic class StaticCaller: public IRenderer\n{\n void (*Call)();\npublic:\n\n StaticCaller((*Call)())\n {\n this->Call = Call;\n }\n\n void Render()\n {\n Call();\n }\n};\n\n"
},
{
"answer_id": 354514,
"author": "Nick Gebbie",
"author_id": 44761,
"author_profile": "https://Stackoverflow.com/users/44761",
"pm_score": 0,
"selected": false,
"text": "typedef void (T::*FUNCTIONPOINTERTYPE)(args..)\nFUNCTIONPOINTERTYPE function;\n T* t;\nFUNCTIONPOINTERTYPE function;\n(t->*function)(args..);\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
60,516 |
<p>I'm using a few (2 or 3) master pages in my ASP.NET MVC application and they must each display bits of information from the database. Such as a list of sponsors, current fundings status etc.</p>
<p>So my question was, where should I put these master-page database calling code?</p>
<p>Normally, these should goes into its own controller class right? But then that'd mean I'd have to wire them up manually (e.g. passing ViewDatas) since it is out of the normal routing framework provided by the MVC framework.</p>
<p>Is there a way to this cleanly without wiring ViewData passing/Action calls to master pages manually or subclassing the frameworks'?</p>
<p>The amount of documentation is very low... and I'm very new to all this including the concepts of MVC itself so please share your tips/techniques on this.</p>
|
[
{
"answer_id": 66806,
"author": "Dane O'Connor",
"author_id": 1946,
"author_profile": "https://Stackoverflow.com/users/1946",
"pm_score": 0,
"selected": false,
"text": "protected override ViewResult View(string viewName, string masterName, object model)\n{\n if (model == null)\n {\n model = new ViewDataBase();\n }\n return base.View(viewName, masterName, model);\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3055/"
] |
60,558 |
<p>I need to do some emulation of some old DOS or mainframe terminals in Flex. Something like the image below for example.</p>
<p><img src="https://i.stack.imgur.com/qFtvP.png" alt="alt text"></p>
<p>The different coloured text is easy enough, but the ability to do different background colours, such as the yellow background is beyond the capabilities of the standard Flash text.</p>
<p>I may also need to be able to enter text at certain places and scroll text up the "terminal". Any idea how I'd attack this? Or better still, any existing code/components for this sort of thing?</p>
|
[
{
"answer_id": 60595,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 2,
"selected": false,
"text": "TextField.getCharBoundaries Shape var firstCharBounds : Rectangle = textField.getCharBoundaries(firstCharIndex);\nvar lastCharBounds : Rectangle = textField.getCharBoundaries(lastCharIndex);\n\nvar rangeBounds : Rectangle = new Rectangle();\n\nrangeBounds.topLeft = firstCharBounds.topLeft;\nrangeBounds.bottomRight = lastCharBounds.bottomRight;\n var charBounds : Rectangle = textField.getCharBoundaries(textField.getLineOffset(lineNumber));\n\nvar lineBounds : Rectangle = new Rectangle(0, charBounds.y, textField.width, firstCharBounds.height);\n updateDisplayList textRangesWithYellowBackground graphics.clear();\n\n// this draws the black background\ngraphics.beginFill(0x000000);\ngraphics.drawRect(0, 0, textField.width, textField.height);\ngraphics.endFill();\n\n// this draws yellow text backgrounds\nfor each ( var r : Rectangle in textRangesWithYellowBackground )\n graphics.beginFill(0xFFFF00);\n graphics.drawRect(r.x, r.y, r.width, r.height);\n graphics.endFill();\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6277/"
] |
60,565 |
<p>I have a Visual Studio Setup Project that I use to install a fairly simple WinForms application. At the end of the install I have a custom user interface page that shows a single check box which asks the user if they want to run the application. I've seen other installers do this quite often. But I cannot find a way to get the Setup Project to run an executable after the install finishes. An ideas?</p>
<p>NOTE: You cannot use Custom Actions because these are used as part of the install process, I want to run my installed application once the user presses the 'Close' button at the end of the install.</p>
|
[
{
"answer_id": 7396841,
"author": "Grub",
"author_id": 723459,
"author_profile": "https://Stackoverflow.com/users/723459",
"pm_score": 0,
"selected": false,
"text": "(typeof(ClassWithinAssemblyToExecute)).Assembly.EntryPoint.Invoke(null, new Object[] {} )\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6276/"
] |
60,569 |
<p>I want something that looks like a file handle but is really backed by an in-memory buffer to use for I/O redirects. How can I do this?</p>
|
[
{
"answer_id": 65211,
"author": "Chris Smith",
"author_id": 9073,
"author_profile": "https://Stackoverflow.com/users/9073",
"pm_score": 1,
"selected": false,
"text": "/libraries/base/IOBase.lhs"
},
{
"answer_id": 1047220,
"author": "cjs",
"author_id": 107294,
"author_profile": "https://Stackoverflow.com/users/107294",
"pm_score": 2,
"selected": false,
"text": "System.SIO System.IO Data.ByteString"
},
{
"answer_id": 7700839,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "Handle ByteString import Data.ByteString (pack)\nimport Data.Knob\nimport System.IO\n\nmain = do\n knob <- newKnob (pack [])\n h <- newFileHandle knob \"test.txt\" WriteMode\n hPutStrLn h \"Hello world!\"\n hClose h\n bytes <- Data.Knob.getContents knob\n putStrLn (\"Wrote bytes: \" ++ show bytes)\n"
},
{
"answer_id": 48191061,
"author": "Asa",
"author_id": 1769679,
"author_profile": "https://Stackoverflow.com/users/1769679",
"pm_score": 1,
"selected": false,
"text": "createPipe System.Process createPipe :: IO (Handle, Handle)\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] |
60,570 |
<p>Backgrounder:</p>
<p>The <a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="noreferrer">PIMPL Idiom</a> (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.</p>
<p>This hides internal implementation details and data from the user of the library.</p>
<p>When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?</p>
<p>To illustrate, this code puts the <code>Purr()</code> implementation on the impl class and wraps it as well.</p>
<p><strong>Why not implement Purr directly on the public class?</strong></p>
<pre class="lang-c++ prettyprint-override"><code>// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}
</code></pre>
|
[
{
"answer_id": 60605,
"author": "Xavier Nodet",
"author_id": 4177,
"author_profile": "https://Stackoverflow.com/users/4177",
"pm_score": 6,
"selected": true,
"text": "Purr() CatImpl Cat::Purr() friend"
},
{
"answer_id": 60618,
"author": "JeffV",
"author_id": 445087,
"author_profile": "https://Stackoverflow.com/users/445087",
"pm_score": 0,
"selected": false,
"text": "catlib::Cat::Purr(){ cat_->Purr(); }\ncat::Cat::Purr(){\n printf(\"purrrrrr\");\n}\n"
},
{
"answer_id": 6426059,
"author": "Esben Nielsen",
"author_id": 808531,
"author_profile": "https://Stackoverflow.com/users/808531",
"pm_score": 2,
"selected": false,
"text": "class Foo {\npublic:\n virtual ~Foo() { }\n virtual void someMethod() = 0;\n\n // This \"replaces\" the constructor\n static Foo *create();\n}\n namespace {\n class FooImpl: virtual public Foo {\n\n public:\n void someMethod() {\n //....\n }\n };\n}\n\nFoo *Foo::create() {\n return new FooImpl;\n}\n"
},
{
"answer_id": 25993728,
"author": "the swine",
"author_id": 1140976,
"author_profile": "https://Stackoverflow.com/users/1140976",
"pm_score": 5,
"selected": false,
"text": "Cat Cat CatImpl .cpp"
},
{
"answer_id": 26871719,
"author": "nurettin",
"author_id": 227755,
"author_profile": "https://Stackoverflow.com/users/227755",
"pm_score": 2,
"selected": false,
"text": "struct Omg{\n void purr(){ cout<< \"purr\\n\"; }\n};\n\nstruct Lol{\n Omg* omg;\n /*...*/\n void purr(){ try{ pre(); omg-> purr(); post(); }catch(...){ error(); } }\n};\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
60,573 |
<p>Using C# .NET 2.0, I have a composite data class that does have the <code>[Serializable]</code> attribute on it. I am creating an <code>XMLSerializer</code> class and passing that into the constructor:</p>
<pre><code>XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
</code></pre>
<p>I am getting an exception saying: </p>
<blockquote>
<p>There was an error reflecting type.</p>
</blockquote>
<p>Inside the data class there is another composite object. Does this also need to have the <code>[Serializable]</code> attribute, or by having it on the top object, does it recursively apply it to all objects inside?</p>
|
[
{
"answer_id": 60581,
"author": "Lamar",
"author_id": 3566,
"author_profile": "https://Stackoverflow.com/users/3566",
"pm_score": 10,
"selected": true,
"text": "[XmlIgnore] XmlSerializer [Serializable]"
},
{
"answer_id": 60596,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 3,
"selected": false,
"text": "XMLSerializer"
},
{
"answer_id": 60610,
"author": "Darren",
"author_id": 6065,
"author_profile": "https://Stackoverflow.com/users/6065",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.IO;\nusing System.Xml;\nusing System.Collections.Generic;\nusing System.Xml.Serialization;\n\npublic class Inner\n{\n private string _AnotherStringProperty;\n public string AnotherStringProperty \n { \n get { return _AnotherStringProperty; } \n set { _AnotherStringProperty = value; } \n }\n}\n\npublic class DataClass\n{\n private string _StringProperty;\n public string StringProperty \n { \n get { return _StringProperty; } \n set{ _StringProperty = value; } \n }\n\n private Inner _InnerObject;\n public Inner InnerObject \n { \n get { return _InnerObject; } \n set { _InnerObject = value; } \n }\n}\n\npublic class MyClass\n{\n\n public static void Main()\n {\n try\n {\n XmlSerializer serializer = new XmlSerializer(typeof(DataClass));\n TextWriter writer = new StreamWriter(@\"c:\\tmp\\dataClass.xml\");\n DataClass clazz = new DataClass();\n Inner inner = new Inner();\n inner.AnotherStringProperty = \"Foo2\";\n clazz.InnerObject = inner;\n clazz.StringProperty = \"foo\";\n serializer.Serialize(writer, clazz);\n }\n finally\n {\n Console.Write(\"Press any key to continue...\");\n Console.ReadKey();\n }\n }\n\n}\n"
},
{
"answer_id": 60714,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": false,
"text": "XmlSerializer"
},
{
"answer_id": 72043,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "NetDataSerialiser"
},
{
"answer_id": 2715915,
"author": "Luca",
"author_id": 161554,
"author_profile": "https://Stackoverflow.com/users/161554",
"pm_score": 3,
"selected": false,
"text": "public class NetService : IXmlSerializable\n{\n #region Data\n\n public string Identifier = String.Empty;\n\n public string Name = String.Empty;\n\n public IPAddress Address = IPAddress.None;\n public int Port = 7777;\n\n #endregion\n\n #region IXmlSerializable Implementation\n\n public XmlSchema GetSchema() { return (null); }\n\n public void ReadXml(XmlReader reader)\n {\n // Attributes\n Identifier = reader[XML_IDENTIFIER];\n if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)\n throw new XmlException(\"unable to parse the element \" + typeof(NetService).Name + \" (badly formatted parameter \" + XML_NETWORK_PORT);\n if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)\n throw new XmlException(\"unable to parse the element \" + typeof(NetService).Name + \" (badly formatted parameter \" + XML_NETWORK_ADDR);\n }\n\n public void WriteXml(XmlWriter writer)\n {\n // Attributes\n writer.WriteAttributeString(XML_IDENTIFIER, Identifier);\n writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());\n writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());\n }\n\n private const string XML_IDENTIFIER = \"Id\";\n\n private const string XML_NETWORK_ADDR = \"Address\";\n\n private const string XML_NETWORK_PORT = \"Port\";\n\n #endregion\n}\n IXmlSerializable XmlSerializer"
},
{
"answer_id": 4471269,
"author": "LepardUK",
"author_id": 44247,
"author_profile": "https://Stackoverflow.com/users/44247",
"pm_score": 2,
"selected": false,
"text": " [System.Xml.Serialization.XmlElementAttribute(Order = XX)]\n"
},
{
"answer_id": 7450751,
"author": "Dennis Calla",
"author_id": 510199,
"author_profile": "https://Stackoverflow.com/users/510199",
"pm_score": 5,
"selected": false,
"text": "[XmlType(\"BaseNamespace.Class1\")]\n"
},
{
"answer_id": 8835456,
"author": "jkokorian",
"author_id": 1068959,
"author_profile": "https://Stackoverflow.com/users/1068959",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<SomeClass> IEnumerable List<SomeClass>"
},
{
"answer_id": 13923224,
"author": "Jeremy Brown",
"author_id": 1911312,
"author_profile": "https://Stackoverflow.com/users/1911312",
"pm_score": 1,
"selected": false,
"text": "[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = \"SeriousInjuryFlag\")]\n [System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = \"AccidentFlag\")]\n"
},
{
"answer_id": 21954336,
"author": "Stefan Michev",
"author_id": 754571,
"author_profile": "https://Stackoverflow.com/users/754571",
"pm_score": 3,
"selected": false,
"text": " - the object being serialized has no parameterless constructor\n - the object contains Dictionary\n - the object has some public Interface members\n"
},
{
"answer_id": 42273101,
"author": "Kiran.Bakwad",
"author_id": 2940450,
"author_profile": "https://Stackoverflow.com/users/2940450",
"pm_score": 0,
"selected": false,
"text": "[System.Xml.Serialization.XmlElementAttribute(\"strFieldName\", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]\n [XmlIgnore]\nstring [] strFielsName {get;set;}\n"
},
{
"answer_id": 59372719,
"author": "chxzy",
"author_id": 4871263,
"author_profile": "https://Stackoverflow.com/users/4871263",
"pm_score": 0,
"selected": false,
"text": "TimeSpan String [System.Xml.Serialization.XmlElementAttribute(DataType=\"time\", Order=3)]\n public string TimeProperty {\n get {\n return this.timePropertyField;\n }\n set {\n this.timePropertyField = value;\n this.RaisePropertyChanged(\"TimeProperty\");\n }\n}\n DateType Xml [System.Xml.Serialization.XmlElementAttribute(Order=3)]\npublic string TimeProperty {\n get {\n return this.timePropertyField;\n }\n set {\n this.timePropertyField = value;\n this.RaisePropertyChanged(\"TimeProperty\");\n }\n}\n"
},
{
"answer_id": 59372769,
"author": "Iqra.",
"author_id": 7596696,
"author_profile": "https://Stackoverflow.com/users/7596696",
"pm_score": 1,
"selected": false,
"text": "Type Type [XmlIgnore]\n public Type Type { get; set; }\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
60,585 |
<p>I'm running PHP, Apache, and Windows. I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM).</p>
<p>I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in your script, but without AD there is no LDAP. What is the equivalent for standalone machines?</p>
|
[
{
"answer_id": 66417,
"author": "Martin",
"author_id": 2581,
"author_profile": "https://Stackoverflow.com/users/2581",
"pm_score": 0,
"selected": false,
"text": "// Usage: logonuser.exe /user username /password password [/domain domain]\n// Exit code is 0 on logon success and 1 on failure.\n\n#include <windows.h>\n\nint main(int argc, char *argv[]) {\n HANDLE r = 0;\n char *user = 0;\n char *password = 0;\n char *domain = 0;\n int i;\n\n for(i = 1; i < argc; i++) {\n if(!strcmp(argv[i], \"/user\")) {\n if(i + 1 < argc) {\n user = argv[i + 1];\n i++;\n }\n } else if(!strcmp(argv[i], \"/domain\")) {\n if(i + 1 < argc) {\n domain = argv[i + 1];\n i++;\n }\n } else if(!strcmp(argv[i], \"/password\")) {\n if(i + 1 < argc) {\n password = argv[i + 1];\n i++;\n }\n }\n }\n\n if(user && password) {\n LogonUser(user, domain, password, LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, &r);\n }\n return r ? 0 : 1;\n}\n if($_SERVER['REQUEST_METHOD'] == 'POST') {\n if(isset($_REQUEST['user'], $_REQUEST['password'], $_REQUEST['domain'])) {\n $failure = 1;\n $user = $_REQUEST['user'];\n $password = $_REQUEST['password'];\n $domain = $_REQUEST['domain'];\n\n if($user && $password) {\n $cmd = \"logonuser.exe /user \" . escapeshellarg($user) . \" /password \" . escapeshellarg($password);\n if($domain) $cmd .= \" /domain \" . escapeshellarg($domain);\n system($cmd, $failure);\n }\n\n if($failure) {\n echo(\"Incorrect credentials.\");\n } else {\n echo(\"Correct credentials!\");\n }\n }\n}\n?>\n<form action=\"<?php echo(htmlentities($_SERVER['PHP_SELF'])); ?>\" method=\"post\">\n Username: <input type=\"text\" name=\"user\" value=\"<?php echo(htmlentities($user)); ?>\" /><br />\n Password: <input type=\"password\" name=\"password\" value=\"\" /><br />\n Domain: <input type=\"text\" name=\"domain\" value=\"<?php echo(htmlentities($domain)); ?>\" /><br />\n <input type=\"submit\" value=\"logon\" />\n</form>\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] |
60,590 |
<p>On a PHP-based web site, I want to send users a download package after they have filled out a short form. The site-initiated download should be similar to sites like download.com, which say "your download will begin in a moment."</p>
<p>A couple of <strong>possible approaches</strong> I know about, and browser compatibility (based on a quick test):</p>
<p><strong>1) Do a <code>window.open</code> pointing to the new file.</strong> </p>
<pre><code>- FireFox 3 blocks this.
- IE6 blocks this.
- IE7 blocks this.
</code></pre>
<p><strong>2) Create an iframe pointing to the new file.</strong> </p>
<pre><code>- FireFox 3 seems to think this is OK. (Maybe it's because I already accepted it once?)
- IE6 blocks this.
- IE7 blocks this.
How can I do this so that at least these three browsers will not object?
</code></pre>
<p>Bonus: is there a method that doesn't require browser-conditional statements? </p>
<p>(I believe that download.com employs both methods conditionally, but I can't get either one to work.)</p>
<p><strong>Responses and Clarifications:</strong></p>
<pre><code>Q: "Why not point the current window to the file?"
A: That might work, but in this particular case, I want to show them some other content while their download starts - for example, "would you like to donate to this project?"
</code></pre>
<p><strong>UPDATE: I have abandoned this approach. See my answer below for reasons.</strong></p>
|
[
{
"answer_id": 60603,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 3,
"selected": false,
"text": "if(file_exists($filename)) {\n header(\"Pragma: public\");\n header(\"Expires: 0\");\n header(\"Cache-Control: must-revalidate, pre-check=0\");\n header(\"Cache-Control: private\", false);\n header(\"Content-Type: \" . $content-type);\n header(\"Content-Disposition: attachment; filename=\\\"\" . basename($filename) . \"\\\";\" );\n header(\"Content-Transfer-Encoding: binary\");\n header(\"Content-Length: \" . filesize($filename));\n\n readfile(\"$filename\");\n}else{\n print \"ERROR: the file \" . basename($filename) . \" could not be downloaded because it did not exist.\";\n}\n"
},
{
"answer_id": 60606,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 5,
"selected": true,
"text": "<meta http-equiv=\"refresh\" content=\"5;url=/download.php?doc=123.zip\"/>\n"
},
{
"answer_id": 60619,
"author": "Dan Walker",
"author_id": 752,
"author_profile": "https://Stackoverflow.com/users/752",
"pm_score": 0,
"selected": false,
"text": "<iframe src=\"/download.exe\" frameborder=\"0\" height=\"0\" width=\"0\"><a href=\"/download.exe\">Click here to download.</a></iframe>\n"
},
{
"answer_id": 114732,
"author": "bastiandoeen",
"author_id": 371953,
"author_profile": "https://Stackoverflow.com/users/371953",
"pm_score": 1,
"selected": false,
"text": "header(\"Location: ./$path/$filename\");\n"
},
{
"answer_id": 728009,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "<a href=\"normaldownload.zip\" onclick=\"use_dhtml_or_ajax_to_display_page()\">\n Content-Disposition"
},
{
"answer_id": 29692393,
"author": "sagunms",
"author_id": 1297184,
"author_profile": "https://Stackoverflow.com/users/1297184",
"pm_score": 0,
"selected": false,
"text": "$(\"btnDownloadCSV\").on('click', function() {\n $.ajax({\n url: \"php_backend/get_download_url\",\n type: 'post',\n contentType: \"application/x-www-form-urlencoded\",\n data: {somedata: \"somedata\"},\n success: function(data) {\n // If iFrame already exists, remove it.\n if($(\"[id^='iframeTempCSV_\"]).length) { \n $(\"[id^='iframeTempCSV_\"]).remove();\n }\n setTimeout(function() {\n // If I'm creating an iframe with the same id, it will permit download only the first time.\n // So randHashId appended to ID to trick the browser.\n var randHashId = Math.random().toString(36).substr(2);\n // Create a fresh iFrame for auto-downloading CSV\n $('<iframe id=\"iframeTempCSV_'+randHashId+'\" style=\"display:none;\" src=\"'+data.filepath+'\"></iframe>').appendTo('body');\n }, 1000);\n },\n error: function(xhr, textStatus, errorThrown) {\n console.error(\"Error downloading...\");\n }\n });\n});\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4376/"
] |
60,607 |
<p>What are the pros/cons of doing either way. Is there One Right Way(tm) ?</p>
|
[
{
"answer_id": 60631,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": "try {\n $user->login();\n} catch (AuthenticationFailureException $e) {\n set_error_handler(\"my_login_form_handler\");\n trigger_error(\"User could not be logged in. Please check username and password and try again!\");\n} catch (PersistenceException $pe) { // database unavailable\n set_error_handler(\"my_login_form_handler\"); \n trigger_error(\"Internal system error. Please contact the administrator.\");\n}\n"
},
{
"answer_id": 1129157,
"author": "shadowhand",
"author_id": 49146,
"author_profile": "https://Stackoverflow.com/users/49146",
"pm_score": 4,
"selected": false,
"text": "E_NOTICE E_NOTICE E_WARNING try catch @ try {\n $foo = $_GET['foo'];\n} catch (ErrorException $e) {\n $foo = NULL;\n}\n try catch"
},
{
"answer_id": 13655714,
"author": "Tivie",
"author_id": 295342,
"author_profile": "https://Stackoverflow.com/users/295342",
"pm_score": 2,
"selected": false,
"text": "class HTMLParser {\n protected $doc;\n protected $source = null;\n public $parsedHtml;\n protected $parseErrors = array();\n public function __construct($doc) {\n if (!$doc instanceof DOMDocument) {\n // My Object is unusable without a valid DOMDOcument object\n // so I throw a CriticalException\n throw new CriticalException(\"Could not create Object Foo. You must pass a valid DOMDOcument object as parameter in the constructor\");\n }\n $this->doc = $doc;\n }\n\n public function setSource($source) {\n if (!is_string($source)) {\n // I expect $source to be a string but was passed something else so I throw an exception\n throw new InvalidArgumentException(\"I expected a string but got \" . gettype($source) . \" instead\");\n }\n $this->source = trim($source);\n return $this;\n }\n\n public function parse() {\n if (is_null($this->source) || $this->source == '') {\n throw new EmptyStringException(\"Source is empty\");\n }\n libxml_use_internal_errors(true);\n $this->doc->loadHTML($this->source);\n $this->parsedHtml = $this->doc->saveHTML();\n $errors = libxml_get_errors();\n if (count($errors) > 0) {\n $this->parseErrors = $errors;\n throw new HtmlParsingException($errors[0]->message,$errors[0]->code,null,\n $errors[0]->level,$errors[0]->column,$errors[0]->file,$errors[0]->line);\n }\n return $this;\n }\n\n public function getParseErrors() {\n return $this->parseErrors;\n }\n\n public function getDOMObj() {\n return clone $this->doc;\n }\n}\n CriticalException DOMDocument __construct(DOMDocument $doc) setsource() InvalidArgumentException parse() XmlParsingException $source = file_get_contents('http://www.somehost.com/some_page.html');\ntry {\n $parser = new HTMLParser(new DOMDocument());\n $parser->setSource($source)\n ->parse();\n} catch (CriticalException $e) {\n // Library failed miserably, no recover is possible for it.\n // In this case, it's prorably my fault because I didn't pass\n // a DOMDocument object.\n print 'Sorry. I made a mistake. Please send me feedback!';\n} catch (InvalidArgumentException $e) {\n // the source passed is not a string, again probably my fault.\n // But I have a working parser object. \n // Maybe I can try again by typecasting the argument to string\n var_dump($parser);\n} catch (EmptyStringException $e) {\n // The source string was empty. Maybe there was an error\n // retrieving the HTML? Maybe the remote server is down?\n // Maybe the website does not exist anymore? In this case,\n // it isn't my fault it failed. Maybe I can use a cached\n // version?\n var_dump($parser);\n} catch (HtmlParsingException $e) {\n // The html suplied is malformed. I got it from the interwebs\n // so it's not my fault. I can use $e or getParseErrors() \n // to see if the html (and DOM Object) is usable\n // I also have a full functioning HTMLParser Object and can\n // retrieve a \"loaded\" functioning DOMDocument Object\n var_dump($parser->getParseErrors());\n var_dump($parser->getDOMObj());\n}\n$var = 'this will print wether an exception was previously thrown or not';\nprint $var;\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
60,641 |
<p>I need to replace all WinAPI calls of the</p>
<ul>
<li>CreateFile, </li>
<li>ReadFile, </li>
<li>SetFilePointer,</li>
<li>CloseHandle </li>
</ul>
<p>with my own implementation (which use low-level file reading via Bluetooth).
The code, where functions will be replaced, is Video File Player and it already works with the regular hdd files.
It is also needed, that Video Player still can play files from HDD, if the file in the VideoPlayer input is a regular hdd file.</p>
<p>What is the best practice for such task?</p>
|
[
{
"answer_id": 60651,
"author": "Maximilian",
"author_id": 1733,
"author_profile": "https://Stackoverflow.com/users/1733",
"pm_score": 0,
"selected": false,
"text": "#define CreateFile MyCreateFile\n\nHRESULT MyCreateFile(whatever the params are);\n #undef CreateFile\nHRESULT MyCreateFile(NobodyCanRememberParamListsLikeThat params)\n{\n if (InputIsNormalFile())\n CreateFile(params);\n else\n // do your thing\n}\n"
},
{
"answer_id": 62005,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 2,
"selected": false,
"text": "namespace Bluetooth\n{\n void CreateFile(/*params*/);\n void etc...\n}\n if (::CreateFile(...))\n{\n}\n if (Bluetooth::CreateFile(...))\n{\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2279145/"
] |
60,645 |
<p>Is it possible to use overlapped I/O with an anonymous pipe? CreatePipe() does not have any way of specifying FILE_FLAG_OVERLAPPED, so I assume ReadFile() will block, even if I supply an OVERLAPPED-structure. </p>
|
[
{
"answer_id": 419736,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "/******************************************************************************\\\n* This is a part of the Microsoft Source Code Samples. \n* Copyright 1995 - 1997 Microsoft Corporation.\n* All rights reserved. \n* This source code is only intended as a supplement to \n* Microsoft Development Tools and/or WinHelp documentation.\n* See these sources for detailed information regarding the \n* Microsoft samples programs.\n\\******************************************************************************/\n\n/*++\nCopyright (c) 1997 Microsoft Corporation\nModule Name:\n pipeex.c\nAbstract:\n CreatePipe-like function that lets one or both handles be overlapped\nAuthor:\n Dave Hart Summer 1997\nRevision History:\n--*/\n\n#include <windows.h>\n#include <stdio.h>\n\nstatic volatile long PipeSerialNumber;\n\nBOOL\nAPIENTRY\nMyCreatePipeEx(\n OUT LPHANDLE lpReadPipe,\n OUT LPHANDLE lpWritePipe,\n IN LPSECURITY_ATTRIBUTES lpPipeAttributes,\n IN DWORD nSize,\n DWORD dwReadMode,\n DWORD dwWriteMode\n )\n\n/*++\nRoutine Description:\n The CreatePipeEx API is used to create an anonymous pipe I/O device.\n Unlike CreatePipe FILE_FLAG_OVERLAPPED may be specified for one or\n both handles.\n Two handles to the device are created. One handle is opened for\n reading and the other is opened for writing. These handles may be\n used in subsequent calls to ReadFile and WriteFile to transmit data\n through the pipe.\nArguments:\n lpReadPipe - Returns a handle to the read side of the pipe. Data\n may be read from the pipe by specifying this handle value in a\n subsequent call to ReadFile.\n lpWritePipe - Returns a handle to the write side of the pipe. Data\n may be written to the pipe by specifying this handle value in a\n subsequent call to WriteFile.\n lpPipeAttributes - An optional parameter that may be used to specify\n the attributes of the new pipe. If the parameter is not\n specified, then the pipe is created without a security\n descriptor, and the resulting handles are not inherited on\n process creation. Otherwise, the optional security attributes\n are used on the pipe, and the inherit handles flag effects both\n pipe handles.\n nSize - Supplies the requested buffer size for the pipe. This is\n only a suggestion and is used by the operating system to\n calculate an appropriate buffering mechanism. A value of zero\n indicates that the system is to choose the default buffering\n scheme.\nReturn Value:\n TRUE - The operation was successful.\n FALSE/NULL - The operation failed. Extended error status is available\n using GetLastError.\n--*/\n\n{\n HANDLE ReadPipeHandle, WritePipeHandle;\n DWORD dwError;\n UCHAR PipeNameBuffer[ MAX_PATH ];\n\n //\n // Only one valid OpenMode flag - FILE_FLAG_OVERLAPPED\n //\n\n if ((dwReadMode | dwWriteMode) & (~FILE_FLAG_OVERLAPPED)) {\n SetLastError(ERROR_INVALID_PARAMETER);\n return FALSE;\n }\n\n //\n // Set the default timeout to 120 seconds\n //\n\n if (nSize == 0) {\n nSize = 4096;\n }\n\n sprintf( PipeNameBuffer,\n \"\\\\\\\\.\\\\Pipe\\\\RemoteExeAnon.%08x.%08x\",\n GetCurrentProcessId(),\n InterlockedIncrement(&PipeSerialNumber)\n );\n\n ReadPipeHandle = CreateNamedPipeA(\n PipeNameBuffer,\n PIPE_ACCESS_INBOUND | dwReadMode,\n PIPE_TYPE_BYTE | PIPE_WAIT,\n 1, // Number of pipes\n nSize, // Out buffer size\n nSize, // In buffer size\n 120 * 1000, // Timeout in ms\n lpPipeAttributes\n );\n\n if (! ReadPipeHandle) {\n return FALSE;\n }\n\n WritePipeHandle = CreateFileA(\n PipeNameBuffer,\n GENERIC_WRITE,\n 0, // No sharing\n lpPipeAttributes,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL | dwWriteMode,\n NULL // Template file\n );\n\n if (INVALID_HANDLE_VALUE == WritePipeHandle) {\n dwError = GetLastError();\n CloseHandle( ReadPipeHandle );\n SetLastError(dwError);\n return FALSE;\n }\n\n *lpReadPipe = ReadPipeHandle;\n *lpWritePipe = WritePipeHandle;\n return( TRUE );\n}\n"
},
{
"answer_id": 51448441,
"author": "RbMm",
"author_id": 6401656,
"author_profile": "https://Stackoverflow.com/users/6401656",
"pm_score": 4,
"selected": false,
"text": "CreatePipe Win32Pipes.%08x.%08x static LONG PipeSerialNumber;\n WCHAR name[64];\n swprintf(name, L\"\\\\Device\\\\NamedPipe\\\\Win32Pipes.%08x.%08x\", \n GetCurrentProcessId(), InterlockedIncrement(&PipeSerialNumber));\n CreatePipe ULONG CreatePipeAnonymousPair7(PHANDLE phServerPipe, PHANDLE phClientPipe)\n{\n HANDLE hNamedPipe;\n\n IO_STATUS_BLOCK iosb;\n\n static UNICODE_STRING NamedPipe = RTL_CONSTANT_STRING(L\"\\\\Device\\\\NamedPipe\\\\\");\n\n OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, const_cast<PUNICODE_STRING>(&NamedPipe), OBJ_CASE_INSENSITIVE };\n\n NTSTATUS status;\n\n if (0 <= (status = NtOpenFile(&hNamedPipe, SYNCHRONIZE, &oa, &iosb, FILE_SHARE_VALID_FLAGS, 0)))\n {\n oa.RootDirectory = hNamedPipe;\n\n static LARGE_INTEGER timeout = { 0, MINLONG };\n static UNICODE_STRING empty = {};\n\n oa.ObjectName = ∅\n\n if (0 <= (status = ZwCreateNamedPipeFile(phServerPipe,\n FILE_READ_ATTRIBUTES|FILE_READ_DATA|\n FILE_WRITE_ATTRIBUTES|FILE_WRITE_DATA|\n FILE_CREATE_PIPE_INSTANCE, \n &oa, &iosb, FILE_SHARE_READ|FILE_SHARE_WRITE,\n FILE_CREATE, 0, FILE_PIPE_BYTE_STREAM_TYPE, FILE_PIPE_BYTE_STREAM_MODE,\n FILE_PIPE_QUEUE_OPERATION, 1, 0, 0, &timeout)))\n {\n oa.RootDirectory = *phServerPipe;\n oa.Attributes = OBJ_CASE_INSENSITIVE|OBJ_INHERIT;\n\n if (0 > (status = NtOpenFile(phClientPipe, SYNCHRONIZE|FILE_READ_ATTRIBUTES|FILE_READ_DATA|\n FILE_WRITE_ATTRIBUTES|FILE_WRITE_DATA, &oa, &iosb, \n FILE_SHARE_VALID_FLAGS, FILE_SYNCHRONOUS_IO_NONALERT)))\n {\n NtClose(oa.RootDirectory);\n }\n }\n\n NtClose(hNamedPipe);\n }\n\n return RtlNtStatusToDosError(status);\n}\n\nULONG CreatePipeAnonymousPair(PHANDLE phServerPipe, PHANDLE phClientPipe)\n{\n static char flag_supported = -1;\n\n if (flag_supported < 0)\n {\n ULONG dwMajorVersion, dwMinorVersion;\n RtlGetNtVersionNumbers(&dwMajorVersion, &dwMinorVersion, 0);\n flag_supported = _WIN32_WINNT_WIN7 <= ((dwMajorVersion << 8)| dwMinorVersion);\n }\n\n if (flag_supported)\n {\n return CreatePipeAnonymousPair7(phServerPipe, phClientPipe);\n }\n\n static LONG PipeSerialNumber;\n\n WCHAR name[64];\n\n swprintf(name, L\"\\\\\\\\?\\\\pipe\\\\Win32Pipes.%08x.%08x\", GetCurrentProcessId(), InterlockedIncrement(&PipeSerialNumber));\n\n HANDLE hClient, hServer = CreateNamedPipeW(name, \n PIPE_ACCESS_DUPLEX|FILE_READ_DATA|FILE_WRITE_DATA|FILE_FLAG_OVERLAPPED, \n PIPE_TYPE_BYTE|PIPE_READMODE_BYTE, 1, 0, 0, 0, 0);\n\n if (hServer != INVALID_HANDLE_VALUE)\n {\n static SECURITY_ATTRIBUTES sa = { sizeof(sa), 0, TRUE };\n\n hClient = CreateFileW(name, FILE_GENERIC_READ|FILE_GENERIC_WRITE, \n FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, 0);\n\n if (hClient != INVALID_HANDLE_VALUE)\n {\n *phServerPipe = hServer, *phClientPipe = hClient;\n return NOERROR;\n }\n\n CloseHandle(hServer);\n }\n\n return GetLastError();\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3923/"
] |
60,649 |
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p>
<ul>
<li><strong>Cross platform</strong> (Win32 and Linux at least)</li>
<li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby, python, etc).</li>
<li>Finally, <strong>simple to use</strong> from a programming point of view!</li>
</ul>
<p>What my options are? I'm programming under Linux, but I'd like what I write to be portable to other OSes in the future. I've thought about using sockets, named pipes, or something like DBus.</p>
|
[
{
"answer_id": 25034401,
"author": "Peque",
"author_id": 3577054,
"author_profile": "https://Stackoverflow.com/users/3577054",
"pm_score": 3,
"selected": false,
"text": "inproc:// ipc:// {tcp|pgm|epgm}:// vmci://"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
] |
60,650 |
<p>Is it possible to to programmatically trigger a postback from server code in ASP.NET? I know that it is possible to do a Response.Redirect or Server.Transfer to redirect to a page, but is there a way to trigger a postback to the same page in server code (<em>i.e.</em> without using javascript trickery to submit a form)?</p>
|
[
{
"answer_id": 38018367,
"author": "Juls",
"author_id": 933511,
"author_profile": "https://Stackoverflow.com/users/933511",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Web;\nusing Microsoft.AspNet.SignalR;\nnamespace SignalRChat\n{\n public class ChatHub : Hub\n {\n public void Send(string name, string message)\n {\n // Call the broadcastMessage method to update clients.\n Clients.All.broadcastMessage(name, message);\n }\n }\n}\n <script type=\"text/javascript\">\n $(function () {\n // Declare a proxy to reference the hub. \n var chat = $.connection.chatHub;\n // Create a function that the hub can call to broadcast messages.\n chat.client.broadcastMessage = function (name, message) {\n // Html encode display name and message. \n var encodedName = $('<div />').text(name).html();\n var encodedMsg = $('<div />').text(message).html();\n // Add the message to the page. \n $('#discussion').append('<li><strong>' + encodedName\n + '</strong>: ' + encodedMsg + '</li>');\n };\n // Get the user name and store it to prepend to messages.\n $('#displayname').val(prompt('Enter your name:', ''));\n // Set initial focus to message input box. \n $('#message').focus();\n // Start the connection.\n $.connection.hub.start().done(function () {\n $('#sendmessage').click(function () {\n // Call the Send method on the hub. \n chat.server.send($('#displayname').val(), $('#message').val());\n // Clear text box and reset focus for next comment. \n $('#message').val('').focus();\n });\n });\n });\n </script>\n"
},
{
"answer_id": 43798658,
"author": "Fandango68",
"author_id": 2181188,
"author_profile": "https://Stackoverflow.com/users/2181188",
"pm_score": 0,
"selected": false,
"text": "Page.ClientScript.GetPostBackEventReference 'this.GetPostBackEventReference(...)' Page.ClientScript.RegisterStartupScript(..."
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4849/"
] |
60,653 |
<p>Is global memory initialized in C++? And if so, how?</p>
<p>(Second) clarification:</p>
<p>When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example.</p>
<p>The situation is: can a singleton reference be set - via an <code>instance()</code> call, prior to its initialization:</p>
<pre><code>MySingleton* MySingleton::_instance = NULL;
</code></pre>
<p>and get two singleton instances as a result?</p>
<p>See my C++ quiz on on multiple instances of a singleton...</p>
|
[
{
"answer_id": 60655,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": true,
"text": "int x;\n\nint main(int argc, char**argv)\n{\n assert(x == 0);\n int y;\n //assert(y == 0); <-- wrong can't assume this.\n}\n"
},
{
"answer_id": 60677,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "int x = 0;\n\nint main() { ... }\n int x;\n\nint main() { ... }\n #pragma data_seg"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2167252/"
] |
60,658 |
<p>In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic.</p>
<p>Please answer in the affirmative - With <em>Do put this here</em>, rather than <em>Don't put that there</em>.</p>
|
[
{
"answer_id": 63619,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "# app/controllers/foos_controller.rb:\nclass FoosController < ApplicationController\n\n def show\n @foo = Foo.find(...)\n end\n\nend\n\n#app/views/foos/show.html.erb:\n...\n<%= @foo.bar %>\n...\n # app/controllers/foos_controller.rb:\nclass FoosController < ApplicationController\n\n helper_method :foo\n\n def show\n end\n\n protected\n\n def foo\n @foo ||= Foo.find(...)\n end\n\nend\n\n#app/views/foos/show.html.erb:\n...\n<%= foo.bar %>\n...\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2167252/"
] |
60,664 |
<p>is it possible to display ⇓ entity in ie6? It is being display in every browser but not IE 6.I am writing markup such as: </p>
<pre><code><span>&#8659;</span>
</code></pre>
|
[
{
"answer_id": 60679,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 4,
"selected": true,
"text": "Symbol Character Numeric Description\n⇓ ⇓ ⇓ Down double arrow - - * Doesn't show with MS IE6\n"
},
{
"answer_id": 60688,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<span style=\"font-family:Arial Unicode MS\"> ⇓ </span>\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
60,672 |
<p>I want to implement an ISAPI filter like feature using HttpModule in IIS7 running under IIS Integrated Request Processing Pipeline mode.</p>
<p>The goal is to look at the incoming request at the Web Server level, and inject some custom HttpHeaders into the request. <code>(for ex: HTTP\_EAUTH\_ID)</code></p>
<p>And later in the page lifecycle of an ASPX page, i should be able to use that variable as</p>
<pre><code>string eauthId = Request.ServerVariables["HTTP\_EAUTH\_ID"].ToString();
</code></pre>
<p>So implementing this module at the Web Server level, is it possible to alter the ServerVariables collection ?? </p>
|
[
{
"answer_id": 61224,
"author": "Tyler",
"author_id": 5642,
"author_profile": "https://Stackoverflow.com/users/5642",
"pm_score": 0,
"selected": false,
"text": "HttpRequest.Headers HttpRequest.ServerVariables HttpContext.Current.Items\nHttpContext.Current.Response.Headers\n Request.Params, Request.QueryString, Request.Cookies, Request.Form"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647/"
] |
60,673 |
<p>What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people <em>insist</em> that every <code>if</code> statement is followed by a brace block (<code>{...}</code>).</p>
<p>I'm interested in what guidelines other people follow, and the reasons behind them. I'm also interested in guidelines that you think are rubbish, but are commonly held. Can anyone suggest a few?</p>
<p>To get the ball rolling, I'll mention a few to start with:</p>
<ul>
<li>Always use braces after every <code>if</code> / <code>else</code> statement (mentioned above). The rationale behind this is that it's not always easy to tell if a single statement is actually one statement, or a preprocessor macro that expands to more than one statement, so this code would break:</li>
</ul>
<pre>
// top of file:
#define statement doSomething(); doSomethingElse
// in implementation:
if (somecondition)
doSomething();
</pre>
<p>but if you use braces then it will work as expected.</p>
<ul>
<li>Use preprocessor macros for conditional compilation ONLY. preprocessor macros can cause all sorts of hell, since they don't allow C++ scoping rules. I've run aground many times due to preprocessor macros with common names in header files. If you're not careful you can cause all sorts of havoc!</li>
</ul>
<p>Now over to you.</p>
|
[
{
"answer_id": 60712,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 4,
"selected": true,
"text": "std::auto_ptr std::tr1::shared_ptr boost::shared_ptr boost::scoped_ptr"
},
{
"answer_id": 60715,
"author": "Brian Paden",
"author_id": 3176,
"author_profile": "https://Stackoverflow.com/users/3176",
"pm_score": 2,
"selected": false,
"text": "if( 12 == var )\n if( var == 12 )\n if( a == b ) something();\nif( b == d )\n{\n bigLongStringOfStuffThatWontFitOnASingleLineNeatly();\n}\n"
},
{
"answer_id": 60733,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 1,
"selected": false,
"text": "if(SomeVeryLongVaribleName != LongFunction(AnotherVarible, AString) &&\n BigVaribleIsValid(SomeVeryLongVaribleName))\n{\n DoSomething();\n}\n"
},
{
"answer_id": 60796,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "-Wall -Werror"
},
{
"answer_id": 64984,
"author": "Dave",
"author_id": 9056,
"author_profile": "https://Stackoverflow.com/users/9056",
"pm_score": 2,
"selected": false,
"text": "for(int i=0; i<=arr.length; i++) {\n arr[i].conf() //confirm that every username doesn't contain invalid characters\n}\n for(int i=0; i<=activeusers.length; i++) {\n activeusers[i].UsernameStripInvalidChars()\n}\n"
}
] |
2008/09/13
|
[
"https://Stackoverflow.com/questions/60673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.