qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
228,377
|
<p>I want to run a psychological study for which participants have to look at large images.</p>
<p>The experiment is done on the web and therefore in a browser window. Is it possible to tell the browser to go into fullscreen, for example on button press?</p>
<p>I know there is the possibility to open a fixed-size popup window. Do you think this would be a feasable alternative? And if, what would be the best way to do it? Are there elegant ways of detecting a popup-blocker, to fallback and run the study in the original browser window.</p>
<p>The main concern is that the participants of this study are not familiar with technical details and should not be bothered by them.</p>
|
[
{
"answer_id": 228390,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\">\n<!--\nfunction popup(url) \n{\n params = 'width='+screen.width;\n params += ', height='+screen.height;\n params += ', top=0, left=0'\n params += ', fullscreen=yes';\n\n newwin=window.open(url,'windowname4', params);\n if (window.focus) {newwin.focus()}\n return false;\n}\n// -->\n</script>\n\n<a href=\"javascript: void(0)\" \n onclick=\"popup('popup.html')\">Fullscreen popup window</a>\n"
},
{
"answer_id": 228414,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 2,
"selected": false,
"text": "<script>\n<!--\nwindow.open(\"page.html\",\"fs\",\"fullscreen,scrollbars\")\n//-->\n</script> \n <a href=\"#\" onclick=\"window.close()\">Close Window</a>\n"
},
{
"answer_id": 228422,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "window.opener.location.href = '/confirmation/page.html';\n"
},
{
"answer_id": 20643560,
"author": "Swen",
"author_id": 2387714,
"author_profile": "https://Stackoverflow.com/users/2387714",
"pm_score": 4,
"selected": true,
"text": "function fullscreen() {\n var element = document.getElementById(\"content\");\n if (element.requestFullScreen) {\n if (!document.fullScreen) {\n element.requestFullscreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize_actual.png\");\n } else {\n document.exitFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize.png\");\n }\n\n } else if (element.mozRequestFullScreen) {\n\n if (!document.mozFullScreen) {\n element.mozRequestFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize_actual.png\");\n google.maps.event.trigger(map, 'resize');\n } else {\n document.mozCancelFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize.png\");\n }\n\n } else if (element.webkitRequestFullScreen) {\n\n if (!document.webkitIsFullScreen) {\n element.webkitRequestFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize_actual.png\");\n google.maps.event.trigger(map, 'resize');\n } else {\n document.webkitCancelFullScreen();\n $(\".fullscreen\").attr('src',\"img/icons/panel_resize.png\");\n } \n } \n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21974/"
] |
228,404
|
<p>I'm writing in second-person just because its easy, for you. </p>
<p>You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.</p>
<p>So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?</p>
<p>So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."</p>
<p>Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?</p>
|
[
{
"answer_id": 228546,
"author": "Tom Barta",
"author_id": 29839,
"author_profile": "https://Stackoverflow.com/users/29839",
"pm_score": 4,
"selected": true,
"text": "std::string"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168235/"
] |
228,424
|
<p>I have the following query:</p>
<pre><code>SELECT c.*
FROM companies AS c
JOIN users AS u USING(companyid)
JOIN jobs AS j USING(userid)
JOIN useraccounts AS us USING(userid)
WHERE j.jobid = 123;
</code></pre>
<p>I have the following questions:</p>
<ol>
<li>Is the USING syntax synonymous with ON syntax?</li>
<li>Are these joins evaluated left to right? In other words, does this query say: x = companies JOIN users; y = x JOIN jobs; z = y JOIN useraccounts;</li>
<li>If the answer to question 2 is yes, is it safe to assume that the companies table has companyid, userid and jobid columns?</li>
<li>I don't understand how the WHERE clause can be used to pick rows on the companies table when it is referring to the alias "j"</li>
</ol>
<p>Any help would be appreciated!</p>
|
[
{
"answer_id": 228473,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 0,
"selected": false,
"text": "SELECT c.*\nFROM companies AS c \n JOIN (SELECT * FROM users AS u \n JOIN (SELECT * FROM jobs AS j USING(userid) \n JOIN useraccounts AS us USING(userid) \n WHERE j.jobid = 123)\n )\n"
},
{
"answer_id": 228517,
"author": "Dave K",
"author_id": 19864,
"author_profile": "https://Stackoverflow.com/users/19864",
"pm_score": 0,
"selected": false,
"text": "SELECT c.* \n FROM companies AS c \n JOIN users AS u USING(companyid) \n JOIN jobs AS j USING(userid) \n JOIN useraccounts AS us USING(userid) \nWHERE j.jobid = 123\n SELECT c.* \n FROM companies AS c \n JOIN users AS u on u.companyid = c.companyid\n JOIN jobs AS j on j.userid = u.userid\n JOIN useraccounts AS us on us.userid = u.userid \nWHERE j.jobid = 123\n SELECT c.* \n FROM companies AS c \n JOIN users AS u on u.companyid = c.companyid\n JOIN jobs AS j on j.userid = c.userid\n JOIN useraccounts AS us on us.userid = c.userid\nWHERE j.jobid = 123\n SELECT c.*, j.jobid.... \n"
},
{
"answer_id": 750425,
"author": "NickZoic",
"author_id": 90927,
"author_profile": "https://Stackoverflow.com/users/90927",
"pm_score": 2,
"selected": false,
"text": "EXPLAIN SELECT [...]\n"
},
{
"answer_id": 48120937,
"author": "William Entriken",
"author_id": 300224,
"author_profile": "https://Stackoverflow.com/users/300224",
"pm_score": 0,
"selected": false,
"text": "JOIN JOIN CREATE TABLE users (\n name text\n);\n\nCREATE TABLE orders (\n order_id text,\n user_name text\n);\n\nCREATE TABLE shipments (\n order_id text,\n fulfiller text\n);\n INSERT INTO users VALUES ('Bob'), ('Mary');\n\nINSERT INTO orders VALUES ('order1', 'Bob');\n\nINSERT INTO shipments VALUES ('order1', 'Fulfilling Mary');\n SELECT *\n FROM users\n LEFT OUTER JOIN orders\n ON orders.user_name = users.name\n JOIN shipments\n ON shipments.order_id = orders.order_id\n LEFT OUTER JOIN JOIN LEFT OUTER JOIN SELECT *\n FROM users\n LEFT OUTER JOIN (\n orders\n JOIN shipments\n ON shipments.order_id = orders.order_id)\n ON orders.user_name = users.name\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056/"
] |
228,441
|
<p>I am working on rails project and I am trying to get exceptions to be logged to the rails log files. I know I can call <code>logger.error $!</code> to get the first line of the exception logged to the file. But, I want to get the entire trace stack logged as well. How do I log the entire trace back of an exception using the default rails logger?</p>
|
[
{
"answer_id": 228467,
"author": "Redbeard",
"author_id": 14977,
"author_profile": "https://Stackoverflow.com/users/14977",
"pm_score": 3,
"selected": false,
"text": "logger.error caller.join(\"\\n\")"
},
{
"answer_id": 236350,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 6,
"selected": true,
"text": "logger.error $!.backtrace\n rescue ErrorType => error_name\n $!"
},
{
"answer_id": 237846,
"author": "Matt Burke",
"author_id": 29691,
"author_profile": "https://Stackoverflow.com/users/29691",
"pm_score": 4,
"selected": false,
"text": "137 logger.fatal(\n138 \"\\n\\n#{exception.class} (#{exception.message}):\\n \" +\n139 clean_backtrace(exception).join(\"\\n \") +\n140 \"\\n\\n\"\n141 )\n\n248 def clean_backtrace(exception)\n249 if backtrace = exception.backtrace\n250 if defined?(RAILS_ROOT)\n251 backtrace.map { |line| line.sub RAILS_ROOT, '' }\n252 else\n253 backtrace\n254 end\n255 end\n256 end\n"
},
{
"answer_id": 308239,
"author": "Priit",
"author_id": 22964,
"author_profile": "https://Stackoverflow.com/users/22964",
"pm_score": 2,
"selected": false,
"text": "ActionController::Rescue log_error def foo_action\n # break something in here\nrescue\n log_error($!)\n # call firemen\nend\n"
},
{
"answer_id": 1527404,
"author": "mxgrn",
"author_id": 103160,
"author_profile": "https://Stackoverflow.com/users/103160",
"pm_score": 3,
"selected": false,
"text": "# Rails.backtrace_cleaner.remove_silencers!\n"
},
{
"answer_id": 50532336,
"author": "user3223833",
"author_id": 3223833,
"author_profile": "https://Stackoverflow.com/users/3223833",
"pm_score": 1,
"selected": false,
"text": "logger.error \"Your error message. Exception message:#{$!} Stacktrace:#{$@}\"\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
228,476
|
<p>Taking over some code from my predecessor and I found a query that uses the Like operator:</p>
<pre><code>SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';
</code></pre>
<p>Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?</p>
<p>note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.</p>
|
[
{
"answer_id": 228488,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM suppliers WHERE supplier_name like '%' + @name + '%'\n"
},
{
"answer_id": 228490,
"author": "vdhant",
"author_id": 30572,
"author_profile": "https://Stackoverflow.com/users/30572",
"pm_score": -1,
"selected": false,
"text": "sql=\"Insert into Employees (Firstname, Lastname, City, State, Zip, Phone, Email) Values ('\" & frmFirstname.text & \"', '\" & frmLastName & \"', '\" & frmCity & \"', '\" & frmState & \"', '\" & frmZip & \"', '\" & frmPhone & \"', '\" & frmEmail & \"')\"\n Dim MySQL as string = \"Insert into NewEmp (fname, LName, Address, City, State, Postalcode, Phone, Email) Values (@Firstname, @LastName, @Address, @City, @State, @Postalcode, @Phone, @Email)\" \n\nWith cmd.Parameters:\n .Add(New SQLParameter(\"@Firstname\", frmFname.text))\n .Add(New SQLParameter(\"@LastName\", frmLname.text))\n .Add(New SQLParameter(\"@Address\", frmAddress.text))\n .Add(New SQLParameter(\"@City\", frmCity.text))\n .Add(New SQLParameter(\"@state\", frmState.text))\n .Add(New SQLParameter(\"@Postalcode\", frmPostalCode.Text))\n .Add(New SQLParameter(\"@Phone\", frmPhone.text))\n .Add(New SQLParameter(\"@email\", frmemail.text))\nend with\n"
},
{
"answer_id": 228491,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 5,
"selected": true,
"text": "var query = \"select * from foo where name like @searchterm\";\nusing (var command = new SqlCommand(query, connection))\n{\n command.Parameters.AddWithValue(\"@searchterm\", String.Format(\"%{0}%\", searchTerm));\n var result = command.ExecuteReader();\n}\n"
},
{
"answer_id": 47334937,
"author": "Mehmet Recep Yildiz",
"author_id": 2358794,
"author_profile": "https://Stackoverflow.com/users/2358794",
"pm_score": 0,
"selected": false,
"text": "List<Person> peopleList = contex.People.SqlQuery(\n @\"SELECT * FROM [Person].[Person]\n WHERE [FirstName] LIKE N'%' + @p0 + '%' \", \"ab\").ToList();\n List<Person> peopleList = contex.People.SqlQuery(\n @\"SELECT * FROM [Person].[Person]\n WHERE [FirstName] LIKE N'%' + @name + '%' \",\n new SqlParameter(\"@name\", \"ab\")).ToList();\n List<Person> peopleList1 = contex.People.Where(s => s.FirstName.Contains(\"ab\")).ToList();\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
] |
228,477
|
<p>I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?</p>
|
[
{
"answer_id": 228481,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 10,
"selected": true,
"text": "System.getProperty(\"os.name\")\n class ShowProperties {\n public static void main(String[] args) {\n System.getProperties().list(System.out);\n }\n}\n"
},
{
"answer_id": 228499,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 7,
"selected": false,
"text": "public static final class OsUtils\n{\n private static String OS = null;\n public static String getOsName()\n {\n if(OS == null) { OS = System.getProperty(\"os.name\"); }\n return OS;\n }\n public static boolean isWindows()\n {\n return getOsName().startsWith(\"Windows\");\n }\n\n public static boolean isUnix() // and so on\n}\n"
},
{
"answer_id": 2917718,
"author": "Leif Carlsen",
"author_id": 233317,
"author_profile": "https://Stackoverflow.com/users/233317",
"pm_score": 8,
"selected": false,
"text": "SystemUtils.IS_OS_WINDOWS"
},
{
"answer_id": 16278800,
"author": "Vishal Chaudhari",
"author_id": 1856449,
"author_profile": "https://Stackoverflow.com/users/1856449",
"pm_score": 3,
"selected": false,
"text": "String osName = System.getProperty(\"os.name\");\nSystem.out.println(\"Operating system \" + osName);\n"
},
{
"answer_id": 17506150,
"author": "Nikesh Jauhari",
"author_id": 1964633,
"author_profile": "https://Stackoverflow.com/users/1964633",
"pm_score": 4,
"selected": false,
"text": "class import java.util.Locale;\n\npublic class OperatingSystem\n{\n private static String OS = System.getProperty(\"os.name\", \"unknown\").toLowerCase(Locale.ROOT);\n\n public static boolean isWindows()\n {\n return OS.contains(\"win\");\n }\n\n public static boolean isMac()\n {\n return OS.contains(\"mac\");\n }\n\n public static boolean isUnix()\n {\n return OS.contains(\"nux\");\n }\n}\n class"
},
{
"answer_id": 18417382,
"author": "Wolfgang Fahl",
"author_id": 1497139,
"author_profile": "https://Stackoverflow.com/users/1497139",
"pm_score": 6,
"selected": false,
"text": "OsCheck.OSType ostype=OsCheck.getOperatingSystemType();\nswitch (ostype) {\n case Windows: break;\n case MacOS: break;\n case Linux: break;\n case Other: break;\n}\n /**\n * helper class to check the operating system this Java VM runs in\n *\n * please keep the notes below as a pseudo-license\n *\n * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java\n * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java\n * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html\n */\nimport java.util.Locale;\npublic static final class OsCheck {\n /**\n * types of Operating Systems\n */\n public enum OSType {\n Windows, MacOS, Linux, Other\n };\n\n // cached result of OS detection\n protected static OSType detectedOS;\n\n /**\n * detect the operating system from the os.name System property and cache\n * the result\n * \n * @returns - the operating system detected\n */\n public static OSType getOperatingSystemType() {\n if (detectedOS == null) {\n String OS = System.getProperty(\"os.name\", \"generic\").toLowerCase(Locale.ENGLISH);\n if ((OS.indexOf(\"mac\") >= 0) || (OS.indexOf(\"darwin\") >= 0)) {\n detectedOS = OSType.MacOS;\n } else if (OS.indexOf(\"win\") >= 0) {\n detectedOS = OSType.Windows;\n } else if (OS.indexOf(\"nux\") >= 0) {\n detectedOS = OSType.Linux;\n } else {\n detectedOS = OSType.Other;\n }\n }\n return detectedOS;\n }\n}\n"
},
{
"answer_id": 22453323,
"author": "TacB0sS",
"author_id": 348189,
"author_profile": "https://Stackoverflow.com/users/348189",
"pm_score": 2,
"selected": false,
"text": "/**\n * types of Operating Systems\n *\n * please keep the note below as a pseudo-license\n *\n * helper class to check the operating system this Java VM runs in\n * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java\n * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java\n * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html\n */\npublic enum OSType {\n MacOS(\"mac\", \"darwin\"),\n Windows(\"win\"),\n Linux(\"nux\"),\n Other(\"generic\");\n\n private static OSType detectedOS;\n\n private final String[] keys;\n\n private OSType(String... keys) {\n this.keys = keys;\n }\n\n private boolean match(String osKey) {\n for (int i = 0; i < keys.length; i++) {\n if (osKey.indexOf(keys[i]) != -1)\n return true;\n }\n return false;\n }\n\n public static OSType getOS_Type() {\n if (detectedOS == null)\n detectedOS = getOperatingSystemType(System.getProperty(\"os.name\", Other.keys[0]).toLowerCase());\n return detectedOS;\n }\n\n private static OSType getOperatingSystemType(String osKey) {\n for (OSType osType : values()) {\n if (osType.match(osKey))\n return osType;\n }\n return Other;\n }\n}\n"
},
{
"answer_id": 23512457,
"author": "Kamidu",
"author_id": 3603020,
"author_profile": "https://Stackoverflow.com/users/3603020",
"pm_score": 4,
"selected": false,
"text": "System.getProperty(\"os.name\");\nSystem.getProperty(\"os.version\");\nSystem.getProperty(\"os.arch\");\n"
},
{
"answer_id": 25078556,
"author": "ShinnedHawks",
"author_id": 3068728,
"author_profile": "https://Stackoverflow.com/users/3068728",
"pm_score": 2,
"selected": false,
"text": "public static void main(String[] args) {\n // TODO Auto-generated method stub\n Properties pro = System.getProperties();\n for(Object obj : pro.keySet()){\n System.out.println(\" System \"+(String)obj+\" : \"+System.getProperty((String)obj));\n }\n}\n"
},
{
"answer_id": 30012452,
"author": "PAA",
"author_id": 2929562,
"author_profile": "https://Stackoverflow.com/users/2929562",
"pm_score": 3,
"selected": false,
"text": "public class App {\n public static void main( String[] args ) {\n //Operating system name\n System.out.println(System.getProperty(\"os.name\"));\n\n //Operating system version\n System.out.println(System.getProperty(\"os.version\"));\n\n //Path separator character used in java.class.path\n System.out.println(System.getProperty(\"path.separator\"));\n\n //User working directory\n System.out.println(System.getProperty(\"user.dir\"));\n\n //User home directory\n System.out.println(System.getProperty(\"user.home\"));\n\n //User account name\n System.out.println(System.getProperty(\"user.name\"));\n\n //Operating system architecture\n System.out.println(System.getProperty(\"os.arch\"));\n\n //Sequence used by operating system to separate lines in text files\n System.out.println(System.getProperty(\"line.separator\"));\n\n System.out.println(System.getProperty(\"java.version\")); //JRE version number\n\n System.out.println(System.getProperty(\"java.vendor.url\")); //JRE vendor URL\n\n System.out.println(System.getProperty(\"java.vendor\")); //JRE vendor name\n\n System.out.println(System.getProperty(\"java.home\")); //Installation directory for Java Runtime Environment (JRE)\n\n System.out.println(System.getProperty(\"java.class.path\"));\n\n System.out.println(System.getProperty(\"file.separator\"));\n }\n}\n Windows 7\n6.1\n;\nC:\\Users\\user\\Documents\\workspace-eclipse\\JavaExample\nC:\\Users\\user\nuser\namd64\n\n\n1.7.0_71\nhttp://java.oracle.com/\nOracle Corporation\nC:\\Program Files\\Java\\jre7\nC:\\Users\\user\\Documents\\workspace-Eclipse\\JavaExample\\target\\classes\n\\\n"
},
{
"answer_id": 31547504,
"author": "Memin",
"author_id": 2234161,
"author_profile": "https://Stackoverflow.com/users/2234161",
"pm_score": 5,
"selected": false,
"text": "System.getProperty(\"os.name\") public class Util { \n public enum OS {\n WINDOWS, LINUX, MAC, SOLARIS\n };// Operating systems.\n\n private static OS os = null;\n\n public static OS getOS() {\n if (os == null) {\n String operSys = System.getProperty(\"os.name\").toLowerCase();\n if (operSys.contains(\"win\")) {\n os = OS.WINDOWS;\n } else if (operSys.contains(\"nix\") || operSys.contains(\"nux\")\n || operSys.contains(\"aix\")) {\n os = OS.LINUX;\n } else if (operSys.contains(\"mac\")) {\n os = OS.MAC;\n } else if (operSys.contains(\"sunos\")) {\n os = OS.SOLARIS;\n }\n }\n return os;\n }\n}\n switch (Util.getOS()) {\n case WINDOWS:\n //do windows stuff\n break;\n case LINUX:\n"
},
{
"answer_id": 41174417,
"author": "Ihor Rybak",
"author_id": 5810648,
"author_profile": "https://Stackoverflow.com/users/5810648",
"pm_score": 6,
"selected": false,
"text": "if (PlatformUtil.isWindows()){\n ...\n}\n"
},
{
"answer_id": 52531796,
"author": "Nafeez Quraishi",
"author_id": 5916535,
"author_profile": "https://Stackoverflow.com/users/5916535",
"pm_score": 3,
"selected": false,
"text": "import org.apache.commons.exec.OS;\n\nif (OS.isFamilyWindows()){\n //load some property\n }\nelse if (OS.isFamilyUnix()){\n //load some other property\n }\n"
},
{
"answer_id": 56142476,
"author": "Vladimir Vaschenko",
"author_id": 5300967,
"author_profile": "https://Stackoverflow.com/users/5300967",
"pm_score": 0,
"selected": false,
"text": "Platform.isWindows();\nPlatform.is64Bit();\nPlatform.isIntel();\nPlatform.isARM();\n <dependency>\n <groupId>net.java.dev.jna</groupId>\n <artifactId>jna</artifactId>\n <version>5.2.0</version>\n</dependency>\n"
},
{
"answer_id": 56869353,
"author": "itro",
"author_id": 1092450,
"author_profile": "https://Stackoverflow.com/users/1092450",
"pm_score": -1,
"selected": false,
"text": "com.sun.javafx.util.Utils if ( Utils.isWindows()){\n // LOGIC HERE\n}\n boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);\n if (isWindows){\n // YOUR LOGIC HERE\n }\n"
},
{
"answer_id": 57616565,
"author": "Theikon",
"author_id": 11173058,
"author_profile": "https://Stackoverflow.com/users/11173058",
"pm_score": 3,
"selected": false,
"text": "System#getProperty(String) os.arch os.name os.version System#setProperty(String, String) SecurityManager JAR -Dos.name= -Dos.arch= RuntimeMXBean RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();\nList<String> arguments = runtimeMxBean.getInputArguments();\n\nfor (String argument : arguments) {\n if (argument.startsWith(\"-Dos.name\") {\n // System.getProperty(\"os.name\") altered\n } else if (argument.startsWith(\"-Dos.arch\") {\n // System.getProperty(\"os.arch\") altered\n }\n}\n"
},
{
"answer_id": 67864441,
"author": "Hristo Stoyanov",
"author_id": 3610608,
"author_profile": "https://Stackoverflow.com/users/3610608",
"pm_score": 3,
"selected": false,
"text": "switch(OSType.DETECTED){\n...\n}\n public enum OSType {\n Windows, MacOS, Linux, Other;\n public static final OSType DETECTED;\n static{\n String OS = System.getProperty(\"os.name\", \"generic\").toLowerCase(Locale.ENGLISH);\n if ((OS.contains(\"mac\")) || (OS.contains(\"darwin\"))) {\n DETECTED = OSType.MacOS;\n } else if (OS.contains(\"win\")) {\n DETECTED = OSType.Windows;\n } else if (OS.contains(\"nux\")) {\n DETECTED = OSType.Linux;\n } else {\n DETECTED = OSType.Other;\n }\n }\n}\n"
},
{
"answer_id": 68681632,
"author": "nima",
"author_id": 536226,
"author_profile": "https://Stackoverflow.com/users/536226",
"pm_score": -1,
"selected": false,
"text": "private var _osType: OsTypes? = null\nval osType: OsTypes\n get() {\n if (_osType == null) {\n _osType = with(System.getProperty(\"os.name\").lowercase(Locale.getDefault())) {\n if (contains(\"win\"))\n OsTypes.WINDOWS\n else if (listOf(\"nix\", \"nux\", \"aix\").any { contains(it) })\n OsTypes.LINUX\n else if (contains(\"mac\"))\n OsTypes.MAC\n else if (contains(\"sunos\"))\n OsTypes.SOLARIS\n else\n OsTypes.OTHER\n }\n }\n return _osType!!\n }\n\nenum class OsTypes {\n WINDOWS, LINUX, MAC, SOLARIS, OTHER\n}\n"
},
{
"answer_id": 71930717,
"author": "ShahzadIftikhar",
"author_id": 6690544,
"author_profile": "https://Stackoverflow.com/users/6690544",
"pm_score": -1,
"selected": false,
"text": "Platform.getOS()\n if (Platform.getOS().equals(Platform.OS_LINUX)) {\n}\n org.eclipse.core.runtime"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318/"
] |
228,518
|
<p>The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in <b>Python</b>:</p>
<pre><code>R=lambda s:all(a==b for a,b in zip(s,reversed(s)))
</code></pre>
<p>50 characters.</p>
<p>The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.</p>
|
[
{
"answer_id": 228526,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 5,
"selected": false,
"text": "p\n xor %eax, %eax\nmov %esi, %edi\n#cld not necessary, assume DF=0 as per x86 ABI\nrepne scasb\nscan:\n dec %edi\n cmpsb\n .byte 0x75, 6 #jnz (short) done\n dec %edi\n cmp %esi, %edi\n .byte 0x72, -9 #jb (short) scan\ninc %eax\ndone:\n"
},
{
"answer_id": 228530,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "P(char*s){char*e=s+strlen(s)-1;while(s<e&&*s==*e)s++,e--;return s>=e;}\n"
},
{
"answer_id": 228535,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 5,
"selected": false,
"text": "R=lambda s:s==s[::-1]\n"
},
{
"answer_id": 228543,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "sub p{$_[0]eq reverse$_[0]}\n def p(a)a==a.reverse end\n"
},
{
"answer_id": 228678,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": "boolean p(String s){return s.equals(\"\"+new StringBuffer(s).reverse());}\n"
},
{
"answer_id": 228685,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 3,
"selected": false,
"text": "(equal p (reverse p))\n (defun g () (equal p (reverse p)))\n"
},
{
"answer_id": 228727,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 5,
"selected": false,
"text": "p=ap(==)reverse\n p x=x==reverse x\n"
},
{
"answer_id": 228740,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 2,
"selected": false,
"text": "function p($s){return $s==strrev($s);} // 38 chars\n $s==strrev($s); // 15 chars\n"
},
{
"answer_id": 229562,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "function y(x){return(x is reverse(x));}\n"
},
{
"answer_id": 229608,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 0,
"selected": false,
"text": "boolean y(StringBuffer x){return x.equals(x.reverse());}\n boolean y(StringBuffer x){return x.toString().equals(x.reverse().toString()); }\n"
},
{
"answer_id": 229610,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "p=uncurry(==).(id&&&reverse)\n"
},
{
"answer_id": 229626,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "function p(s)return s==s:reverse()end\n p=function(s)return s==s:reverse''end\n function p(s){return s==s.split('').reverse().join('')}\n"
},
{
"answer_id": 230113,
"author": "Sundar R",
"author_id": 8127,
"author_profile": "https://Stackoverflow.com/users/8127",
"pm_score": 2,
"selected": false,
"text": "p(char*s){char*r=strdup(s);strrev(r);return strcmp(r,s);}\n p(char*s){char*r=strdup(s);s[0]=strcmp(strrev(r),s);free(r);return s[0];}\n"
},
{
"answer_id": 230294,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "#include int p(char*a,char*b=0,char*c=0){return c?b<a||p(a+1,--b,c)&&*a==*b:b&&*b?p(a,b+1):p(a,b?b:a,b);}\n"
},
{
"answer_id": 231080,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "test \"`echo $1|sed -e 's/\\(.\\)/\\1\\n/g'|tac|tr -d '\\n'`\" == \"$1\"\n"
},
{
"answer_id": 231391,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 7,
"selected": true,
"text": "p=:-:|.\n p 'radar'\n1\n\np 'moose'\n0\n"
},
{
"answer_id": 231476,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "def p(a)a==a.reverse end\n def p(a)a==a.r end\n def m(a)a==a.split('').inject{|r,l|l+r}end\n Function P(ByVal S As String) As Boolean\n For i As Integer = 0 To S.Length - 1\n If S(i) <> S(S.Length - i - 1) Then\n Return False\n End If\n Next\n Return True\nEnd Function\n"
},
{
"answer_id": 231639,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 2,
"selected": false,
"text": "int p(char[]s){int i=0,l=s.Length,t=1;while(++i<l)if(s[i]!=s[l-i-1])t&=0;return t;} \n int p(char[]s){int i=0;int l=s.Length;while(++i<l)if(s[i]!=s[l-i-1])return 0;return 1;}\n function p:p=s=strreverse(s):end function\n"
},
{
"answer_id": 231685,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 0,
"selected": false,
"text": "sub p{return @_==reverse split//;}\n"
},
{
"answer_id": 232360,
"author": "matyr",
"author_id": 15066,
"author_profile": "https://Stackoverflow.com/users/15066",
"pm_score": 2,
"selected": false,
"text": "p={it==it[-1..0]}"
},
{
"answer_id": 232440,
"author": "nyxtom",
"author_id": 19753,
"author_profile": "https://Stackoverflow.com/users/19753",
"pm_score": 2,
"selected": false,
"text": "let p s=let i=0;let l=s.Length;while(++i<l)if(s[i]!=[l-i-1]) 0; 1;;\n"
},
{
"answer_id": 232615,
"author": "Steven Dee",
"author_id": 31077,
"author_profile": "https://Stackoverflow.com/users/31077",
"pm_score": 3,
"selected": false,
"text": "p=ap(==)reverse\n"
},
{
"answer_id": 232952,
"author": "Figo",
"author_id": 12661,
"author_profile": "https://Stackoverflow.com/users/12661",
"pm_score": 3,
"selected": false,
"text": "main(int n,char**v){char*b,*e;b=e=v[1];while(*++e);for(e--;*b==*e&&b++<e--;);return b>e;}\n"
},
{
"answer_id": 233108,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "#L(equal !1(reverse !1))\n (defun p (s)\n (let ((l (1- (length s))))\n (iter (for i from l downto (/ l 2))\n (always (equal (elt s i) (elt s (- l i)))))))\n"
},
{
"answer_id": 233872,
"author": "OdeToCode",
"author_id": 17210,
"author_profile": "https://Stackoverflow.com/users/17210",
"pm_score": 4,
"selected": false,
"text": "public bool IsPalindrome(string s)\n{\n return s.Reverse().SequenceEqual(s);\n}\n public bool IsPalindrome(string s)\n{\n return s.Aggregate(new StringBuilder(),\n (sb, c) => sb.Insert(0, c),\n (sb) => sb.ToString() == s);\n}\n"
},
{
"answer_id": 235821,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "user=> (defn p[s](=(seq s)(reverse(seq s))))\n#'user/p\nuser=> (p \"radar\")\ntrue\nuser=> (p \"moose\")\nfalse\n"
},
{
"answer_id": 235864,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 0,
"selected": false,
"text": "p(char*a){char*b=a-1;while(*++b);while(a<b&&*a++==*--b);return!(a<b);}\n int"
},
{
"answer_id": 235870,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "sub p{$_[0]eq+reverse@_}\n"
},
{
"answer_id": 237017,
"author": "Jasper Bekkers",
"author_id": 31486,
"author_profile": "https://Stackoverflow.com/users/31486",
"pm_score": 2,
"selected": false,
"text": "p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++!=*--b;return!q;}\n p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++%*--b;return!q;}\n p(char*a){char*b=a;while(*b)b++;while(*a&&*a++==*--b);return!*a;}\n"
},
{
"answer_id": 237420,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "p=function(x){return (x==x.split('').reverse().join())}\n join \"\" function p(s){return s==s.split(\"\").reverse().join(\"\")}\n"
},
{
"answer_id": 237577,
"author": "Skip Head",
"author_id": 23271,
"author_profile": "https://Stackoverflow.com/users/23271",
"pm_score": 0,
"selected": false,
"text": "boolean p(String s){int i=0,l=s.length();while(i<l){if(s.charAt(i++)!=s.charAt(--l))l=-1;}return l>=0;\n"
},
{
"answer_id": 237665,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 0,
"selected": false,
"text": "fun p s=s=implode(rev(explode(s)))\n"
},
{
"answer_id": 239501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "p(char *s){char *e=s;while(*++e);for(;*s==*--e&&s++<e;);return s>e;}\n"
},
{
"answer_id": 471849,
"author": "gnovice",
"author_id": 52738,
"author_profile": "https://Stackoverflow.com/users/52738",
"pm_score": 2,
"selected": false,
"text": "R=@(s)all(s==fliplr(s));\n"
},
{
"answer_id": 471869,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "bool p(const std::string &s){std::string s2(s);std::reverse(s2);return s==s2;}\n bool p(std::string s){std::string x=s;std::reverse(x);return s==x;}\n"
},
{
"answer_id": 472245,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "r[]y=y\nr(a:x)y=r x$a:y\np s=s==r s[]\n"
},
{
"answer_id": 1605617,
"author": "Eric Strom",
"author_id": 189416,
"author_profile": "https://Stackoverflow.com/users/189416",
"pm_score": 2,
"selected": false,
"text": "/^(.?|(.)(?1)\\2)$/\n"
},
{
"answer_id": 2324017,
"author": "Deadcode",
"author_id": 161468,
"author_profile": "https://Stackoverflow.com/users/161468",
"pm_score": 2,
"selected": false,
"text": "p(char*s){return!*s||!(s[strlen(s)-1]-=*s)&&p(++s);} p(char*s){char*e=s;while(*e)++e;return!*s||!(*--e-=*s)&&p(++s);}"
},
{
"answer_id": 2324146,
"author": "Sean",
"author_id": 182693,
"author_profile": "https://Stackoverflow.com/users/182693",
"pm_score": 1,
"selected": false,
"text": "sub{\"@_\"eq reverse@_}\n"
},
{
"answer_id": 3539899,
"author": "FishyFingers",
"author_id": 427410,
"author_profile": "https://Stackoverflow.com/users/427410",
"pm_score": 0,
"selected": false,
"text": "function p(s){l=s.length;return l<2||(s[0]==s[l-1]&&p(s.substr(1,l-2)))}\n p=function(s,y){return y?(s==p(s)):s[1]?(p(s.substr(1))+s[0]):s[0]}\n\np(\"hannah\",1);\n p=function(s,y,i){\nreturn i?s[i]?s[i]+p(s,0,i+1):'':y?(s==p(s)):s[1]?(p(p(s,0,1))+s[0]):s[0]\n}\n\np(\"hannah\",1);\n function p(s,l){for(c in s){if(s[c]!=s[l-1-c])s=0}return s}\n\np(\"hannah\",6);// (is this cheating?)\n"
},
{
"answer_id": 3886155,
"author": "mob",
"author_id": 168657,
"author_profile": "https://Stackoverflow.com/users/168657",
"pm_score": 2,
"selected": false,
"text": ".-1%=\n\n$ echo -n abacaba | ruby golfscript.rb palindrome.gs\n1\n\n$ echo -n deadbeef | ruby golfscript.rb palindrome.gs\n0\n"
},
{
"answer_id": 3886306,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 0,
"selected": false,
"text": "let p(s:string)=s=s.Reverse()\n"
},
{
"answer_id": 3894687,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 0,
"selected": false,
"text": "Reverse Func<string,bool>p=null;p=w=>{if(w.Length<2)return true;return w[0]==w[w.Length-1]&&p(w.Substring(1,w.Length-2));};\n"
},
{
"answer_id": 3894868,
"author": "Jack",
"author_id": 121747,
"author_profile": "https://Stackoverflow.com/users/121747",
"pm_score": 0,
"selected": false,
"text": ";~=\n"
},
{
"answer_id": 5364731,
"author": "pimvdb",
"author_id": 514749,
"author_profile": "https://Stackoverflow.com/users/514749",
"pm_score": 0,
"selected": false,
"text": "function a(x){for(r='',i=x.length;i>0;i--)r+=x[i-1];return x==r}\n a('lolol'); // true\na('haha'); // false\n"
},
{
"answer_id": 6005274,
"author": "Denis Mitropolskiy",
"author_id": 272834,
"author_profile": "https://Stackoverflow.com/users/272834",
"pm_score": 1,
"selected": false,
"text": "let p (s : string) = \n fst(s |> Seq.fold (fun (r, i) c -> (r && c = s.[s.Length - 1 - i], i + 1)) (true, 0))\n let p (s : string) = \n let r = ref true\n Seq.iteri (fun i c -> r := (!r && c = s.[s.Length - 1 - i])) s\n !r\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
228,523
|
<p>Following on from <a href="https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values">this question</a> what would be the best way to write a Char.IsHex() function in C#. So far I've got this but don't like it:</p>
<pre><code>bool CharIsHex(char c) {
c = Char.ToLower(c);
return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
}
</code></pre>
|
[
{
"answer_id": 228531,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": true,
"text": "bool is_hex_char = (c >= '0' && c <= '9') ||\n (c >= 'a' && c <= 'f') ||\n (c >= 'A' && c <= 'F');\n"
},
{
"answer_id": 228536,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 4,
"selected": false,
"text": "public static class Extensions\n{\n public static bool IsHex(this char c)\n {\n return (c >= '0' && c <= '9') ||\n (c >= 'a' && c <= 'f') ||\n (c >= 'A' && c <= 'F');\n }\n}\n char char c = 'A';\n\nif (c.IsHex())\n{\n Console.WriteLine(\"We have a hex char.\");\n}\n"
},
{
"answer_id": 228570,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "bool CharIsHex(char c) {\n c = Char.ToLower(c);\n return Char.IsDigit(c) || (c >= 'a' && c <= 'f');\n}\n"
},
{
"answer_id": 228580,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "Char.IsDigit() true true Char.IsDigit() 0xff10 0xff19 0x30-0x39 0xff21-0xff26 0xff41-0xff46 bool isHexChar = ('0' <= c) && (c <= '9') ||\n ('a' <= c) && (c <= 'f') ||\n ('A' <= c) && (c <= 'F');\n"
},
{
"answer_id": 228606,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "using System.Text.RegularExpressions;\npublic static class Extensions\n{\n public static bool IsHex(this char c)\n {\n\n return (new Regex(\"[A-Fa-f0-9]\").IsMatch(c.ToString()));\n }\n}\n"
},
{
"answer_id": 27446564,
"author": "Steven Liekens",
"author_id": 1288449,
"author_profile": "https://Stackoverflow.com/users/1288449",
"pm_score": 2,
"selected": false,
"text": "bool IsHex(char c)\n{\n return \"0123456789ABCDEFabcdef\".IndexOf(c) != -1;\n}\n"
},
{
"answer_id": 48183323,
"author": "juFo",
"author_id": 187650,
"author_profile": "https://Stackoverflow.com/users/187650",
"pm_score": 3,
"selected": false,
"text": "char c = 'a';\nSystem.Uri.IsHexDigit(c);\n"
},
{
"answer_id": 72610222,
"author": "Stelio Kontos",
"author_id": 9412456,
"author_profile": "https://Stackoverflow.com/users/9412456",
"pm_score": 0,
"selected": false,
"text": "System.Uri.IsHexDigit(char) // add this to a public static extensions class\npublic static bool IsHexDigit(this char c) => c is >= '0' and <= '9' or >= 'a' and <= 'f' or >= 'A' and <= 'F';\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
228,532
|
<p>What's the difference between <code>Char.IsDigit()</code> and <code>Char.IsNumber()</code> in C#?</p>
|
[
{
"answer_id": 228538,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 6,
"selected": false,
"text": "DecimalDigitNumber LetterNumber OtherNumber Char.IsDigit DecimalDigitNumber Char.IsNumber DecimalDigitNumber LetterNumber OtherNumber"
},
{
"answer_id": 228565,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 8,
"selected": true,
"text": "Char.IsDigit() Char.IsNumber() IsDigit() true static private void test()\n{\n for (int i = 0; i <= 0xffff; ++i)\n {\n char c = (char) i;\n\n if (Char.IsDigit( c) != Char.IsNumber( c)) {\n Console.WriteLine( \"Char value {0:x} IsDigit() = {1}, IsNumber() = {2}\", i, Char.IsDigit( c), Char.IsNumber( c));\n }\n }\n}\n"
},
{
"answer_id": 36056338,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 6,
"selected": false,
"text": "IsNumber(x) true UnicodeCategory true IsNumber() IsDigit() UnicodeCategory.DecimalDigitNumber [Test]\n public void IsNumberTest()\n {\n var numberLikes = new[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherNumber, UnicodeCategory.LetterNumber };\n for (var i = 0; i < 0xffff; i++)\n {\n var c = Char.ConvertFromUtf32(i).ToCharArray()[0];\n if (numberLikes.Contains(Char.GetUnicodeCategory(c)))\n {\n File.AppendAllText(\"IsNumberLike.txt\", string.Format(\"{0},{1},{2},&#{3};,{4},{5}\\n\", i, c, Char.GetUnicodeCategory(c), i, Char.IsNumber(c), Char.IsDigit(c)));\n }\n }\n }\n +------+----+--------------------+----------+------+-------+\n| int |symbol| UnicodeCategory | Html |IsNumber|IsDigit|\n+-------+---+--------------------+----------+------+-------+\n| 48 | 0 | DecimalDigitNumber | 0 | True | True |\n| 49 | 1 | DecimalDigitNumber | 1 | True | True |\n| 50 | 2 | DecimalDigitNumber | 2 | True | True |\n| 51 | 3 | DecimalDigitNumber | 3 | True | True |\n| 52 | 4 | DecimalDigitNumber | 4 | True | True |\n| 53 | 5 | DecimalDigitNumber | 5 | True | True |\n| 54 | 6 | DecimalDigitNumber | 6 | True | True |\n| 55 | 7 | DecimalDigitNumber | 7 | True | True |\n| 56 | 8 | DecimalDigitNumber | 8 | True | True |\n| 57 | 9 | DecimalDigitNumber | 9 | True | True |\n| 178 | ² | OtherNumber | ² | True | False |\n| 179 | ³ | OtherNumber | ³ | True | False |\n| 185 | ¹ | OtherNumber | ¹ | True | False |\n| 188 | ¼ | OtherNumber | ¼ | True | False |\n| 189 | ½ | OtherNumber | ½ | True | False |\n| 190 | ¾ | OtherNumber | ¾ | True | False |\n| 1632 | ٠ | DecimalDigitNumber | ٠ | True | True |\n| 1633 | ١ | DecimalDigitNumber | ١ | True | True |\n| 1634 | ٢ | DecimalDigitNumber | ٢ | True | True |\n| 1635 | ٣ | DecimalDigitNumber | ٣ | True | True |\n| 1636 | ٤ | DecimalDigitNumber | ٤ | True | True |\n| 1637 | ٥ | DecimalDigitNumber | ٥ | True | True |\n| 1638 | ٦ | DecimalDigitNumber | ٦ | True | True |\n| 1639 | ٧ | DecimalDigitNumber | ٧ | True | True |\n| 1640 | ٨ | DecimalDigitNumber | ٨ | True | True |\n| 1641 | ٩ | DecimalDigitNumber | ٩ | True | True |\n| 1776 | ۰ | DecimalDigitNumber | ۰ | True | True |\n| 1777 | ۱ | DecimalDigitNumber | ۱ | True | True |\n| 1778 | ۲ | DecimalDigitNumber | ۲ | True | True |\n| 1779 | ۳ | DecimalDigitNumber | ۳ | True | True |\n| 1780 | ۴ | DecimalDigitNumber | ۴ | True | True |\n| 1781 | ۵ | DecimalDigitNumber | ۵ | True | True |\n| 1782 | ۶ | DecimalDigitNumber | ۶ | True | True |\n| 1783 | ۷ | DecimalDigitNumber | ۷ | True | True |\n| 1784 | ۸ | DecimalDigitNumber | ۸ | True | True |\n| 1785 | ۹ | DecimalDigitNumber | ۹ | True | True |\n| 1984 | ߀ | DecimalDigitNumber | ߀ | True | True |\n| 1985 | ߁ | DecimalDigitNumber | ߁ | True | True |\n| 1986 | ߂ | DecimalDigitNumber | ߂ | True | True |\n| 1987 | ߃ | DecimalDigitNumber | ߃ | True | True |\n| 1988 | ߄ | DecimalDigitNumber | ߄ | True | True |\n| 1989 | ߅ | DecimalDigitNumber | ߅ | True | True |\n| 1990 | ߆ | DecimalDigitNumber | ߆ | True | True |\n| 1991 | ߇ | DecimalDigitNumber | ߇ | True | True |\n| 1992 | ߈ | DecimalDigitNumber | ߈ | True | True |\n| 1993 | ߉ | DecimalDigitNumber | ߉ | True | True |\n| 2406 | ० | DecimalDigitNumber | ० | True | True |\n| 2407 | १ | DecimalDigitNumber | १ | True | True |\n| 2408 | २ | DecimalDigitNumber | २ | True | True |\n| 2409 | ३ | DecimalDigitNumber | ३ | True | True |\n| 2410 | ४ | DecimalDigitNumber | ४ | True | True |\n| 2411 | ५ | DecimalDigitNumber | ५ | True | True |\n| 2412 | ६ | DecimalDigitNumber | ६ | True | True |\n| 2413 | ७ | DecimalDigitNumber | ७ | True | True |\n| 2414 | ८ | DecimalDigitNumber | ८ | True | True |\n| 2415 | ९ | DecimalDigitNumber | ९ | True | True |\n| 2534 | ০ | DecimalDigitNumber | ০ | True | True |\n| 2535 | ১ | DecimalDigitNumber | ১ | True | True |\n| 2536 | ২ | DecimalDigitNumber | ২ | True | True |\n| 2537 | ৩ | DecimalDigitNumber | ৩ | True | True |\n| 2538 | ৪ | DecimalDigitNumber | ৪ | True | True |\n| 2539 | ৫ | DecimalDigitNumber | ৫ | True | True |\n| 2540 | ৬ | DecimalDigitNumber | ৬ | True | True |\n| 2541 | ৭ | DecimalDigitNumber | ৭ | True | True |\n| 2542 | ৮ | DecimalDigitNumber | ৮ | True | True |\n| 2543 | ৯ | DecimalDigitNumber | ৯ | True | True |\n| 2548 | ৴ | OtherNumber | ৴ | True | False |\n| 2549 | ৵ | OtherNumber | ৵ | True | False |\n| 2550 | ৶ | OtherNumber | ৶ | True | False |\n| 2551 | ৷ | OtherNumber | ৷ | True | False |\n| 2552 | ৸ | OtherNumber | ৸ | True | False |\n| 2553 | ৹ | OtherNumber | ৹ | True | False |\n| 2662 | ੦ | DecimalDigitNumber | ੦ | True | True |\n| 2663 | ੧ | DecimalDigitNumber | ੧ | True | True |\n| 2664 | ੨ | DecimalDigitNumber | ੨ | True | True |\n| 2665 | ੩ | DecimalDigitNumber | ੩ | True | True |\n| 2666 | ੪ | DecimalDigitNumber | ੪ | True | True |\n| 2667 | ੫ | DecimalDigitNumber | ੫ | True | True |\n| 2668 | ੬ | DecimalDigitNumber | ੬ | True | True |\n| 2669 | ੭ | DecimalDigitNumber | ੭ | True | True |\n| 2670 | ੮ | DecimalDigitNumber | ੮ | True | True |\n| 2671 | ੯ | DecimalDigitNumber | ੯ | True | True |\n| 2790 | ૦ | DecimalDigitNumber | ૦ | True | True |\n| 2791 | ૧ | DecimalDigitNumber | ૧ | True | True |\n| 2792 | ૨ | DecimalDigitNumber | ૨ | True | True |\n| 2793 | ૩ | DecimalDigitNumber | ૩ | True | True |\n| 2794 | ૪ | DecimalDigitNumber | ૪ | True | True |\n| 2795 | ૫ | DecimalDigitNumber | ૫ | True | True |\n| 2796 | ૬ | DecimalDigitNumber | ૬ | True | True |\n| 2797 | ૭ | DecimalDigitNumber | ૭ | True | True |\n| 2798 | ૮ | DecimalDigitNumber | ૮ | True | True |\n| 2799 | ૯ | DecimalDigitNumber | ૯ | True | True |\n| 2918 | ୦ | DecimalDigitNumber | ୦ | True | True |\n| 2919 | ୧ | DecimalDigitNumber | ୧ | True | True |\n| 2920 | ୨ | DecimalDigitNumber | ୨ | True | True |\n| 2921 | ୩ | DecimalDigitNumber | ୩ | True | True |\n| 2922 | ୪ | DecimalDigitNumber | ୪ | True | True |\n| 2923 | ୫ | DecimalDigitNumber | ୫ | True | True |\n| 2924 | ୬ | DecimalDigitNumber | ୬ | True | True |\n| 2925 | ୭ | DecimalDigitNumber | ୭ | True | True |\n| 2926 | ୮ | DecimalDigitNumber | ୮ | True | True |\n| 2927 | ୯ | DecimalDigitNumber | ୯ | True | True |\n| 2930 | ୲ | OtherNumber | ୲ | True | False |\n| 2931 | ୳ | OtherNumber | ୳ | True | False |\n| 2932 | ୴ | OtherNumber | ୴ | True | False |\n| 2933 | ୵ | OtherNumber | ୵ | True | False |\n| 2934 | ୶ | OtherNumber | ୶ | True | False |\n| 2935 | ୷ | OtherNumber | ୷ | True | False |\n| 3046 | ௦ | DecimalDigitNumber | ௦ | True | True |\n| 3047 | ௧ | DecimalDigitNumber | ௧ | True | True |\n| 3048 | ௨ | DecimalDigitNumber | ௨ | True | True |\n| 3049 | ௩ | DecimalDigitNumber | ௩ | True | True |\n| 3050 | ௪ | DecimalDigitNumber | ௪ | True | True |\n| 3051 | ௫ | DecimalDigitNumber | ௫ | True | True |\n| 3052 | ௬ | DecimalDigitNumber | ௬ | True | True |\n| 3053 | ௭ | DecimalDigitNumber | ௭ | True | True |\n| 3054 | ௮ | DecimalDigitNumber | ௮ | True | True |\n| 3055 | ௯ | DecimalDigitNumber | ௯ | True | True |\n| 3056 | ௰ | OtherNumber | ௰ | True | False |\n| 3057 | ௱ | OtherNumber | ௱ | True | False |\n| 3058 | ௲ | OtherNumber | ௲ | True | False |\n| 3174 | ౦ | DecimalDigitNumber | ౦ | True | True |\n| 3175 | ౧ | DecimalDigitNumber | ౧ | True | True |\n| 3176 | ౨ | DecimalDigitNumber | ౨ | True | True |\n| 3177 | ౩ | DecimalDigitNumber | ౩ | True | True |\n| 3178 | ౪ | DecimalDigitNumber | ౪ | True | True |\n| 3179 | ౫ | DecimalDigitNumber | ౫ | True | True |\n| 3180 | ౬ | DecimalDigitNumber | ౬ | True | True |\n| 3181 | ౭ | DecimalDigitNumber | ౭ | True | True |\n| 3182 | ౮ | DecimalDigitNumber | ౮ | True | True |\n| 3183 | ౯ | DecimalDigitNumber | ౯ | True | True |\n| 3192 | ౸ | OtherNumber | ౸ | True | False |\n| 3193 | ౹ | OtherNumber | ౹ | True | False |\n| 3194 | ౺ | OtherNumber | ౺ | True | False |\n| 3195 | ౻ | OtherNumber | ౻ | True | False |\n| 3196 | ౼ | OtherNumber | ౼ | True | False |\n| 3197 | ౽ | OtherNumber | ౽ | True | False |\n| 3198 | ౾ | OtherNumber | ౾ | True | False |\n| 3302 | ೦ | DecimalDigitNumber | ೦ | True | True |\n| 3303 | ೧ | DecimalDigitNumber | ೧ | True | True |\n| 3304 | ೨ | DecimalDigitNumber | ೨ | True | True |\n| 3305 | ೩ | DecimalDigitNumber | ೩ | True | True |\n| 3306 | ೪ | DecimalDigitNumber | ೪ | True | True |\n| 3307 | ೫ | DecimalDigitNumber | ೫ | True | True |\n| 3308 | ೬ | DecimalDigitNumber | ೬ | True | True |\n| 3309 | ೭ | DecimalDigitNumber | ೭ | True | True |\n| 3310 | ೮ | DecimalDigitNumber | ೮ | True | True |\n| 3311 | ೯ | DecimalDigitNumber | ೯ | True | True |\n| 3430 | ൦ | DecimalDigitNumber | ൦ | True | True |\n| 3431 | ൧ | DecimalDigitNumber | ൧ | True | True |\n| 3432 | ൨ | DecimalDigitNumber | ൨ | True | True |\n| 3433 | ൩ | DecimalDigitNumber | ൩ | True | True |\n| 3434 | ൪ | DecimalDigitNumber | ൪ | True | True |\n| 3435 | ൫ | DecimalDigitNumber | ൫ | True | True |\n| 3436 | ൬ | DecimalDigitNumber | ൬ | True | True |\n| 3437 | ൭ | DecimalDigitNumber | ൭ | True | True |\n| 3438 | ൮ | DecimalDigitNumber | ൮ | True | True |\n| 3439 | ൯ | DecimalDigitNumber | ൯ | True | True |\n| 3440 | ൰ | OtherNumber | ൰ | True | False |\n| 3441 | ൱ | OtherNumber | ൱ | True | False |\n| 3442 | ൲ | OtherNumber | ൲ | True | False |\n| 3443 | ൳ | OtherNumber | ൳ | True | False |\n| 3444 | ൴ | OtherNumber | ൴ | True | False |\n| 3445 | ൵ | OtherNumber | ൵ | True | False |\n| 3664 | ๐ | DecimalDigitNumber | ๐ | True | True |\n| 3665 | ๑ | DecimalDigitNumber | ๑ | True | True |\n| 3666 | ๒ | DecimalDigitNumber | ๒ | True | True |\n| 3667 | ๓ | DecimalDigitNumber | ๓ | True | True |\n| 3668 | ๔ | DecimalDigitNumber | ๔ | True | True |\n| 3669 | ๕ | DecimalDigitNumber | ๕ | True | True |\n| 3670 | ๖ | DecimalDigitNumber | ๖ | True | True |\n| 3671 | ๗ | DecimalDigitNumber | ๗ | True | True |\n| 3672 | ๘ | DecimalDigitNumber | ๘ | True | True |\n| 3673 | ๙ | DecimalDigitNumber | ๙ | True | True |\n| 3792 | ໐ | DecimalDigitNumber | ໐ | True | True |\n| 3793 | ໑ | DecimalDigitNumber | ໑ | True | True |\n| 3794 | ໒ | DecimalDigitNumber | ໒ | True | True |\n| 3795 | ໓ | DecimalDigitNumber | ໓ | True | True |\n| 3796 | ໔ | DecimalDigitNumber | ໔ | True | True |\n| 3797 | ໕ | DecimalDigitNumber | ໕ | True | True |\n| 3798 | ໖ | DecimalDigitNumber | ໖ | True | True |\n| 3799 | ໗ | DecimalDigitNumber | ໗ | True | True |\n| 3800 | ໘ | DecimalDigitNumber | ໘ | True | True |\n| 3801 | ໙ | DecimalDigitNumber | ໙ | True | True |\n| 3872 | ༠ | DecimalDigitNumber | ༠ | True | True |\n| 3873 | ༡ | DecimalDigitNumber | ༡ | True | True |\n| 3874 | ༢ | DecimalDigitNumber | ༢ | True | True |\n| 3875 | ༣ | DecimalDigitNumber | ༣ | True | True |\n| 3876 | ༤ | DecimalDigitNumber | ༤ | True | True |\n| 3877 | ༥ | DecimalDigitNumber | ༥ | True | True |\n| 3878 | ༦ | DecimalDigitNumber | ༦ | True | True |\n| 3879 | ༧ | DecimalDigitNumber | ༧ | True | True |\n| 3880 | ༨ | DecimalDigitNumber | ༨ | True | True |\n| 3881 | ༩ | DecimalDigitNumber | ༩ | True | True |\n| 3882 | ༪ | OtherNumber | ༪ | True | False |\n| 3883 | ༫ | OtherNumber | ༫ | True | False |\n| 3884 | ༬ | OtherNumber | ༬ | True | False |\n| 3885 | ༭ | OtherNumber | ༭ | True | False |\n| 3886 | ༮ | OtherNumber | ༮ | True | False |\n| 3887 | ༯ | OtherNumber | ༯ | True | False |\n| 3888 | ༰ | OtherNumber | ༰ | True | False |\n| 3889 | ༱ | OtherNumber | ༱ | True | False |\n| 3890 | ༲ | OtherNumber | ༲ | True | False |\n| 3891 | ༳ | OtherNumber | ༳ | True | False |\n| 4160 | ၀ | DecimalDigitNumber | ၀ | True | True |\n| 4161 | ၁ | DecimalDigitNumber | ၁ | True | True |\n| 4162 | ၂ | DecimalDigitNumber | ၂ | True | True |\n| 4163 | ၃ | DecimalDigitNumber | ၃ | True | True |\n| 4164 | ၄ | DecimalDigitNumber | ၄ | True | True |\n| 4165 | ၅ | DecimalDigitNumber | ၅ | True | True |\n| 4166 | ၆ | DecimalDigitNumber | ၆ | True | True |\n| 4167 | ၇ | DecimalDigitNumber | ၇ | True | True |\n| 4168 | ၈ | DecimalDigitNumber | ၈ | True | True |\n| 4169 | ၉ | DecimalDigitNumber | ၉ | True | True |\n| 4240 | ႐ | DecimalDigitNumber | ႐ | True | True |\n| 4241 | ႑ | DecimalDigitNumber | ႑ | True | True |\n| 4242 | ႒ | DecimalDigitNumber | ႒ | True | True |\n| 4243 | ႓ | DecimalDigitNumber | ႓ | True | True |\n| 4244 | ႔ | DecimalDigitNumber | ႔ | True | True |\n| 4245 | ႕ | DecimalDigitNumber | ႕ | True | True |\n| 4246 | ႖ | DecimalDigitNumber | ႖ | True | True |\n| 4247 | ႗ | DecimalDigitNumber | ႗ | True | True |\n| 4248 | ႘ | DecimalDigitNumber | ႘ | True | True |\n| 4249 | ႙ | DecimalDigitNumber | ႙ | True | True |\n| 4969 | ፩ | OtherNumber | ፩ | True | False |\n| 4970 | ፪ | OtherNumber | ፪ | True | False |\n| 4971 | ፫ | OtherNumber | ፫ | True | False |\n| 4972 | ፬ | OtherNumber | ፬ | True | False |\n| 4973 | ፭ | OtherNumber | ፭ | True | False |\n| 4974 | ፮ | OtherNumber | ፮ | True | False |\n| 4975 | ፯ | OtherNumber | ፯ | True | False |\n| 4976 | ፰ | OtherNumber | ፰ | True | False |\n| 4977 | ፱ | OtherNumber | ፱ | True | False |\n| 4978 | ፲ | OtherNumber | ፲ | True | False |\n| 4979 | ፳ | OtherNumber | ፳ | True | False |\n| 4980 | ፴ | OtherNumber | ፴ | True | False |\n| 4981 | ፵ | OtherNumber | ፵ | True | False |\n| 4982 | ፶ | OtherNumber | ፶ | True | False |\n| 4983 | ፷ | OtherNumber | ፷ | True | False |\n| 4984 | ፸ | OtherNumber | ፸ | True | False |\n| 4985 | ፹ | OtherNumber | ፹ | True | False |\n| 4986 | ፺ | OtherNumber | ፺ | True | False |\n| 4987 | ፻ | OtherNumber | ፻ | True | False |\n| 4988 | ፼ | OtherNumber | ፼ | True | False |\n| 5870 | ᛮ | LetterNumber | ᛮ | True | False |\n| 5871 | ᛯ | LetterNumber | ᛯ | True | False |\n| 5872 | ᛰ | LetterNumber | ᛰ | True | False |\n| 6112 | ០ | DecimalDigitNumber | ០ | True | True |\n| 6113 | ១ | DecimalDigitNumber | ១ | True | True |\n| 6114 | ២ | DecimalDigitNumber | ២ | True | True |\n| 6115 | ៣ | DecimalDigitNumber | ៣ | True | True |\n| 6116 | ៤ | DecimalDigitNumber | ៤ | True | True |\n| 6117 | ៥ | DecimalDigitNumber | ៥ | True | True |\n| 6118 | ៦ | DecimalDigitNumber | ៦ | True | True |\n| 6119 | ៧ | DecimalDigitNumber | ៧ | True | True |\n| 6120 | ៨ | DecimalDigitNumber | ៨ | True | True |\n| 6121 | ៩ | DecimalDigitNumber | ៩ | True | True |\n| 6128 | ៰ | OtherNumber | ៰ | True | False |\n| 6129 | ៱ | OtherNumber | ៱ | True | False |\n| 6130 | ៲ | OtherNumber | ៲ | True | False |\n| 6131 | ៳ | OtherNumber | ៳ | True | False |\n| 6132 | ៴ | OtherNumber | ៴ | True | False |\n| 6133 | ៵ | OtherNumber | ៵ | True | False |\n| 6134 | ៶ | OtherNumber | ៶ | True | False |\n| 6135 | ៷ | OtherNumber | ៷ | True | False |\n| 6136 | ៸ | OtherNumber | ៸ | True | False |\n| 6137 | ៹ | OtherNumber | ៹ | True | False |\n| 6160 | ᠐ | DecimalDigitNumber | ᠐ | True | True |\n| 6161 | ᠑ | DecimalDigitNumber | ᠑ | True | True |\n| 6162 | ᠒ | DecimalDigitNumber | ᠒ | True | True |\n| 6163 | ᠓ | DecimalDigitNumber | ᠓ | True | True |\n| 6164 | ᠔ | DecimalDigitNumber | ᠔ | True | True |\n| 6165 | ᠕ | DecimalDigitNumber | ᠕ | True | True |\n| 6166 | ᠖ | DecimalDigitNumber | ᠖ | True | True |\n| 6167 | ᠗ | DecimalDigitNumber | ᠗ | True | True |\n| 6168 | ᠘ | DecimalDigitNumber | ᠘ | True | True |\n| 6169 | ᠙ | DecimalDigitNumber | ᠙ | True | True |\n| 6470 | ᥆ | DecimalDigitNumber | ᥆ | True | True |\n| 6471 | ᥇ | DecimalDigitNumber | ᥇ | True | True |\n| 6472 | ᥈ | DecimalDigitNumber | ᥈ | True | True |\n| 6473 | ᥉ | DecimalDigitNumber | ᥉ | True | True |\n| 6474 | ᥊ | DecimalDigitNumber | ᥊ | True | True |\n| 6475 | ᥋ | DecimalDigitNumber | ᥋ | True | True |\n| 6476 | ᥌ | DecimalDigitNumber | ᥌ | True | True |\n| 6477 | ᥍ | DecimalDigitNumber | ᥍ | True | True |\n| 6478 | ᥎ | DecimalDigitNumber | ᥎ | True | True |\n| 6479 | ᥏ | DecimalDigitNumber | ᥏ | True | True |\n| 6608 | ᧐ | DecimalDigitNumber | ᧐ | True | True |\n| 6609 | ᧑ | DecimalDigitNumber | ᧑ | True | True |\n| 6610 | ᧒ | DecimalDigitNumber | ᧒ | True | True |\n| 6611 | ᧓ | DecimalDigitNumber | ᧓ | True | True |\n| 6612 | ᧔ | DecimalDigitNumber | ᧔ | True | True |\n| 6613 | ᧕ | DecimalDigitNumber | ᧕ | True | True |\n| 6614 | ᧖ | DecimalDigitNumber | ᧖ | True | True |\n| 6615 | ᧗ | DecimalDigitNumber | ᧗ | True | True |\n| 6616 | ᧘ | DecimalDigitNumber | ᧘ | True | True |\n| 6617 | ᧙ | DecimalDigitNumber | ᧙ | True | True |\n| 6618 | ᧚ | OtherNumber | ᧚ | True | False |\n| 6784 | ᪀ | DecimalDigitNumber | ᪀ | True | True |\n| 6785 | ᪁ | DecimalDigitNumber | ᪁ | True | True |\n| 6786 | ᪂ | DecimalDigitNumber | ᪂ | True | True |\n| 6787 | ᪃ | DecimalDigitNumber | ᪃ | True | True |\n| 6788 | ᪄ | DecimalDigitNumber | ᪄ | True | True |\n| 6789 | ᪅ | DecimalDigitNumber | ᪅ | True | True |\n| 6790 | ᪆ | DecimalDigitNumber | ᪆ | True | True |\n| 6791 | ᪇ | DecimalDigitNumber | ᪇ | True | True |\n| 6792 | ᪈ | DecimalDigitNumber | ᪈ | True | True |\n| 6793 | ᪉ | DecimalDigitNumber | ᪉ | True | True |\n| 6800 | ᪐ | DecimalDigitNumber | ᪐ | True | True |\n| 6801 | ᪑ | DecimalDigitNumber | ᪑ | True | True |\n| 6802 | ᪒ | DecimalDigitNumber | ᪒ | True | True |\n| 6803 | ᪓ | DecimalDigitNumber | ᪓ | True | True |\n| 6804 | ᪔ | DecimalDigitNumber | ᪔ | True | True |\n| 6805 | ᪕ | DecimalDigitNumber | ᪕ | True | True |\n| 6806 | ᪖ | DecimalDigitNumber | ᪖ | True | True |\n| 6807 | ᪗ | DecimalDigitNumber | ᪗ | True | True |\n| 6808 | ᪘ | DecimalDigitNumber | ᪘ | True | True |\n| 6809 | ᪙ | DecimalDigitNumber | ᪙ | True | True |\n| 6992 | ᭐ | DecimalDigitNumber | ᭐ | True | True |\n| 6993 | ᭑ | DecimalDigitNumber | ᭑ | True | True |\n| 6994 | ᭒ | DecimalDigitNumber | ᭒ | True | True |\n| 6995 | ᭓ | DecimalDigitNumber | ᭓ | True | True |\n| 6996 | ᭔ | DecimalDigitNumber | ᭔ | True | True |\n| 6997 | ᭕ | DecimalDigitNumber | ᭕ | True | True |\n| 6998 | ᭖ | DecimalDigitNumber | ᭖ | True | True |\n| 6999 | ᭗ | DecimalDigitNumber | ᭗ | True | True |\n| 7000 | ᭘ | DecimalDigitNumber | ᭘ | True | True |\n| 7001 | ᭙ | DecimalDigitNumber | ᭙ | True | True |\n| 7088 | ᮰ | DecimalDigitNumber | ᮰ | True | True |\n| 7089 | ᮱ | DecimalDigitNumber | ᮱ | True | True |\n| 7090 | ᮲ | DecimalDigitNumber | ᮲ | True | True |\n| 7091 | ᮳ | DecimalDigitNumber | ᮳ | True | True |\n| 7092 | ᮴ | DecimalDigitNumber | ᮴ | True | True |\n| 7093 | ᮵ | DecimalDigitNumber | ᮵ | True | True |\n| 7094 | ᮶ | DecimalDigitNumber | ᮶ | True | True |\n| 7095 | ᮷ | DecimalDigitNumber | ᮷ | True | True |\n| 7096 | ᮸ | DecimalDigitNumber | ᮸ | True | True |\n| 7097 | ᮹ | DecimalDigitNumber | ᮹ | True | True |\n| 7232 | ᱀ | DecimalDigitNumber | ᱀ | True | True |\n| 7233 | ᱁ | DecimalDigitNumber | ᱁ | True | True |\n| 7234 | ᱂ | DecimalDigitNumber | ᱂ | True | True |\n| 7235 | ᱃ | DecimalDigitNumber | ᱃ | True | True |\n| 7236 | ᱄ | DecimalDigitNumber | ᱄ | True | True |\n| 7237 | ᱅ | DecimalDigitNumber | ᱅ | True | True |\n| 7238 | ᱆ | DecimalDigitNumber | ᱆ | True | True |\n| 7239 | ᱇ | DecimalDigitNumber | ᱇ | True | True |\n| 8304 | ⁰ | OtherNumber | ⁰ | True | False |\n| 8308 | ⁴ | OtherNumber | ⁴ | True | False |\n| 8309 | ⁵ | OtherNumber | ⁵ | True | False |\n| 8310 | ⁶ | OtherNumber | ⁶ | True | False |\n| 8311 | ⁷ | OtherNumber | ⁷ | True | False |\n| 8312 | ⁸ | OtherNumber | ⁸ | True | False |\n| 8313 | ⁹ | OtherNumber | ⁹ | True | False |\n| 8320 | ₀ | OtherNumber | ₀ | True | False |\n| 8321 | ₁ | OtherNumber | ₁ | True | False |\n| 8322 | ₂ | OtherNumber | ₂ | True | False |\n| 8323 | ₃ | OtherNumber | ₃ | True | False |\n| 8324 | ₄ | OtherNumber | ₄ | True | False |\n| 8325 | ₅ | OtherNumber | ₅ | True | False |\n| 8326 | ₆ | OtherNumber | ₆ | True | False |\n| 8327 | ₇ | OtherNumber | ₇ | True | False |\n| 8328 | ₈ | OtherNumber | ₈ | True | False |\n| 8329 | ₉ | OtherNumber | ₉ | True | False |\n| 8528 | ⅐ | OtherNumber | ⅐ | True | False |\n| 8529 | ⅑ | OtherNumber | ⅑ | True | False |\n| 8530 | ⅒ | OtherNumber | ⅒ | True | False |\n| 8531 | ⅓ | OtherNumber | ⅓ | True | False |\n| 8532 | ⅔ | OtherNumber | ⅔ | True | False |\n| 8533 | ⅕ | OtherNumber | ⅕ | True | False |\n| 8534 | ⅖ | OtherNumber | ⅖ | True | False |\n| 8535 | ⅗ | OtherNumber | ⅗ | True | False |\n| 8536 | ⅘ | OtherNumber | ⅘ | True | False |\n| 8537 | ⅙ | OtherNumber | ⅙ | True | False |\n| 8538 | ⅚ | OtherNumber | ⅚ | True | False |\n| 8539 | ⅛ | OtherNumber | ⅛ | True | False |\n| 8540 | ⅜ | OtherNumber | ⅜ | True | False |\n| 8541 | ⅝ | OtherNumber | ⅝ | True | False |\n| 8542 | ⅞ | OtherNumber | ⅞ | True | False |\n| 8543 | ⅟ | OtherNumber | ⅟ | True | False |\n| 8544 | Ⅰ | LetterNumber | Ⅰ | True | False |\n| 8545 | Ⅱ | LetterNumber | Ⅱ | True | False |\n| 8546 | Ⅲ | LetterNumber | Ⅲ | True | False |\n| 8547 | Ⅳ | LetterNumber | Ⅳ | True | False |\n| 8548 | Ⅴ | LetterNumber | Ⅴ | True | False |\n| 8549 | Ⅵ | LetterNumber | Ⅵ | True | False |\n| 8550 | Ⅶ | LetterNumber | Ⅶ | True | False |\n| 8551 | Ⅷ | LetterNumber | Ⅷ | True | False |\n| 8552 | Ⅸ | LetterNumber | Ⅸ | True | False |\n| 8553 | Ⅹ | LetterNumber | Ⅹ | True | False |\n| 8554 | Ⅺ | LetterNumber | Ⅺ | True | False |\n| 8555 | Ⅻ | LetterNumber | Ⅻ | True | False |\n| 8556 | Ⅼ | LetterNumber | Ⅼ | True | False |\n| 8557 | Ⅽ | LetterNumber | Ⅽ | True | False |\n| 8558 | Ⅾ | LetterNumber | Ⅾ | True | False |\n| 8559 | Ⅿ | LetterNumber | Ⅿ | True | False |\n| 8560 | ⅰ | LetterNumber | ⅰ | True | False |\n| 8561 | ⅱ | LetterNumber | ⅱ | True | False |\n| 8562 | ⅲ | LetterNumber | ⅲ | True | False |\n| 8563 | ⅳ | LetterNumber | ⅳ | True | False |\n| 8564 | ⅴ | LetterNumber | ⅴ | True | False |\n| 8565 | ⅵ | LetterNumber | ⅵ | True | False |\n| 8566 | ⅶ | LetterNumber | ⅶ | True | False |\n| 8567 | ⅷ | LetterNumber | ⅷ | True | False |\n| 8568 | ⅸ | LetterNumber | ⅸ | True | False |\n| 8569 | ⅹ | LetterNumber | ⅹ | True | False |\n| 8570 | ⅺ | LetterNumber | ⅺ | True | False |\n| 8571 | ⅻ | LetterNumber | ⅻ | True | False |\n| 8572 | ⅼ | LetterNumber | ⅼ | True | False |\n| 8573 | ⅽ | LetterNumber | ⅽ | True | False |\n| 8574 | ⅾ | LetterNumber | ⅾ | True | False |\n| 8575 | ⅿ | LetterNumber | ⅿ | True | False |\n| 8576 | ↀ | LetterNumber | ↀ | True | False |\n| 8577 | ↁ | LetterNumber | ↁ | True | False |\n| 8578 | ↂ | LetterNumber | ↂ | True | False |\n| 8581 | ↅ | LetterNumber | ↅ | True | False |\n+-------+---+--------------------+----------+------+-------+\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
228,534
|
<p>Is there someway to set the default file permission in Linux? That is, the file permission for a newly created file (regardless of the context for which it was created
). I know about putting umask in the shell startup but that only works for shell sessions. When I transfer files to a Linux box using <strong>pscp</strong>, the file is always created with permissions of 664 (rw-rw-r--). The has occurred across every flavor of Linux that I've used. This is especially annoying when I pscp a file to shared Linux machine (like my ISP). Until I can shell in and chmod the permission, the file is basically sitting there with read access for everyone, which is not exactly secure.</p>
|
[
{
"answer_id": 228564,
"author": "Matt Curtis",
"author_id": 17221,
"author_profile": "https://Stackoverflow.com/users/17221",
"pm_score": 4,
"selected": false,
"text": ".bash_profile .zshenv .tcshrc"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
228,544
|
<p>If I want to check for the null string I would do</p>
<pre><code>[ -z $mystr ]
</code></pre>
<p>but what if I want to check whether the variable has been defined at all? Or is there no distinction in Bash scripting?</p>
|
[
{
"answer_id": 228552,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": false,
"text": "~> if [ -z $FOO ]; then echo \"EMPTY\"; fi\nEMPTY\n~> FOO=\"\"\n~> if [ -z $FOO ]; then echo \"EMPTY\"; fi\nEMPTY\n~> FOO=\"a\"\n~> if [ -z $FOO ]; then echo \"EMPTY\"; fi\n~> \n ~$ unset FOO\n~$ if test ${FOO+defined}; then echo \"DEFINED\"; fi\n~$ FOO=\"\"\n~$ if test ${FOO+defined}; then echo \"DEFINED\"; fi\nDEFINED\n ~$ FOO=\"\"\n~$ if test \"${FOO-default value}\" ; then echo \"UNDEFINED\"; fi\n~$ unset FOO\n~$ if test \"${FOO-default value}\" ; then echo \"UNDEFINED\"; fi\nUNDEFINED\n"
},
{
"answer_id": 230593,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 8,
"selected": true,
"text": "if [ -z \"${VAR+xxx}\" ]; then echo \"VAR is not set at all\"; fi\nif [ -z \"$VAR\" ] && [ \"${VAR+xxx}\" = \"xxx\" ]; then echo \"VAR is set but empty\"; fi\n if [ -z \"$VAR\" -a \"${VAR+xxx}\" = \"xxx\" ]; then echo \"VAR is set but empty\"; fi\n -a && test [ if [ -z \"${VAR+xxx}\" ]; then echo \"VAR is not set at all\"; fi\n if [ -z \"${VAR}\" ]; then echo \"VAR is not set at all\"; fi\n VAR=\n (\nunset VAR\nif [ -z \"${VAR+xxx}\" ]; then echo \"JL:1 VAR is not set at all\"; fi\nif [ -z \"${VAR}\" ]; then echo \"MP:1 VAR is not set at all\"; fi\nVAR=\nif [ -z \"${VAR+xxx}\" ]; then echo \"JL:2 VAR is not set at all\"; fi\nif [ -z \"${VAR}\" ]; then echo \"MP:2 VAR is not set at all\"; fi\n)\n ${VAR=value} ${VAR:=value} ${VAR-value} ${VAR:-value} ${VAR+value} ${VAR:+value} bash set -o nounset unbound variable if [ -z \"${VAR+xxx}\" ]; then echo \"VAR is not set at all\"; fi\nif [ -z \"${VAR-}\" ] && [ \"${VAR+xxx}\" = \"xxx\" ]; then echo \"VAR is set but empty\"; fi\n set -o nounset set +u set -u set -o nounset"
},
{
"answer_id": 7617214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "isdefined=0\n${mystr+ export isdefined=1}\n (set -u) mystr=${mystr- 7}\n : ${mystr? not defined}\n"
},
{
"answer_id": 7617451,
"author": "Swiss",
"author_id": 84955,
"author_profile": "https://Stackoverflow.com/users/84955",
"pm_score": 0,
"selected": false,
"text": "var_defined() {\n local var_name=$1\n set | grep \"^${var_name}=\" 1>/dev/null\n return $?\n}\n if var_defined foo; then\n echo \"foo is defined\"\nelse\n echo \"foo is not defined\"\nfi\n"
},
{
"answer_id": 9898583,
"author": "Aaron Davies",
"author_id": 428843,
"author_profile": "https://Stackoverflow.com/users/428843",
"pm_score": 1,
"selected": false,
"text": "$ unset foo\n$ foo=\n$ echo ${!foo[*]}\n0\n\n$ foo=bar\n$ echo ${!foo[*]}\n0\n\n$ foo=(bar baz)\n$ echo ${!foo[*]}\n0 1\n foo $ unset foo\n$ [[ ${!foo[*]} ]]; echo $?\n1\n\n$ foo=\n$ [[ ${!foo[*]} ]]; echo $?\n0\n\n$ foo=bar\n$ [[ ${!foo[*]} ]]; echo $?\n0\n\n$ foo=(bar baz)\n$ [[ ${!foo[*]} ]]; echo $?\n0\n"
},
{
"answer_id": 10965292,
"author": "k107",
"author_id": 594496,
"author_profile": "https://Stackoverflow.com/users/594496",
"pm_score": 4,
"selected": false,
"text": "[ -n \"$var\" ] && echo \"var is set and not empty\"\n[ -z \"$var\" ] && echo \"var is unset or empty\"\n[ \"${var+x}\" = \"x\" ] && echo \"var is set\" # may or may not be empty\n[ -n \"${var+x}\" ] && echo \"var is set\" # may or may not be empty\n[ -z \"${var+x}\" ] && echo \"var is unset\"\n[ -z \"${var-x}\" ] && echo \"var is set and empty\"\n"
},
{
"answer_id": 11593841,
"author": "Sacrilicious",
"author_id": 743638,
"author_profile": "https://Stackoverflow.com/users/743638",
"pm_score": 1,
"selected": false,
"text": "shopt -s -o nounset\n ${mystr:?} parameter null or not set"
},
{
"answer_id": 16946889,
"author": "Felix Leipold",
"author_id": 500571,
"author_profile": "https://Stackoverflow.com/users/500571",
"pm_score": 3,
"selected": false,
"text": "[ -v mystr ]\n"
},
{
"answer_id": 20003892,
"author": "Gili",
"author_id": 14731,
"author_profile": "https://Stackoverflow.com/users/14731",
"pm_score": 3,
"selected": false,
"text": "set -o nounset if [ -n \"${VAR-}\" ]; then\n echo \"VAR is set and is not empty\"\nelif [ \"${VAR+DEFINED_BUT_EMPTY}\" = \"DEFINED_BUT_EMPTY\" ]; then\n echo \"VAR is set, but empty\"\nelse\n echo \"VAR is not set\"\nfi\n"
},
{
"answer_id": 34028846,
"author": "funroll",
"author_id": 878969,
"author_profile": "https://Stackoverflow.com/users/878969",
"pm_score": 1,
"selected": false,
"text": "if [ -z \"$PS1\" ]; then\n echo This shell is not interactive\nelse\n echo This shell is interactive\nfi\n [ ] export VARIABLE_NAME=\"$SOME_OTHER_VARIABLE/path-part\"\n if [ -z \"$VARIABLE_NAME\" ]; then\n export VARIABLE_NAME=\"$SOME_OTHER_VARIABLE/path-part\"\nfi\n s/\\vexport ([A-Z_]+)\\=(\"[^\"]+\")\\n/if [ -z \"$\\1\" ]; then\\r export \\1=\\2\\rfi\\r/gc\n : :'<,'> VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Aug 22 2015 15:38:58)\nCompiled by root@apple.com\n"
},
{
"answer_id": 59073821,
"author": "nfleury",
"author_id": 5074477,
"author_profile": "https://Stackoverflow.com/users/5074477",
"pm_score": 0,
"selected": false,
"text": "test -z ${mystr} && echo \"mystr is not defined\"\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30636/"
] |
228,545
|
<p>A legacy backend requires the email body with a .tif document, no tif and it fails. So i need to generate a blank .tif, is there a fast way to do this with ghostscript? </p>
<hr>
<p>edit: make once in project installation use when i need it.</p>
|
[
{
"answer_id": 229044,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffpack -g1x1 -sOutputFile=small.tif -c newpath 0 0 moveto 1 1 lineto closepath stroke showpage quit\n gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffpack -g1x1 -sOutputFile=small.tif -c showpage quit\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
228,549
|
<p>I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of</p>
<pre><code>function editRecord()
{
var gridView = document.getElementById("<%= GridView.ClientID %>");
var id = // somehow get the id here ???
window.open("edit.aspx?id=" + id);
}
</code></pre>
<p>The question is how do I retrieve the selected records ID in javascript?</p>
|
[
{
"answer_id": 228556,
"author": "Dave K",
"author_id": 19864,
"author_profile": "https://Stackoverflow.com/users/19864",
"pm_score": 1,
"selected": false,
"text": "function editRecord(clientId)\n{ ....\n <input type=\"button\" onclick=\"editRecord(your-rows-client-id-goes-here)\" />\n"
},
{
"answer_id": 228616,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 4,
"selected": true,
"text": "<asp:TemplateField ShowHeader=\"False\">\n <ItemTemplate>\n <asp:HiddenField ID=\"hdID\" runat=\"server\" Value='<%# Eval(\"JobID\") %>' />\n </ItemTemplate>\n</asp:TemplateField>\n<asp:TemplateField Visible=\"False\">\n <ItemTemplate>\n <asp:LinkButton ID=\"lnkSelect\" runat=\"server\" CommandName=\"select\" Text=\"Select\" />\n </ItemTemplate>\n</asp:TemplateField>\n protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n // Click to highlight row\n Control lnkSelect = e.Row.FindControl(\"lnkSelect\");\n if (lnkSelect != null)\n {\n StringBuilder click = new StringBuilder();\n click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));\n click.AppendLine(String.Format(\"onGridViewRowSelected('{0}')\", e.Row.RowIndex));\n e.Row.Attributes.Add(\"onclick\", click.ToString());\n }\n } \n}\n <script type=\"text/javascript\">\n\nvar selectedRowIndex = null;\n\nfunction onGridViewRowSelected(rowIndex)\n{ \n selectedRowIndex = rowIndex;\n}\n\nfunction editItem()\n{ \n if (selectedRowIndex == null) return;\n\n var gridView = document.getElementById('<%= GridView1.ClientID %>'); \n var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0]; \n var hidID = cell.childNodes[0]; \n window.open('JobTypeEdit.aspx?id=' + hidID.value);\n}\n\n</script> \n"
},
{
"answer_id": 8904692,
"author": "Brent",
"author_id": 1022710,
"author_profile": "https://Stackoverflow.com/users/1022710",
"pm_score": 0,
"selected": false,
"text": "<asp:HyperLink runat=\"server\" ID=\"editLink\" Target=\"_blank\"\n NavigateURL='<%# Eval(\"JobID\",\"edit.aspx?id={0}\") %>'> \n Edit..\n</asp:HyperLink>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
228,559
|
<p>currently i obtain the below result from the following C# line of code when in es-MX Culture</p>
<pre><code> Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = new
CultureInfo("es-mx");
<span><%=DateTime.Now.ToLongDateString()%></span>
</code></pre>
<h1>miércoles, 22 de octubre de 2008</h1>
<p>i would like to obtain the following</p>
<h1>Miércoles, 22 de Octubre de 2008</h1>
<p>do i need to Build my own culture?</p>
|
[
{
"answer_id": 228582,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "dddd, dd' de 'MMMM' de 'yyyy"
},
{
"answer_id": 228597,
"author": "jaircazarin-old-account",
"author_id": 20915,
"author_profile": "https://Stackoverflow.com/users/20915",
"pm_score": 4,
"selected": true,
"text": " string[] newNames = { \"Lunes\", \"Martes\", \"Miercoles\", \"Jueves\", \"Viernes\", \"Sabado\", \"Domingo\" };\n Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = newNames;\n"
},
{
"answer_id": 228649,
"author": "Oscar Cabrero",
"author_id": 14440,
"author_profile": "https://Stackoverflow.com/users/14440",
"pm_score": 0,
"selected": false,
"text": "private void SetDateTimeFormatNames()\n {\n\n Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = ConvertoToTitleCase(Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames);\n Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames = ConvertoToTitleCase(Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames);\n\n }\n\nprivate string[] ConvertoToTitleCase(string[] arrayToConvert)\n {\n for (int i = 0; i < arrayToConvert.Length; i++)\n {\n arrayToConvert[i] = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(arrayToConvert[i]);\n }\n\n return arrayToConvert;\n }\n"
},
{
"answer_id": 2542616,
"author": "xavier",
"author_id": 304756,
"author_profile": "https://Stackoverflow.com/users/304756",
"pm_score": 2,
"selected": false,
"text": " public static string GetFecha()\n {\n System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(\"es-EC\");\n System.Threading.Thread.CurrentThread.CurrentCulture = culture;\n\n // maldita sea!\n string strDate = culture.TextInfo.ToTitleCase(DateTime.Now.ToLongDateString());\n\n return strDate.Replace(\"De\", \"de\");\n\n\n }\n"
},
{
"answer_id": 70626777,
"author": "Márcio Souza Júnior",
"author_id": 2083581,
"author_profile": "https://Stackoverflow.com/users/2083581",
"pm_score": 1,
"selected": false,
"text": "string.Format private string GetDateFormated(DateTime date)\n{\n return string.Format(\"{0}, {1} {2} {3}\",\n ToTitleCase(date.ToString(\"dddd\")),\n date.ToString(\"dd\"),\n ToTitleCase(date.ToString(\"MMMM\")),\n date.ToString(\"yyyy\"));\n}\n\nprivate string ToTitleCase(string input)\n{\n return input[0].ToString().ToUpper() + input.Substring(1);\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14440/"
] |
228,567
|
<p>I have a section of makefile that has this sort of structure:</p>
<pre><code>
bob:
ifdef DEBUG
@echo running
endif
@echo chug chug chug
ifdef DEBUG
@echo done
endif
bobit:
@echo "before"
@make bob
@echo "after"
</code></pre>
<p>I'm simplifying greatly here, all the echo's are actually non trivial blocks of commands and there is more conditional stuff, but this captures the essence of my problem.</p>
<p>For technical reasons I don't want to get into right now, I need to get rid of that submake, but because the echo's represent nontrivial amounts of code I don't want to just copy and past the body of bob in place of the submake.</p>
<p>Ideally what I'd like to do is something like this</p>
<pre><code>
define BOB_BODY
ifdef DEBUG
@echo running
endif
@echo chug chug chug
ifdef DEBUG
@echo done
endif
endef
bob:
$(BOB_BODY)
bobit:
@echo "before"
$(BOB_BODY)
@echo "after"
</code></pre>
<p>Unfortunately the conditionals seem to be shafting me, they produce "ifdef: Command not found" errors, I tried getting around this with various combinations of eval and call, but can't seem to figure out a way to get it to work.</p>
<p>How do I make this work? and is it even the right way to approach the problem?</p>
|
[
{
"answer_id": 233014,
"author": "Gordon Wrigley",
"author_id": 10471,
"author_profile": "https://Stackoverflow.com/users/10471",
"pm_score": 3,
"selected": true,
"text": "\ndefine BOB_BODY\n @if [[ -n \"$(DEBUG)\" ]]; then \\\n echo running; \\\n fi;\n @echo chug chug chug\n @if [[ -n \"$(DEBUG)\" ]]; then \\\n echo done; \\\n fi\nendef\n\nbob:\n $(BOB_BODY)\n\nbobit:\n @echo \"before\"\n $(BOB_BODY)\n @echo \"after\"\n"
},
{
"answer_id": 7667551,
"author": "pmod",
"author_id": 356838,
"author_profile": "https://Stackoverflow.com/users/356838",
"pm_score": 0,
"selected": false,
"text": "ifdef DEBUG\n define BOB_BODY \n @echo running\n @echo chug chug chug\n @echo done\n endef\nelse \n define BOB_BODY \n @echo chug chug chug\n endef\nendif\n define CHUG\n @echo chug chug chug\nendef\n\nifdef DEBUG\n define BOB_BODY \n @echo running\n $(CHUG)\n @echo done\n endef\nelse \n define BOB_BODY \n $(CHUG)\n endef\nendif\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10471/"
] |
228,574
|
<p>I am tasked with updating a family of web sites that promote scientific conferences that cater to a niche scientific field. The sites are currently written with some modest CSS layout for the shared common page template structure, but the details of each page are a mishmash of <p>, <br>, and &nbsp; to position the content. This makes it tough to update the content, since the spacings are always changing, and the page ends up ugly at the slightest mod.</p>
<p>So, I'd like to change this stuff into a more CSS-happy state. There are lots of sites that offer tips for specific CSS design goals, but I'm a developer without a lot of web site artistry capabilities and don't have a structure already in mind. Are there any good sites that teach CSS in the context of some relatively mundane -- but effectively presented -- business content? Stuff like the CSS zen garden is way cool, but I'm looking more for something that will both give me some simple text-heavy business data positioning ideas <em>and</em> present those ideas as a CSS learning opportunity.</p>
<p>Does any such site exist?</p>
|
[
{
"answer_id": 234895,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 3,
"selected": true,
"text": "<br/> line-height"
},
{
"answer_id": 242221,
"author": "dewde",
"author_id": 2640,
"author_profile": "https://Stackoverflow.com/users/2640",
"pm_score": 2,
"selected": false,
"text": "<br> <p></p> <h1>,<h2>,<h3>"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] |
228,590
|
<p>A couple of the options are:</p>
<pre><code>$connection = {my db connection/object};
function PassedIn($connection) { ... }
function PassedByReference(&$connection) { ... }
function UsingGlobal() {
global $connection;
...
}
</code></pre>
<p>So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.</p>
<p>I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.</p>
<p>The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.</p>
|
[
{
"answer_id": 228596,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "mysql"
},
{
"answer_id": 228652,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 1,
"selected": false,
"text": "class SomeClass {\n protected $dbc;\n\n public function __construct($db) {\n $this->dbc = $db;\n }\n\n public function getDB() {\n return $this->dbc;\n }\n\n function read_something() {\n $db = getDB();\n $db->query();\n }\n}\n function read_something() {\n $db = System::getDB();\n $db->query();\n}\n"
},
{
"answer_id": 228660,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "class MyClass {\n protected $_db;\n\n public function __construct($db)\n {\n $this->_db = $db;\n }\n\n public function doSomething()\n {\n $this->_db->query(...);\n }\n}\n"
},
{
"answer_id": 228663,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": -1,
"selected": false,
"text": "function usingFunc() {\n $connection = getConnection();\n ...\n}\n\nfunction getConnection() {\n static $connectionObject = null;\n if ($connectionObject == null) {\n $connectionObject = connectFoo(\"whatever\",\"connection\",\"method\",\"you\",\"choose\");\n }\n return $connectionObject;\n}\n"
},
{
"answer_id": 228715,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 3,
"selected": true,
"text": "class ResourceManager {\n private static $DB;\n private static $Config;\n\n public static function get($resource, $options = false) {\n if (property_exists('ResourceManager', $resource)) {\n if (empty(self::$$resource)) {\n self::_init_resource($resource, $options);\n }\n if (!empty(self::$$resource)) {\n return self::$$resource;\n }\n }\n return null;\n }\n\n private static function _init_resource($resource, $options = null) {\n if ($resource == 'DB') {\n $dsn = 'mysql:host=localhost';\n $username = 'my_username';\n $password = 'p4ssw0rd';\n try {\n self::$DB = new PDO($dsn, $username, $password);\n } catch (PDOException $e) {\n echo 'Connection failed: ' . $e->getMessage();\n }\n } elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) {\n self::$$resource = new $resource($options);\n }\n }\n}\n function doDBThingy() {\n $db = ResourceManager::get('DB');\n if ($db) {\n $stmt = $db->prepare('SELECT * FROM `table`');\n etc...\n }\n}\n"
},
{
"answer_id": 229383,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "Foo->doStuff() Foo Foo"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
228,595
|
<p>I have an ADO.Net Data Service that I am using to do a data import. There are a number of entities that are linked to by most entities. To do that during import I create those entities first, save them and then use .SetLink(EntityImport, "NavigationProperty", CreatedEntity). Now the first issue that I ran into was that the context did not always know about CreatedEntity (this is due to each of the entities being imported independently and a creation of a context as each item is created - I'd like to retain this functionality - i.e. I'm trying to avoid "just use one context" as the answer). </p>
<p>So I have a .AddToCreatedEntityType(CreatedEntity) before attempting to call SetLink. This of course works for the first time, but on the second pass I get the error message "the context is already tracking the entity". </p>
<p>Is there a way to check if the context is already tracking the entity (context.Contains(CreatedEntity) isn't yet implemented)? I was thinking about attempting a try catch and just avoiding the error, but that seems to create a new CreatedEntity each pass. It is looking like I need to use a LINQ to Data Services to get that CreatedEntity each time, but that seems innefficient - any suggestions?</p>
|
[
{
"answer_id": 228800,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 3,
"selected": false,
"text": "public static class EntityObjectExtensions\n{\n public static Boolean IsTracked(this EntityObject self)\n {\n return (self.EntityState & EntityState.Detached) != EntityState.Detached;\n }\n}\n"
},
{
"answer_id": 277103,
"author": "James_2195",
"author_id": 36086,
"author_profile": "https://Stackoverflow.com/users/36086",
"pm_score": 2,
"selected": false,
"text": "if (context.Entities.Where(entities => entities.Entity == currentItem).Any())\n{\n this.service.UpdateObject(currentItem); \n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25719/"
] |
228,614
|
<p>This is a bit of a lazyweb question but you get the rep so :-)</p>
<p>I have a Java class that returns instances of itself to allow chaining
(e.g. ClassObject.doStuff().doStuff())</p>
<p>For instance:</p>
<pre><code>public class Chainer
{
public Chainer doStuff()
{
/* Do stuff ... */
return this;
}
}
</code></pre>
<p>I would like to extend this class. Is there a way, perhaps using generics, to extend this class without having to overwrite each method signature?</p>
<p>E.g. not:</p>
<pre><code>public class ChainerExtender extends Chainer
{
public ChainerExtender doStuff()
{
super.doStuff();
return this;
}
}
</code></pre>
<p>I have tried:</p>
<pre><code>public class Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
return (A)this;
}
}
public class ChainerExtender extends Chainer
{
public <A extends Chainer> A doStuff()
{
/* Do stuff ... */
return super.doStuff();
}
}
</code></pre>
<p>But this didn't work giving the error:</p>
<pre><code>type parameters of <A>A cannot be determined;
no unique maximal instance exists for type variable A with upper bounds A,Chainer
</code></pre>
<p>Am I forced to have class declarations like:</p>
<pre><code>public class Chainer<T extends Chainer<T>> {}
public class ChainerExtender extends Chainer<ChainerExtender>
</code></pre>
<p>As per <a href="https://stackoverflow.com/questions/153994/generic-type-args-which-specificy-the-extending-class">this question</a>?</p>
|
[
{
"answer_id": 228632,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "public class Test {\n\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n ChainerExtender c = new ChainerExtender();\n c.doStuff().doStuff();\n }\n\n public static class Chainer\n {\n public <A extends Chainer> A doStuff()\n {\n /* Do stuff ... */\n System.out.println(\"Chainer\");\n return (A)this;\n }\n }\n\n public static class ChainerExtender extends Chainer\n {\n /** \n * @see test.Test.Chainer#doStuff()\n */\n @Override\n public <A extends Chainer> A doStuff()\n {\n System.out.println(\"ChainerExtender\");\n return super.doStuff();\n }\n }\n\n}\n ChainerExtender\nChainer\nChainerExtender\nChainer\n"
},
{
"answer_id": 228657,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "public interface IChainer\n{\n IChainer doStuff();\n IChainer doSomethingElse();\n}\n\npublic class Chainer implements IChainer\n{\n public IChainer doStuff()\n {\n // really do something\n return this;\n }\n\n public IChainer doSomethingElse()\n {\n return this; // do nothing\n }\n}\n\npublic class ChainerExtender extends Chainer\n{\n // simply inherits implementation for doStuff()\n\n public override IChainer doSomethingElse()\n {\n // really do something\n return this;\n }\n}\n"
},
{
"answer_id": 228867,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 1,
"selected": false,
"text": "super.doStuff() this"
},
{
"answer_id": 229907,
"author": "bhavanki",
"author_id": 24184,
"author_profile": "https://Stackoverflow.com/users/24184",
"pm_score": 2,
"selected": false,
"text": "Chainer ChainerExtender doOtherStuff Chainer"
},
{
"answer_id": 256693,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 4,
"selected": true,
"text": "public class Chainer\n{\n public Chainer doStuff()\n {\n /* Do stuff ... */\n return this;\n }\n}\n\npublic class ChainerExtender extends Chainer\n{\n @Override\n public ChainerExtender doStuff()\n {\n /* Do stuff ... */\n super.doStuff();\n return this;\n }\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
228,617
|
<p>I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don't want the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two functions then the decision has to be made at run-time or at compile-time autonomously).</p>
|
[
{
"answer_id": 228621,
"author": "worbel",
"author_id": 62575,
"author_profile": "https://Stackoverflow.com/users/62575",
"pm_score": 2,
"selected": false,
"text": "#include <windows.h> void clrscr()\n{\n HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);\n COORD coord = {0, 0};\n DWORD count;\n\n CONSOLE_SCREEN_BUFFER_INFO csbi;\n GetConsoleScreenBufferInfo(hStdOut, &csbi);\n\n FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);\n\n SetConsoleCursorPosition(hStdOut, coord);\n}\n"
},
{
"answer_id": 228625,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 6,
"selected": true,
"text": "#ifdef _WIN32"
},
{
"answer_id": 228627,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "cout << \"\\f\";\n void clrscr()\n{\n#ifdef _WIN32\n HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);\n COORD coord = {0, 0};\n DWORD count;\n CONSOLE_SCREEN_BUFFER_INFO csbi;\n GetConsoleScreenBufferInfo(hStdOut, &csbi);\n FillConsoleOutputCharacter(hStdOut, ' ',\n csbi.dwSize.X * csbi.dwSize.Y,\n coord, &count);\n SetConsoleCursorPosition(hStdOut, coord);\n#else\n cout << \"\\f\";\n#endif\n}\n"
},
{
"answer_id": 228628,
"author": "fmsf",
"author_id": 26004,
"author_profile": "https://Stackoverflow.com/users/26004",
"pm_score": 6,
"selected": false,
"text": "#include <cstdlib>\n\nvoid clear_screen()\n{\n#ifdef WINDOWS\n std::system(\"cls\");\n#else\n // Assume POSIX\n std::system (\"clear\");\n#endif\n}\n"
},
{
"answer_id": 263650,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 4,
"selected": false,
"text": "write(1,\"\\E[H\\E[2J\",7);\n"
},
{
"answer_id": 8202322,
"author": "fatpugsley",
"author_id": 1056458,
"author_profile": "https://Stackoverflow.com/users/1056458",
"pm_score": -1,
"selected": false,
"text": "for (int i=0;i<1000;i++){cout<<endl;}\n"
},
{
"answer_id": 15481700,
"author": "Nick",
"author_id": 2183165,
"author_profile": "https://Stackoverflow.com/users/2183165",
"pm_score": 4,
"selected": false,
"text": "#ifdef _WIN32\n#define CLEAR \"cls\"\n#else //In any other OS\n#define CLEAR \"clear\"\n#endif\n\n//And in the point you want to clear the screen:\n//....\nsystem(CLEAR);\n//....\n"
},
{
"answer_id": 28641993,
"author": "otboss",
"author_id": 4500996,
"author_profile": "https://Stackoverflow.com/users/4500996",
"pm_score": 1,
"selected": false,
"text": "for (i = 0; i < 100000; i++)\n{\n printf (\"\\n\\n\\n\\n\\n\");\n}\n"
},
{
"answer_id": 28642082,
"author": "Nupskill",
"author_id": 4524875,
"author_profile": "https://Stackoverflow.com/users/4524875",
"pm_score": -1,
"selected": false,
"text": "#include <conio.h>\n\nint main()\n\n{\n clrscr();\n}\n"
},
{
"answer_id": 33992073,
"author": "DrBeco",
"author_id": 670521,
"author_profile": "https://Stackoverflow.com/users/670521",
"pm_score": 3,
"selected": false,
"text": "void cls(void)\n{\n system(\"cls||clear\");\n return;\n}\n"
},
{
"answer_id": 47406222,
"author": "iBug",
"author_id": 5958455,
"author_profile": "https://Stackoverflow.com/users/5958455",
"pm_score": 1,
"selected": false,
"text": "// File: clear_screen.h\n#ifndef _CLEAR_SCREEN_H\n#define _CLEAR_SCREEN_H\nvoid clearScreen(void); /* Clears the screen */\n#endif /* _CLEAR_SCREEN_H */\n // File: clear_screen.c\n#ifdef _WIN32\n#include <windows.h>\nvoid clearScreen(void) {\n HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);\n COORD topLeft = {0, 0};\n DWORD dwCount, dwSize;\n CONSOLE_SCREEN_BUFFER_INFO csbi;\n GetConsoleScreenBufferInfo(hOutput, &csbi);\n dwSize = csbi.dwSize.X * csbi.dwSize.Y;\n FillConsoleOutputCharacter(hOutput, 0x20, dwSize, topLeft, &dwCount);\n FillConsoleOutputAttribute(hOutput, 0x07, dwSize, topLeft, &dwCount);\n SetConsoleCursorPosition(hOutput, topLeft);\n}\n#endif /* _WIN32 */\n\n#ifdef __unix__\n#include <stdio.h>\nvoid clearScreen(void) {\n printf(\"\\x1B[2J\");\n}\n#endif /* __unix__ */\n"
},
{
"answer_id": 66795344,
"author": "csmathhc",
"author_id": 14786728,
"author_profile": "https://Stackoverflow.com/users/14786728",
"pm_score": 1,
"selected": false,
"text": "std::system clear cls std::system #ifdef _WIN32\n#include <Windows.h>\n#endif\n\nvoid clrscr() {\n#ifdef _WIN32\n COORD tl = { 0,0 };\n CONSOLE_SCREEN_BUFFER_INFO s;\n HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);\n GetConsoleScreenBufferInfo(console, &s);\n DWORD written, cells = s.dwSize.X * s.dwSize.Y;\n FillConsoleOutputCharacter(console, ' ', cells, tl, &written);\n FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written);\n SetConsoleCursorPosition(console, tl);\n#else\n std::cout << \"\\033[2J\\033[1; 1H\";\n#endif\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62575/"
] |
228,620
|
<p>I keep hearing people complaining that C++ doesn't have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I'm afraid I just don't see the point to it... using RAII with smart pointers eliminates the need for it, right?</p>
<p>My only experience with garbage collection was on a couple of cheap eighties home computers, where it meant that the system would freeze up for a few seconds every so often. I'm sure it has improved since then, but as you can guess, that didn't leave me with a high opinion of it.</p>
<p>What advantages could garbage collection offer an experienced C++ developer?</p>
|
[
{
"answer_id": 229619,
"author": "David Cournapeau",
"author_id": 11465,
"author_profile": "https://Stackoverflow.com/users/11465",
"pm_score": 3,
"selected": false,
"text": "#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include <memory>\n\nusing namespace std;\n\nvolatile sig_atomic_t got_sigint = 0;\n\nclass A {\n public:\n A() { printf(\"ctor\\n\"); };\n ~A() { printf(\"dtor\\n\"); };\n};\n\nvoid catch_sigint (int sig)\n{\n got_sigint = 1;\n}\n\n/* Emulate expensive computation */\nvoid do_something()\n{\n sleep(3);\n}\n\nvoid handle_sigint()\n{\n printf(\"Caught SIGINT\\n\");\n exit(EXIT_FAILURE);\n}\n\nint main (void)\n{\n A a;\n auto_ptr<A> aa(new A);\n\n signal(SIGINT, catch_sigint);\n\n while (1) {\n if (got_sigint == 0) {\n do_something();\n } else {\n handle_sigint();\n return -1;\n }\n }\n}\n"
},
{
"answer_id": 17154645,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 2,
"selected": false,
"text": "weak_ptr free free"
},
{
"answer_id": 28330272,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "public class MaximumItemFinder\n{\n String maxItemName = \"\";\n int maxItemValue = -2147483647 - 1;\n\n public void AddAnother(int itemValue, String itemName)\n {\n if (itemValue >= maxItemValue)\n {\n maxItemValue = itemValue;\n maxItemName = itemName;\n }\n }\n public String getMaxItemName() { return maxItemName; }\n public int getMaxItemValue() { return maxItemValue; }\n}\n maxItemName = itemName; MaximumItemFinder AddAnother MaximumItemFinder getMaxItemName MaximumItemFinder AddAnother GetMaxItemName AddAnother int"
},
{
"answer_id": 30078169,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "shared_ptr R A B R C R A R B R C C C valgrind C R C"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
228,623
|
<p>This may be a simple fix - but I'm trying to sum together all the nodes (Size property from the Node class) on the binary search tree. Below in my BST class I have the following so far, but it returns 0:</p>
<pre><code> private long sum(Node<T> thisNode)
{
if (thisNode.Left == null && thisNode.Right == null)
return 0;
if (node.Right == null)
return sum(thisNode.Left);
if (node.Left == null)
return sum(thisNode.Right);
return sum(thisNode.Left) + sum(thisNode.Right);
}
</code></pre>
<p>Within my Node class I have Data which stores Size and Name in their given properties. I'm just trying to sum the entire size. Any suggestions or ideas?</p>
|
[
{
"answer_id": 228631,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": " if (thisNode.Left == null && thisNode.Right == null)\n return thisNode.Size;\n"
},
{
"answer_id": 228641,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "private long sum(Node<T> thisNode)\n{\n if (thisNode.Left == null && thisNode.Right == null)\n return thisNode.Size;\n if (node.Right == null)\n return thisNode.Size + sum(thisNode.Left);\n if (node.Left == null) \n return thisNode.Size + sum(thisNode.Right);\n return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);\n}\n private long sum(Node<T> thisNode)\n{\n if (thisNode.Left == null && thisNode.Right == null)\n return thisNode.Size;\n if (node.Right == null)\n return sum(thisNode.Left);\n if (node.Left == null) \n return sum(thisNode.Right);\n return sum(thisNode.Left) + sum(thisNode.Right);\n}\n private long sum(Node<T> thisNode)\n{\n if (thisNode == null)\n return 0;\n return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);\n}\n"
},
{
"answer_id": 228643,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 1,
"selected": false,
"text": "private long Sum(Node<T> thisNode)\n{\n if( thisNode == null )\n return 0;\n\n return thisNode.Size + Sum(thisNode.Left) + Sum(thisNode.Right);\n}\n public class Node<T>\n {\n public T Data;\n public Node<T> Left;\n public Node<T> Right;\n\n public static void ForEach(Node<T> root, Action<T> action)\n {\n action(root.Data);\n\n if (root.Left != null)\n ForEach(root.Left, action);\n if (root.Right != null)\n ForEach(root.Right, action);\n }\n }\n\n public interface IHasSize\n {\n long Size { get; }\n }\n\n public static long SumSize<T>(Node<T> root) where T : IHasSize\n {\n long sum = 0;\n Node<T>.ForEach(root, delegate(T item)\n {\n sum += item.Size;\n });\n return sum;\n }\n"
},
{
"answer_id": 228645,
"author": "EggyBach",
"author_id": 15475,
"author_profile": "https://Stackoverflow.com/users/15475",
"pm_score": 1,
"selected": false,
"text": " private long sum(Node<T> thisNode)\n {\n if (thisNode == null)\n return 0;\n return thisNode.Size + sum(thisNode.Left) + sum(thisNode.Right);\n }\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30649/"
] |
228,642
|
<p>Python is quite cool, but unfortunately, its debugger is not as good as perl -d. </p>
<p>One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:</p>
<pre><code># NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO()
~> cat -n /tmp/show_perl.pl
1 #!/usr/local/bin/perl
2
3 sub foo {
4 print "hi\n";
5 print "bye\n";
6 }
7
8 exit 0;
~> perl -d /tmp/show_perl.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(/tmp/show_perl.pl:8): exit 0;
# MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY
DB<1> s foo()
main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3: foo();
DB<<2>> s
main::foo(/tmp/show_perl.pl:4): print "hi\n";
DB<<2>> n
hi
main::foo(/tmp/show_perl.pl:5): print "bye\n";
DB<<2>> n
bye
DB<2> n
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<2> q
</code></pre>
<p>This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).</p>
<p>So my question is twofold:</p>
<ol>
<li>Am I missing something?</li>
<li>Is there a python debugger that would indeed let me do this?</li>
</ol>
<p>Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.</p>
|
[
{
"answer_id": 228653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "~> cat -n /tmp/test_python.py\n 1 #!/usr/local/bin/python\n 2\n 3 def foo():\n 4 print \"hi\"\n 5 print \"bye\"\n 6\n 7 exit(0)\n 8\n\n~> pydb /tmp/test_python.py\n(/tmp/test_python.py:7): <module>\n7 exit(0)\n\n\n(Pydb) debug foo()\nENTERING RECURSIVE DEBUGGER\n------------------------Call level 11\n(/tmp/test_python.py:3): foo\n3 def foo():\n\n((Pydb)) s\n(/tmp/test_python.py:4): foo\n4 print \"hi\"\n\n((Pydb)) s\nhi\n(/tmp/test_python.py:5): foo\n5 print \"bye\"\n\n\n((Pydb)) s\nbye\n------------------------Return from level 11 (<type 'NoneType'>)\n----------------------Return from level 10 (<type 'NoneType'>)\nLEAVING RECURSIVE DEBUGGER\n(/tmp/test_python.py:7): <module>\n"
},
{
"answer_id": 228662,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 2,
"selected": false,
"text": "def foo():\n a = 0\n print \"hi\"\n\n a += 1\n\n print \"bye\"\n\nfoo()\n $ python /usr/lib/python2.5/pdb.py /var/tmp/pdbtest.py ~\n> /var/tmp/pdbtest.py(2)<module>()\n-> def foo():\n(Pdb) s\n> /var/tmp/pdbtest.py(10)<module>()\n-> foo()\n(Pdb) s\n--Call--\n> /var/tmp/pdbtest.py(2)foo()\n-> def foo():\n(Pdb) s\n> /var/tmp/pdbtest.py(3)foo()\n-> a = 0\n(Pdb) s\n> /var/tmp/pdbtest.py(4)foo()\n-> print \"hi\"\n(Pdb) print a\n0\n(Pdb) s\nhi\n> /var/tmp/pdbtest.py(6)foo()\n-> a += 1\n(Pdb) s\n> /var/tmp/pdbtest.py(8)foo()\n-> print \"bye\"\n(Pdb) print a\n1\n(Pdb) s\nbye\n--Return--\n> /var/tmp/pdbtest.py(8)foo()->None\n-> print \"bye\"\n(Pdb) s\n--Return--\n> /var/tmp/pdbtest.py(10)<module>()->None\n-> foo()\n(Pdb) s\n"
},
{
"answer_id": 229311,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 2,
"selected": false,
"text": "pdb.set_trace if <state>: pdb.set_trace()"
},
{
"answer_id": 229380,
"author": "Simon",
"author_id": 22404,
"author_profile": "https://Stackoverflow.com/users/22404",
"pm_score": 5,
"selected": false,
"text": "$ cat test.py\n#!/usr/bin/python\n\ndef foo(f, g):\n h = f+g\n print h\n return 2*f\n $ python\nPython 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) \n[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import pdb\n>>> import test\n>>> pdb.runcall(test.foo, 1, 2)\n> /Users/simon/Desktop/test.py(4)foo()\n-> h = f+g\n(Pdb) n\n> /Users/simon/Desktop/test.py(5)foo()\n-> print h\n(Pdb) \n"
},
{
"answer_id": 230561,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 2,
"selected": false,
"text": "sudo aptitude install winpdb\n import rpdb2; rpdb2.start_embedded_debugger_interactive_password()\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
228,648
|
<p>I'm new to ruby and I'm playing around with the IRB.</p>
<p>I found that I can list methods of an object using the ".methods" method, and that self.methods sort of give me what I want (similar to Python's dir(<strong>builtins</strong>)?), but how can I find the methods of a library/module I've loaded via include and require?</p>
<pre><code>irb(main):036:0* self.methods
=> ["irb_pop_binding", "inspect", "taguri", "irb_chws", "clone", "irb_pushws", "public_methods", "taguri=", "irb_pwws",
"public", "display", "irb_require", "irb_exit", "instance_variable_defined?", "irb_cb", "equal?", "freeze", "irb_context
", "irb_pop_workspace", "irb_cwb", "irb_jobs", "irb_bindings", "methods", "irb_current_working_workspace", "respond_to?"
, "irb_popb", "irb_cws", "fg", "pushws", "conf", "dup", "cwws", "instance_variables", "source", "cb", "kill", "help", "_
_id__", "method", "eql?", "irb_pwb", "id", "bindings", "send", "singleton_methods", "popb", "irb_kill", "chws", "taint",
"irb_push_binding", "instance_variable_get", "frozen?", "irb_source", "pwws", "private", "instance_of?", "__send__", "i
rb_workspaces", "to_a", "irb_quit", "to_yaml_style", "irb_popws", "irb_change_workspace", "jobs", "type", "install_alias
_method", "irb_push_workspace", "require_gem", "object_id", "instance_eval", "protected_methods", "irb_print_working_wor
kspace", "irb_load", "require", "==", "cws", "===", "irb_pushb", "instance_variable_set", "irb_current_working_binding",
"extend", "kind_of?", "context", "gem", "to_yaml_properties", "quit", "popws", "irb", "to_s", "to_yaml", "irb_fg", "cla
ss", "hash", "private_methods", "=~", "tainted?", "include", "irb_cwws", "irb_change_binding", "irb_help", "untaint", "n
il?", "pushb", "exit", "irb_print_working_binding", "is_a?", "workspaces"]
irb(main):037:0>
</code></pre>
<p>I'm used to python, where I use the dir() function to accomplish the same thing:</p>
<pre><code>>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>>
</code></pre>
|
[
{
"answer_id": 228903,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "self.methods self.class File.methods"
},
{
"answer_id": 232272,
"author": "two-bit-fool",
"author_id": 23899,
"author_profile": "https://Stackoverflow.com/users/23899",
"pm_score": 3,
"selected": false,
"text": "dir() dir() included_modules dir() print Kernel false methods() def included_methods(object=self)\n object = object.class if object.class != Class\n modules = (object.included_modules-[Kernel])\n modules.collect{ |mod| mod.methods(false)}.flatten.sort\nend\n irb(main):006:0> included_methods\n=> []\nirb(main):007:0> include Math\n=> Object\nirb(main):008:0> included_methods\n=> [\"acos\", \"acosh\", \"asin\", \"asinh\", \"atan\", \"atan2\", \"atanh\", \"cos\", \"cosh\", \"erf\", \"erfc\", \"exp\", \"frexp\", \"hypot\", \"ldexp\", \"log\", \"log10\", \"sin\", \"sinh\", \"sqrt\", \"tan\", \"tanh\"]\n dir() local_variables\n local_variables included_methods included_methods (included_methods + local_variables).sort\n"
},
{
"answer_id": 235996,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 6,
"selected": false,
"text": "local_variables\ninstance_variables\nglobal_variables\n\nclass_variables\nconstants\n local_variables #=> [\"_\"]\nfoo = \"bar\"\nlocal_variables #=> [\"_\", \"foo\"]\n# Note: the _ variable in IRB contains the last value evaluated\n_ #=> \"bar\"\n\ninstance_variables #=> []\n@inst_var = 42\ninstance_variables #=> [\"@inst_var\"]\n\nglobal_variables #=> [\"$-d\", \"$\\\"\", \"$$\", \"$<\", \"$_\", ...]\n$\" #=> [\"e2mmap.rb\", \"irb/init.rb\", \"irb/workspace.rb\", ...]\n eval \"@inst_var\" #=> 42\nglobal_variables.each do |v|\n puts eval(v)\nend\n Object.class_variables #=> []\nObject.constants #=> [\"IO\", \"Duration\", \"UNIXserver\", \"Binding\", ...]\n\nclass MyClass\n A_CONST = 'pshh'\n class InnerClass\n end\n def initialize\n @@meh = \"class_var\"\n end\nend\n\nMyClass.constants #=> [\"A_CONST\", \"InnerClass\"]\nMyClass.class_variables #=> []\nmc = MyClass.new\nMyClass.class_variables #=> [\"@@meh\"]\nMyClass.class_eval \"@@meh\" #=> \"class_var\"\n \"\".class #=> String\n\"\".class.ancestors #=> [String, Enumerable, Comparable, ...]\nString.ancestors #=> [String, Enumerable, Comparable, ...]\n\ndef trace\n return caller\nend\ntrace #=> [\"(irb):67:in `irb_binding'\", \"/System/Library/Frameworks/Ruby...\", ...]\n"
},
{
"answer_id": 4132930,
"author": "Tomtt",
"author_id": 501795,
"author_profile": "https://Stackoverflow.com/users/501795",
"pm_score": 3,
"selected": false,
"text": "$ gem install method_info\n$ rvm use 1.8.7 # (1.8.6 works but can be very slow for an object with a lot of methods)\n$ irb\n> require 'method_info'\n> 5.method_info\n::: Fixnum :::\n%, &, *, **, +, -, -@, /, <, <<, <=, <=>, ==, >, >=, >>, [], ^, abs,\ndiv, divmod, even?, fdiv, id2name, modulo, odd?, power!, quo, rdiv,\nrpower, size, to_f, to_s, to_sym, zero?, |, ~\n::: Integer :::\nceil, chr, denominator, downto, floor, gcd, gcdlcm, integer?, lcm,\nnext, numerator, ord, pred, round, succ, taguri, taguri=, times, to_i,\nto_int, to_r, to_yaml, truncate, upto\n::: Precision :::\nprec, prec_f, prec_i\n::: Numeric :::\n+@, coerce, eql?, nonzero?, pretty_print, pretty_print_cycle,\nremainder, singleton_method_added, step\n::: Comparable :::\nbetween?\n::: Object :::\nclone, to_yaml_properties, to_yaml_style, what?\n::: MethodInfo::ObjectMethod :::\nmethod_info\n::: Kernel :::\n===, =~, __clone__, __id__, __send__, class, display, dup, enum_for,\nequal?, extend, freeze, frozen?, hash, id, inspect, instance_eval,\ninstance_exec, instance_of?, instance_variable_defined?,\ninstance_variable_get, instance_variable_set, instance_variables,\nis_a?, kind_of?, method, methods, nil?, object_id, pretty_inspect,\nprivate_methods, protected_methods, public_methods, respond_to?, ri,\nsend, singleton_methods, taint, tainted?, tap, to_a, to_enum, type,\nuntaint\n => nil\n require 'method_info'\nMethodInfo::OptionHandler.default_options = {\n :ancestors_to_exclude => [Object],\n :enable_colors => true\n}\n"
},
{
"answer_id": 38624205,
"author": "MarioR",
"author_id": 6647036,
"author_profile": "https://Stackoverflow.com/users/6647036",
"pm_score": 2,
"selected": false,
"text": "Object.constants.select{|x| eval(x.to_s).class == Class}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24718/"
] |
228,672
|
<p>I am part of a team creating a web application using PHP and MySQL. The application will have multiple users with different roles. The application will also be used in a geographically distributed manner. Accordingly we need to create an access control system that operates at the following two levels:</p>
<ol>
<li>Controls user permissions for specific php pages i.e. provides or denies access to specific pages (or user interface elements) based on the user's role. For example: a user may be allowed access to the "Students" page but not to the "Teachers" page.</li>
<li>Controls user permissions for specific database records i.e. modifies database queries so that only specific records are displayed. For example, for a user at the city level, only those records should be displayed that relate to the user's particular city, while for a user at the national level, records for ALL CITIES in the country should be displayed.</li>
</ol>
<p>I need help on designing a system that can handle both these types of access control. Point no. 1 seems to be simple enough. However, I am completely at a loss on how to do point number 2 without hardcoding the information in the SQL queries.</p>
<p>Any help would be appreciated. </p>
<p>Thanks in advance</p>
<p>Vinayak</p>
|
[
{
"answer_id": 325805,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 5,
"selected": true,
"text": "IAuthorizable"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22009/"
] |
228,680
|
<p>How does one import CSV files via Excel VBA in a set, in groups or in multiple individual files, rather than one at a time?</p>
|
[
{
"answer_id": 228973,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 1,
"selected": false,
"text": "Open \"myfile.csv\" For Input As 1\nDim Txt As String\nTxt = Input(LOF(1), 1)\nClose #1\nDim V As Variant\nV = Split(Txt, \",\")\n"
},
{
"answer_id": 231640,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "strPath = \"C:\\Docs\\\"\nstrFile = Dir(strPath & \"*.csv\")\n\nDo While strFile <> \"\"\n Workbooks.Open Filename:=strPath & strFile\n ActiveWorkbook.SaveAs Filename:=strPath & Mid(strFile, 1, InStr(strFile, \".\") - 1) _\n & \"Conv.xls\", FileFormat:=xlNormal\n\n strFile = Dir\nLoop\n"
},
{
"answer_id": 245649,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "Dog Names,Dog Ages,Collar Size\nWoof,3,4\nBowser,2,5\nRuffy,4.5,6\nAngel,1,7\nDemon,7,8\nDog,9,2\n Dog_Names Dog_Ages Collar_Size wscript.echo x Option Explicit\n\nDim FSO\nSet FSO = CreateObject( \"Scripting.FileSystemObject\" )\n\nDim oStream\nDim sData\nDim aData\n\nSet oStream = fso.OpenTextFile(\"data.csv\")\nsData = oStream.ReadAll\naData = Split( sData, vbNewLine )\n\nDim sLine\nsLine = aData(0)\n\nDim aContent\naContent = Split( sLine, \",\" )\n\nDim aNames()\nDim nArrayCount\nnArrayCount = UBound( aContent )\nReDim aNames( nArrayCount )\n\nDim i\n\nFor i = 0 To nArrayCount\n aNames(i) = Replace( aContent( i ), \" \", \"_\" )\n x \"dim \" & aNames(i) & \"()\"\nNext\n\nFor j = 0 To nArrayCount\n x \"redim \" & aNames(j) & \"( \" & UBound( aData ) - 1 & \" )\"\nNext\n\nDim j\nDim actual\nactual = 0\n\nFor i = 1 To UBound( aData )\n sLine = aData( i )\n If sLine <> vbnullstring Then\n actual = actual + 1\n aContent = Split( sLine, \",\" )\n For j = 0 To nArrayCount\n x aNames(j) & \"(\" & i - 1 & \")=\" & Chr(34) & aContent(j) & Chr(34)\n Next\n End If\nNext\n\nFor j = 0 To nArrayCount\n x \"redim preserve \" & aNames(j) & \"(\" & actual - 1 & \")\"\nNext\n\nFor i = 0 To actual - 1\n For j = 0 To nArrayCount\n x \"wscript.echo aNames(\" & j & \"),\" & aNames(j) & \"(\" & i & \")\"\n Next\nNext\n\nSub x( s )\n 'wscript.echo s\n executeglobal s\nEnd Sub\n >cscript \"C:\\Documents and Settings\\Bruce\\Desktop\\datathing.vbs\"\nDog_Names Woof\nDog_Ages 3\nCollar_Size 4\nDog_Names Bowser\nDog_Ages 2\nCollar_Size 5\nDog_Names Ruffy\nDog_Ages 4.5\nCollar_Size 6\nDog_Names Angel\nDog_Ages 1\nCollar_Size 7\nDog_Names Demon\nDog_Ages 7\nCollar_Size 8\nDog_Names Dog\nDog_Ages 9\nCollar_Size 2\n>Exit code: 0 Time: 0.338\n"
},
{
"answer_id": 6384945,
"author": "njt",
"author_id": 803119,
"author_profile": "https://Stackoverflow.com/users/803119",
"pm_score": 1,
"selected": false,
"text": "Function getCsv(fn)\n Dim d, scrup As Boolean\n scrup = Application.ScreenUpdating\n Application.ScreenUpdating = False\n With Me.QueryTables.Add( _\n Connection:=\"TEXT;\" & fn, _\n Destination:=Me.Range(\"A1\") _\n )\n .Name = \"data\"\n .FieldNames = True\n .RowNumbers = False\n .FillAdjacentFormulas = False\n .PreserveFormatting = True\n .RefreshStyle = xlOverwriteCells\n .SavePassword = False\n .SaveData = True\n .AdjustColumnWidth = False\n .TextFilePromptOnRefresh = False\n .TextFilePlatform = 850\n .TextFileStartRow = 1\n .TextFileParseType = xlDelimited\n .TextFileTextQualifier = xlTextQualifierDoubleQuote\n .TextFileCommaDelimiter = True\n .Refresh BackgroundQuery:=False\n End With\n\n d = Me.Names(1).RefersToRange.Value\n\n Me.Names(1).Delete\n Me.UsedRange.Rows.Delete\n\n Application.ScreenUpdating = scrup\n getCsv = d\nEnd Function\n dim d\nd = getCsv(\"C:\\temp\\some.csv\")\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
228,684
|
<p>If I have a source.c file with a struct:</p>
<pre><code>struct a {
int i;
struct b {
int j;
}
};
</code></pre>
<p>How can this struct be used in another file (i.e. <code>func.c</code>)?</p>
<p>Should I create a new header file, declare the struct there and include that header in <code>func.c</code>?</p>
<p>Or should I define the whole struct in a header file and include that in both <code>source.c</code> and <code>func.c</code>? How can the struct be declared <code>extern</code> in both files?</p>
<p>Should I <code>typedef</code> it? If so, how?</p>
|
[
{
"answer_id": 228689,
"author": "fmsf",
"author_id": 26004,
"author_profile": "https://Stackoverflow.com/users/26004",
"pm_score": 3,
"selected": false,
"text": "#ifndef A_H\n#define A_H\n\nstruct a { \n int i;\n struct b {\n int j;\n }\n};\n\n#endif\n"
},
{
"answer_id": 228691,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": false,
"text": "extern extern extern struct a myAValue;\n struct a myAValue;\n"
},
{
"answer_id": 228757,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": false,
"text": "#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME\n#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME\n\nstruct a\n{ \n int i;\n struct b\n {\n int j;\n }\n};\n\n#endif\n struct a ;\n struct MyStruct ; /* Forward declaration */\n\nstruct MyStruct\n{\n /* etc. */\n} ;\n\nvoid doSomething(struct MyStruct * p) /* parameter */\n{\n struct MyStruct a ; /* variable */\n /* etc */\n}\n struct MyStructTag ; /* Forward declaration */\n\ntypedef struct MyStructTag\n{\n /* etc. */\n} MyStruct ;\n\nvoid doSomething(MyStruct * p) /* parameter */\n{\n MyStruct a ; /* variable */\n /* etc */\n}\n typedef struct\n{\n /* etc. */\n} MyStruct ;\n typedef struct MyStructTag\n{\n /* etc. */\n} MyStruct ;\n typedef struct MyStruct\n{\n /* etc. */\n} MyStruct ;\n // C++ explicit declaration by the user\nstruct MyStruct\n{\n /* etc. */\n} ;\n// C++ standard then implicitly adds the following line\ntypedef MyStruct MyStruct;\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
228,702
|
<p>Say I have the classic 4-byte signed integer, and I want something like</p>
<pre><code>print hex(-1)
</code></pre>
<p>to give me something like</p>
<blockquote>
<p>0xffffffff</p>
</blockquote>
<p>In reality, the above gives me <code>-0x1</code>. I'm dawdling about in some lower level language, and python commandline is quick n easy.</p>
<p>So.. is there a way to do it?</p>
|
[
{
"answer_id": 228708,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 6,
"selected": true,
"text": ">>> print(hex (-1 & 0xffffffff))\n0xffffffff\n >>> def hex3(n):\n... return \"0x%s\"%(\"00000000%s\"%(hex(n&0xffffffff)[2:-1]))[-8:]\n...\n>>> print hex3(-1)\n0xffffffff\n>>> print hex3(17)\n0x00000011\n def hex2(n):\n return \"0x%x\"%(n&0xffffffff)\n\ndef hex3(n):\n return \"0x%s\"%(\"00000000%x\"%(n&0xffffffff))[-8:]\n"
},
{
"answer_id": 228785,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 2,
"selected": false,
"text": "'%#4x' % (-1 & 0xffffffff)\n"
},
{
"answer_id": 39483945,
"author": "Sai Gautam",
"author_id": 4499207,
"author_profile": "https://Stackoverflow.com/users/4499207",
"pm_score": 2,
"selected": false,
"text": "\"0x{:04x}\".format((int(my_num) & 0xFFFF), '04x')\n my_num"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23648/"
] |
228,705
|
<p>I know I'm gonna get down votes, but I have to make sure if this is logical or not.</p>
<p>I have three tables A, B, C. B is a table used to make a many-many relationship between A and C. But the thing is that A and C are also related directly in a 1-many relationship</p>
<p>A customer added the following requirement:</p>
<p>Obtain the information from the Table B inner joining with A and C, and in the same query relate A and C in a one-many relationship</p>
<p>Something like:</p>
<p><a href="http://img247.imageshack.us/img247/7371/74492374sa4.png" rel="nofollow noreferrer">alt text http://img247.imageshack.us/img247/7371/74492374sa4.png</a></p>
<p>I tried doing the query but always got 0 rows back. The customer insists that I can accomplish the requirement, but I doubt it. Any comments?</p>
<p>PS. I didn't have a more descriptive title, any ideas?</p>
<p>UPDATE:
Thanks to rcar, In some cases this can be logical, in order to have a history of all the classes a student has taken (supposing the student can only take one class at a time)</p>
<p>UPDATE:
There is a table for Contacts, a table with the Information of each Contact, and the Relationship table. To get the information of a Contact I have to make a 1:1 relationship with Information, and each contact can have like and an address book with; this is why the many-many relationship is implemented.</p>
<p>The full idea is to obtain the contact's name and his address book.
Now that I got the customer's idea... I'm having trouble with the query, basically I am trying to use the query that jdecuyper wrote, but as he warns, I get no data back</p>
|
[
{
"answer_id": 228739,
"author": "jdecuyper",
"author_id": 296,
"author_profile": "https://Stackoverflow.com/users/296",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM relAC RAC\n INNER JOIN tableA A ON A.id_class = RAC.id_class \n INNER JOIN tableC C ON C.id_class = RAC.id_class \n WHERE A.id_class = B.id_class\n"
},
{
"answer_id": 228742,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 3,
"selected": false,
"text": "SELECT s.name AS \"student name\", c1.className AS \"student class\", c2.className as \"class list\"\nFROM s\nJOIN many_to_many mtm ON s.id_student = mtm.id_student\nJOIN c c1 ON s.id_class = c1.id_class\nJOIN c c2 ON mtm.id_class = c2.id_class\n"
},
{
"answer_id": 228744,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 2,
"selected": false,
"text": "student class"
},
{
"answer_id": 231081,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "SELECT s.name, c.className, (s.id_class = c.id_class) AS is_current\nFROM s JOIN many_to_many AS mtm ON (s.id_student = mtm.id_student)\n JOIN c ON (c.id_class = mtm.id_class);\n CASE SELECT s.name, c.className, \n CASE WHEN s.id_class = c.id_class THEN 'current' ELSE 'past' END AS is_current\nFROM s JOIN many_to_many AS mtm ON (s.id_student = mtm.id_student)\n JOIN c ON (c.id_class = mtm.id_class);\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23146/"
] |
228,723
|
<p>Now that Silverlight 2 has finally shipped. I'm wondering if anyone has put together any logging frameworks for it, maybe something like <a href="http://msdn.microsoft.com/en-us/library/ff647183.aspx" rel="noreferrer">enterprise library logging</a> or <a href="http://logging.apache.org/log4net/" rel="noreferrer">log4net</a>? I'm interesting in something that can perform tracing client side and also log messages to the server.</p>
<p>So far the only project I have found is <a href="http://clog.codeplex.com/" rel="noreferrer">Clog</a> on <a href="http://www.codeproject.com/KB/silverlight/SilverlightLogging.aspx" rel="noreferrer">CodeProject</a>. Has anyone used this? What were your thoughts on it?</p>
|
[
{
"answer_id": 905607,
"author": "Rene Schulte",
"author_id": 79954,
"author_profile": "https://Stackoverflow.com/users/79954",
"pm_score": 3,
"selected": false,
"text": " // http://kodierer.blogspot.com.es/2009/05/silverlight-logging-extension-method.html\n public static string Log(string message)\n {\n var msgLog = \"\";\n try\n {\n\n HtmlWindow window = HtmlPage.Window;\n\n //only log if a console is available\n var isConsoleAvailable = (bool)window.Eval(\"typeof(console) != 'undefined' && typeof(console.log) != 'undefined'\");\n\n if (!isConsoleAvailable) return \"isConsoleAvailable \" + isConsoleAvailable;\n\n var createLogFunction = (bool)window.Eval(\"typeof(ssplog) == 'undefined'\");\n if (createLogFunction)\n {\n // Load the logging function into global scope:\n string logFunction = @\"function ssplog(msg) { console.log(msg); }\";\n string code = string.Format(@\"if(window.execScript) {{ window.execScript('{0}'); }} else {{ eval.call(null, '{0}'); }}\", logFunction);\n window.Eval(code);\n }\n\n // Prepare the message\n DateTime dateTime = DateTime.Now;\n string output = string.Format(\"{0} - {1} - {2}\", dateTime.ToString(\"u\"), \"DEBUG\", message);\n\n // Invoke the logging function:\n var logger = window.Eval(\"ssplog\") as ScriptObject;\n logger.InvokeSelf(output);\n }\n catch (Exception ex)\n {\n msgLog = \"Error Log \" + ex.Message;\n }\n return msgLog;\n\n }\n"
},
{
"answer_id": 3194094,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 4,
"selected": false,
"text": "IsolateStorage Read /// <summary>\n/// A lightweight logging class for Silverlight.\n/// </summary>\npublic class Log\n{\n /// <summary>\n /// The log file to write to. Defaults to \"dd-mm-yyyy.log\" e.g. \"13-01-2010.log\"\n /// </summary>\n public static string LogFilename { get; set; }\n\n /// <summary>\n /// Whether to appendthe calling method to the start of the log line.\n /// </summary>\n public static bool UseStackFrame { get; set; }\n\n static Log()\n {\n LogFilename = string.Format(\"{0}.log\", DateTime.Today.ToString(\"dd-MM-yyyy\"));\n UseStackFrame = false;\n }\n\n /// <summary>\n /// Reads the entire log file, or returns an empty string if it doesn't exist yet.\n /// </summary>\n /// <returns></returns>\n public static string ReadLog()\n {\n string result = \"\";\n IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite();\n\n if (storage.FileExists(LogFilename))\n {\n try\n {\n using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(LogFilename,FileMode.OpenOrCreate,storage))\n {\n using (StreamReader reader = new StreamReader(stream))\n {\n result = reader.ReadToEnd();\n }\n }\n }\n catch (IOException)\n {\n // Ignore\n }\n }\n\n return result;\n }\n\n /// <summary>\n /// Writes information (not errors) to the log file.\n /// </summary>\n /// <param name=\"format\">A format string</param>\n /// <param name=\"args\">Any arguments for the format string.</param>\n public static void Info(string format, params object[] args)\n {\n WriteLine(LoggingLevel.Info, format, args);\n }\n\n /// <summary>\n /// Writes a warning (non critical error) to the log file\n /// </summary>\n /// <param name=\"format\">A format string</param>\n /// <param name=\"args\">Any arguments for the format string.</param>\n public static void Warn(string format, params object[] args)\n {\n WriteLine(LoggingLevel.Warn, format, args);\n }\n\n /// <summary>\n /// Writes a critical or fatal error to the log file.\n /// </summary>\n /// <param name=\"format\">A format string</param>\n /// <param name=\"args\">Any arguments for the format string.</param>\n public static void Fatal(string format, params object[] args)\n {\n WriteLine(LoggingLevel.Fatal, format, args);\n }\n\n /// <summary>\n /// Writes the args to the default logging output using the format provided.\n /// </summary>\n public static void WriteLine(LoggingLevel level, string format, params object[] args)\n {\n string message = string.Format(format, args);\n\n // Optionally show the calling method\n if (UseStackFrame)\n {\n var name = new StackFrame(2, false).GetMethod().Name;\n\n string prefix = string.Format(\"[{0} - {1}] \", level, name);\n message = string.Format(prefix + format, args);\n }\n\n Debug.WriteLine(message);\n WriteToFile(message);\n }\n\n /// <summary>\n /// Writes a line to the current log file.\n /// </summary>\n /// <param name=\"message\"></param>\n private static void WriteToFile(string message)\n {\n try\n {\n IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite();\n bool b = storage.FileExists(LogFilename);\n\n using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(LogFilename,FileMode.Append,storage))\n {\n using (StreamWriter writer = new StreamWriter(stream))\n {\n writer.WriteLine(\"[{0}] {1}\", DateTime.UtcNow.ToString(), message);\n }\n }\n }\n catch (IOException)\n {\n // throw new Catch22Exception();\n }\n }\n}\n\n/// <summary>\n/// The type of error to log.\n/// </summary>\npublic enum LoggingLevel\n{\n /// <summary>\n /// A message containing information only.\n /// </summary>\n Info,\n /// <summary>\n /// A non-critical warning error message.\n /// </summary>\n Warn,\n /// <summary>\n /// A fatal error message.\n /// </summary>\n Fatal\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30664/"
] |
228,724
|
<p>Im creating a report using crystal report in vb.net.</p>
<p>The report contained a crosstab which I have 3 data:
1. Dealer - row field
2. Month - column
3. Quantity Sales - summarize field</p>
<p>How can I arrange this by ascending order based on the
Quantity Sales - summarize field?</p>
<p>thanks</p>
|
[
{
"answer_id": 234541,
"author": "thismat",
"author_id": 14045,
"author_profile": "https://Stackoverflow.com/users/14045",
"pm_score": 2,
"selected": false,
"text": "SELECT customer, sum(amountdue) AS total FROM invoices \nGROUP BY customer\nORDER BY total ASC\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
228,726
|
<p>The coding is done using VS2008
There are two divs in my page namely "dvLeftContent" and "dvRightContent".
I cannot statically set the height of the pages since "dvRightContent" have variable heights on various pages (Master Pages are used here)
Is there a client side function(javascript or jquery) that takes the height of the right div and assigns it to left div?</p>
|
[
{
"answer_id": 234541,
"author": "thismat",
"author_id": 14045,
"author_profile": "https://Stackoverflow.com/users/14045",
"pm_score": 2,
"selected": false,
"text": "SELECT customer, sum(amountdue) AS total FROM invoices \nGROUP BY customer\nORDER BY total ASC\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17447/"
] |
228,730
|
<p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
|
[
{
"answer_id": 228734,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 2,
"selected": false,
"text": "for letter in range(ord('a'), ord('z') + 1):\n print chr(letter) + \":\", lowertext.count(chr(letter))\n"
},
{
"answer_id": 228762,
"author": "Matthew Trevor",
"author_id": 11265,
"author_profile": "https://Stackoverflow.com/users/11265",
"pm_score": 4,
"selected": false,
"text": "import string\n\nallTheLetters = string.ascii_lowercase\n\ndef alphCount(text):\n lowerText = text.lower()\n for letter in allTheLetters: \n print letter + \":\", lowertext.count(letter)\n"
},
{
"answer_id": 228766,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "import string\nstring.ascii_lowercase\n counters = dict()\nfor letter in string.ascii_lowercase:\n counters[letter] = lowertext.count(letter)\n counters = \n dict( (letter,lowertext.count(letter)) for letter in string.ascii_lowercase )\n"
},
{
"answer_id": 228790,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": false,
"text": "s = 'hi there'\nf = {}\n\nfor c in s:\n f[c] = f.get(c, 0) + 1\n\nprint f\n"
},
{
"answer_id": 228845,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 2,
"selected": false,
"text": "import string\nfor c in string.lowercase:\n print c\n import string\n\nsample = \"Hello there, this is a test!\"\nletter_freq = dict((c,0) for c in string.lowercase)\n\nfor c in [c for c in sample.lower() if c.isalpha()]:\n letter_freq[c] += 1\n\nprint letter_freq\n"
},
{
"answer_id": 228850,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 7,
"selected": true,
"text": "import string\nallTheLetters = string.lowercase\n def getAllTheLetters(begin='a', end='z'):\n beginNum = ord(begin)\n endNum = ord(end)\n for number in xrange(beginNum, endNum+1):\n yield chr(number)\n True import string\nprint ''.join(getAllTheLetters()) == string.lowercase\n from collections import defaultdict \ndef letterOccurrances(string):\n frequencies = defaultdict(lambda: 0)\n for character in string:\n frequencies[character.lower()] += 1\n return frequencies\n occs = letterOccurrances(\"Hello, world!\")\nprint occs['l']\nprint occs['h']\n # -*- coding: utf-8 -*-\noccs = letterOccurrances(u\"héĺĺó, ẃóŕĺd!\")\nprint occs[u'l']\nprint occs[u'ĺ']\n def alphCount(text):\n for character, count in sorted(letterOccurrances(text).iteritems()):\n print \"%s: %s\" % (character, count)\n\nalphCount(\"hello, world!\")\n"
},
{
"answer_id": 8659737,
"author": "Kimvais",
"author_id": 180174,
"author_profile": "https://Stackoverflow.com/users/180174",
"pm_score": 2,
"selected": false,
"text": "from collections import Counter\nimport string\n\nc = Counter()\nfor letter in text.lower():\n c[letter] += 1\n\nfor letter in string.lowercase:\n print(\"%s: %d\" % (letter, c[letter]))\n"
},
{
"answer_id": 10820994,
"author": "masnun",
"author_id": 301107,
"author_profile": "https://Stackoverflow.com/users/301107",
"pm_score": -1,
"selected": false,
"text": "import string\nfor x in list(string.lowercase):\n print x\n"
},
{
"answer_id": 14206285,
"author": "user1956583",
"author_id": 1956583,
"author_profile": "https://Stackoverflow.com/users/1956583",
"pm_score": 0,
"selected": false,
"text": "import random\nimport string\n\nchars = string.letters + string.digits + string.punctuation\nchars_len = len(chars)\nn = 40\n\nprint(''.join([chars[random.randint(0, chars_len)] for i in range(n)]))\n"
},
{
"answer_id": 15001537,
"author": "guest",
"author_id": 2095294,
"author_profile": "https://Stackoverflow.com/users/2095294",
"pm_score": 0,
"selected": false,
"text": "import string\nstring.lowercase \nstring.uppercase\n string.letters[:26] \nstring.letters[26:]\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
228,775
|
<p>I'm trying to do some async stuff in a webservice method. Let say I have the following API call: <a href="http://www.example.com/api.asmx" rel="nofollow noreferrer">http://www.example.com/api.asmx</a></p>
<p>and the method is called <em>GetProducts()</em>.</p>
<p>I this GetProducts methods, I do some stuff (eg. get data from database) then just before i return the result, I want to do some async stuff (eg. send me an email).</p>
<p>So this is what I did.</p>
<pre><code>[WebMethod(Description = "Bal blah blah.")]
public IList<Product> GetProducts()
{
// Blah blah blah ..
// Get data from DB .. hi DB!
// var myData = .......
// Moar clbuttic blahs :) (yes, google for clbuttic if you don't know what that is)
// Ok .. now send me an email for no particular reason, but to prove that async stuff works.
var myObject = new MyObject();
myObject.SendDataAsync();
// Ok, now return the result.
return myData;
}
}
public class TrackingCode
{
public void SendDataAsync()
{
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += BackgroundWorker_DoWork;
backgroundWorker.RunWorkerAsync();
//System.Threading.Thread.Sleep(1000 * 20);
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
SendEmail();
}
}
</code></pre>
<p>Now, when I run this code the email is never sent. If I uncomment out the Thread.Sleep .. then the email is sent.</p>
<p>So ... why is it that the background worker thread is torn down? is it dependant on the parent thread? Is this the wrong way I should be doing background or forked threading, in asp.net web apps?</p>
|
[
{
"answer_id": 228798,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "BackgroundWorker ThreadPool ThreadPool public void SendDataAsync()\n{\n ThreadPool.QueueUserWorkItem(delegate\n {\n SendEmail();\n });\n}\n"
},
{
"answer_id": 241708,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "Semaphore ThreadPool CustomThreadPool"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
228,783
|
<p>It's common in C++ to name member variables with some kind of prefix to denote the fact that they're member variables, rather than local variables or parameters. If you've come from an MFC background, you'll probably use <code>m_foo</code>. I've also seen <code>myFoo</code> occasionally.</p>
<p>C# (or possibly just .NET) seems to recommend using just an underscore, as in <code>_foo</code>. Is this allowed by the C++ standard?</p>
|
[
{
"answer_id": 228797,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 11,
"selected": true,
"text": "std __ ::std #undef errno math_errhandling setjmp va_end E is to LC_ f l SIG SIG_ str mem wcs PRI SCN X _t _t _t"
},
{
"answer_id": 228848,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 8,
"selected": false,
"text": "#define _WRONG\n#define __WRONG_AGAIN\n#define RIGHT_\n#define WRONG__WRONG\n#define RIGHT_RIGHT\n#define RIGHT_x_RIGHT\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
228,795
|
<p>If I have the following code (this was written in .NET)</p>
<pre><code>double i = 0.1 + 0.1 + 0.1;
</code></pre>
<p>Why doesn't <code>i</code> equal <code>0.3</code>?<br>
Any ideas?</p>
|
[
{
"answer_id": 228802,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "if (abs(a-b) < epsilon) { ...\n"
},
{
"answer_id": 228808,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 1,
"selected": false,
"text": "Decimal"
},
{
"answer_id": 228828,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "decimal"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
228,796
|
<p>I want to write a odometer-like method in a C#-style-language, but not just using 0-9 for characters, but any set of characters. It will act like a brute-force application, more or less.</p>
<p>If I pass in a char-array of characters from <strong>0</strong> to <strong>J</strong>, and set length to 5, I want results like <em>00000, 00001, 00002... HJJJJ, IJJJJJ, JJJJJ</em>.</p>
<p>Here is the base, please help me expand:</p>
<pre><code>protected void Main()
{
char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
BruteForce(chars, 5);
}
private void BruteForce(char[] chars, int length)
{
// for-loop (?) console-writing all possible combinations from 00000 to JJJJJ
// (when passed in length is 5)
// TODO: Implement code...
}
</code></pre>
|
[
{
"answer_id": 228815,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "for (int i = 0; i < (1 << 24); i++)\n string s = i.ToString(\"X6\");\n"
},
{
"answer_id": 228825,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<string> private static IEnumerable<string> GetAllMatches(char[] chars, int length)\n{\n int[] indexes = new int[length];\n char[] current = new char[length];\n for (int i=0; i < length; i++)\n {\n current[i] = chars[0];\n }\n do\n {\n yield return new string(current);\n }\n while (Increment(indexes, current, chars));\n}\n\nprivate static bool Increment(int[] indexes, char[] current, char[] chars)\n{\n int position = indexes.Length-1;\n\n while (position >= 0)\n {\n indexes[position]++;\n if (indexes[position] < chars.Length)\n {\n current[position] = chars[indexes[position]];\n return true;\n }\n indexes[position] = 0;\n current[position] = chars[0];\n position--;\n }\n return false;\n}\n"
},
{
"answer_id": 231533,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 0,
"selected": false,
"text": "public class BaseNCounter\n{\n public char[] CharSet { get; set; }\n public int Power { get; set; }\n\n public BaseNCounter() { }\n\n public IEnumerable<string> Count() {\n long max = (long)Math.Pow((double)this.CharSet.Length, (double)this.Power);\n long[] counts = new long[this.Power];\n for(long i = 0; i < max; i++)\n yield return IncrementArray(ref counts, i);\n }\n\n public string IncrementArray(ref long[] counts, long count) {\n long temp = count;\n for (int i = this.Power - 1; i >= 0 ; i--) {\n long pow = (long)Math.Pow(this.CharSet.Length, i);\n counts[i] = temp / pow;\n temp = temp % pow;\n }\n\n StringBuilder sb = new StringBuilder();\n foreach (int c in counts) sb.Insert(0, this.CharSet[c]);\n return sb.ToString();\n }\n}\n class Program\n{\n static void Main(string[] args)\n {\n BaseNCounter c = new BaseNCounter() { \n CharSet = new char [] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }, \n Power = 2};\n\n foreach(string cc in c.Count())\n Console.Write(\"{0} ,\", cc);\n Console.WriteLine(\"\");\n\n BaseNCounter c2 = new BaseNCounter()\n {\n CharSet = new char[] { 'x', 'q', 'r', '9'},\n Power = 3\n };\n foreach (string cc in c2.Count())\n Console.Write(\"{0} ,\", cc);\n Console.Read();\n }\n}\n"
},
{
"answer_id": 1393146,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 2,
"selected": true,
"text": "private static char[] characters =\n new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };\n\n// length: The length of the string created by bruteforce\npublic static void PerformBruteForce(int length) {\n int charactersLength = characters.Length;\n int[] odometer = new int[length];\n long size = (long)Math.Pow(charactersLength, length);\n\n for (int i = 0; i < size; i++) {\n WriteBruteForce(odometer, characters);\n int position = 0;\n do {\n odometer[position] += 1;\n odometer[position] %= charactersLength;\n } while (odometer[position++] == 0 && position < length);\n }\n}\n\nprivate static void WriteBruteForce(int[] odometer, char[] characters) {\n // Print backwards\n for (int i = odometer.Length - 1; i >= 0; i--) {\n Console.Write(characters[odometer[i]]);\n }\n Console.WriteLine();\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] |
228,814
|
<p>I need a little help on this subject.</p>
<p>I have a Web application written in ASP.NET plus I have the .bak file of the SQL Express database, my question is: How can I install this in a simple click and go way in the client?</p>
<p>how can I write a script that will create a new database, restore the bak file into that database, set up IIS and ... well, that's it :)</p>
<p>I do this all manually, and I do this a lot, so I was just asking if there is a way to prevent do all this steps manually.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 232487,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 1,
"selected": false,
"text": "App_Data"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28004/"
] |
228,835
|
<p>what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?</p>
|
[
{
"answer_id": 228879,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 7,
"selected": true,
"text": "// lang.en.js\nlang = {\n greeting : \"Hello\"\n};\n\n// lang.fr.js\nlang = {\n greeting : \"Bonjour\"\n};\n document.onload = function() {\n alert(lang.greeting);\n};\n var l = new Language('en');\nl.get('greeting');\n"
},
{
"answer_id": 24832259,
"author": "Nail",
"author_id": 943535,
"author_profile": "https://Stackoverflow.com/users/943535",
"pm_score": 4,
"selected": false,
"text": "function Language(lang)\n{\n var __construct = function() {\n if (eval('typeof ' + lang) == 'undefined')\n {\n lang = \"en\";\n }\n return;\n }()\n\n this.getStr = function(str, defaultStr) {\n var retStr = eval('eval(lang).' + str);\n if (typeof retStr != 'undefined')\n {\n return retStr;\n } else {\n if (typeof defaultStr != 'undefined')\n {\n return defaultStr;\n } else {\n return eval('en.' + str);\n }\n }\n }\n}\n var en = {\n SelPlace:\"Select this place?\",\n Save:\"Saved.\"\n};\n\nvar tr = {\n SelPlace:\"Burayı seçmek istiyor musunuz?\"\n};\n\nvar translator = new Language(\"en\");\nalert(translator.getStr(\"SelPlace\")); // result: Select this place?\nalert(translator.getStr(\"Save\")); // result: Saved.\nalert(translator.getStr(\"DFKASFASDFJK\", \"Default string for non-existent string\")); // result: Default string for non-existent string\n\nvar translator = new Language(\"tr\");\nalert(translator.getStr(\"SelPlace\")); // result: Burayı seçmek istiyor musunuz?\nalert(translator.getStr(\"Save\")); // result: Saved. (because it doesn't exist in this language, borrowed from english as default)\nalert(translator.getStr(\"DFKASFASDFJK\", \"Default string for non-existent string\")); // result: Default string for non-existent string\n"
},
{
"answer_id": 30191493,
"author": "Tzach",
"author_id": 1795244,
"author_profile": "https://Stackoverflow.com/users/1795244",
"pm_score": 3,
"selected": false,
"text": "var Mustache = require('mustache');\n\nvar LANGUAGE = {\n general: {\n welcome: \"Welcome {{name}}!\"\n }\n};\n\nfunction _get_string(key) {\n var parts = key.split('.');\n var result = LANGUAGE, i;\n for (i = 0; i < parts.length; ++i) {\n result = result[parts[i]];\n }\n return result;\n}\n\nmodule.exports = function(key, params) {\n var str = _get_string(key);\n if (!params || _.isEmpty(params)) {\n return str;\n }\n return Mustache.render(str, params);\n};\n var L = require('language');\nvar the_string = L('general.welcome', {name='Joe'});\n"
},
{
"answer_id": 44169714,
"author": "Grigory Kislin",
"author_id": 548473,
"author_profile": "https://Stackoverflow.com/users/548473",
"pm_score": 0,
"selected": false,
"text": "<html>\n<script type=\"text/javascript\">\n var i18n = [];\n <c:forEach var='key' items='<%=new String[]{\"common.deleted\",\"common.saved\",\"common.enabled\",\"common.disabled\",\"...}%>'>\n i18n['${key}'] = '<spring:message code=\"${key}\"/>';\n </c:forEach>\n</script>\n</html>\n alert(i18n[\"common.deleted\"]);\n"
},
{
"answer_id": 57882370,
"author": "Amirhossein",
"author_id": 11258674,
"author_profile": "https://Stackoverflow.com/users/11258674",
"pm_score": 2,
"selected": false,
"text": "var strings = new Object();\n\nif(navigator.browserLanguage){\n lang = navigator.browserLanguage;\n}else{\n lang = navigator.language;\n}\n\nlang = lang.substr(0,2).toLowerCase();\n\n\n\nif(lang=='fa'){/////////////////////////////Persian////////////////////////////////////////////////////\n\n\n strings[\"Contents\"] = \"فهرست\";\n strings[\"Index\"] = \"شاخص\";\n strings[\"Search\"] = \"جستجو\";\n strings[\"Bookmark\"] = \"ذخیره\";\n\n strings[\"Loading the data for search...\"] = \"در حال جسنجوی متن...\";\n strings[\"Type in the word(s) to search for:\"] = \"لغت مد نظر خود را اینجا تایپ کنید:\";\n strings[\"Search title only\"] = \"جستجو بر اساس عنوان\";\n strings[\"Search previous results\"] = \"جستجو در نتایج قبلی\";\n strings[\"Display\"] = \"نمایش\";\n strings[\"No topics found!\"] = \"موردی یافت نشد!\";\n\n strings[\"Type in the keyword to find:\"] = \"کلیدواژه برای یافتن تایپ کنید\";\n\n strings[\"Show all\"] = \"نمایش همه\";\n strings[\"Hide all\"] = \"پنهان کردن\";\n strings[\"Previous\"] = \"قبلی\";\n strings[\"Next\"] = \"بعدی\";\n\n strings[\"Loading table of contents...\"] = \"در حال بارگزاری جدول فهرست...\";\n\n strings[\"Topics:\"] = \"عنوان ها\";\n strings[\"Current topic:\"] = \"عنوان جاری:\";\n strings[\"Remove\"] = \"پاک کردن\";\n strings[\"Add\"] = \"افزودن\";\n\n}else{//////////////////////////////////////English///////////////////////////////////////////////////\n\nstrings[\"Contents\"] = \"Contents\";\nstrings[\"Index\"] = \"Index\";\nstrings[\"Search\"] = \"Search\";\nstrings[\"Bookmark\"] = \"Bookmark\";\n\nstrings[\"Loading the data for search...\"] = \"Loading the data for search...\";\nstrings[\"Type in the word(s) to search for:\"] = \"Type in the word(s) to search for:\";\nstrings[\"Search title only\"] = \"Search title only\";\nstrings[\"Search previous results\"] = \"Search previous results\";\nstrings[\"Display\"] = \"Display\";\nstrings[\"No topics found!\"] = \"No topics found!\";\n\nstrings[\"Type in the keyword to find:\"] = \"Type in the keyword to find:\";\n\nstrings[\"Show all\"] = \"Show all\";\nstrings[\"Hide all\"] = \"Hide all\";\nstrings[\"Previous\"] = \"Previous\";\nstrings[\"Next\"] = \"Next\";\n\nstrings[\"Loading table of contents...\"] = \"Loading table of contents...\";\n\nstrings[\"Topics:\"] = \"Topics:\";\nstrings[\"Current topic:\"] = \"Current topic:\";\nstrings[\"Remove\"] = \"Remove\";\nstrings[\"Add\"] = \"Add\";\n\n}\n"
},
{
"answer_id": 61810072,
"author": "Benjamin Sloutsky",
"author_id": 13401529,
"author_profile": "https://Stackoverflow.com/users/13401529",
"pm_score": 1,
"selected": false,
"text": "<div id=\"google_translate_element\" style = \"float: left; margin-left: 10px;\"></div>\n\n<script type=\"text/javascript\">\nfunction googleTranslateElementInit() {\n new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');\n}\n</script>\n\n<script type=\"text/javascript\" src=\"//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit\"></script>\n\n</div><input type = \"text\" style = \"display: inline; margin-left: 8%;\" class = \"sear\" placeholder = \"Search people...\"><button class = \"bar\">🔎</button>\n"
},
{
"answer_id": 66312038,
"author": "amirrezasalari",
"author_id": 14659697,
"author_profile": "https://Stackoverflow.com/users/14659697",
"pm_score": 1,
"selected": false,
"text": "class Language {\n constructor(lang) {\n var __construct = function (){\n if (eval('typeof ' + lang) == 'undefined'){\n lang = \"en\";\n }\n return;\n };\n this.getStr = function (str){\n var retStr = eval('eval(lang).' + str);\n if (typeof retStr != 'undefined'){\n return retStr;\n } else {\n return str;\n }\n };\n }\n}\n\nvar en = {\n Save:\"Saved.\"\n};\n\nvar fa = {\n Save:\"ذخیره\"\n};\n\nvar translator = new Language(\"fa\");\nconsole.log(translator.getStr(\"Save\"));"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3214/"
] |
228,851
|
<p>Has anybody tried creating <code>RawSocket</code> in <code>Android</code> and have succeeded ?</p>
|
[
{
"answer_id": 246911,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "Socket DatagramSocket java.net"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
228,863
|
<p>I am considering creating some JSP-tags that will always give the same output. For example:</p>
<pre><code><foo:bar>baz</foo:bar>
</code></pre>
<p>Will always output:</p>
<pre><code><div class="bar">baz</div>
</code></pre>
<p>Is there any way to get a JSP-tag to behave just like static output in the generated servlet?</p>
<p>For example:</p>
<pre><code>out.write("<div class=\"bar\">");
...
out.write("</div>");
</code></pre>
<p>in stead of</p>
<pre><code>x.y.z.foo.BarTag _jspx_th_foo_bar_0 = new x.y.z.foo.BarTag();
_jspx_th_foo_bar_0.setPageContext(pageContext);
_jspx_th_foo_bar_0.setParent(null);
_jspxTagObjects.push(_jspx_th_foo_bar_0);
int _jspx_eval_foo_bar_0 = _jspx_th_foo_bar_0.doStartTag();
etc...
etc...
etc...
</code></pre>
<h2>Background</h2>
<p>I'm worried about performance. I haven't tested this yet, but it looks like the generated servlet does a lot for something very simple, and performance is very important.</p>
<p>But if the servlet behaves as if the output was written directly in the JSP, the cost in production will be zero.</p>
<p>I see a few advantages by doing this. I can change the static HTML or even change to something more dynamic, without editing every portlet. In our setup it's easy to change a tag, but very time-consuming to change every JSP that uses a specific element.</p>
<p>This also means I can force developers to not write something like</p>
<pre><code><div class="bar" style="whatever">...</div>
</code></pre>
<p>There is even more advantages, but if it costs performance on the production servers, it's probably not worth it.</p>
|
[
{
"answer_id": 239624,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 2,
"selected": true,
"text": "package XX.XX.XX.XX\n\nimport java.io.IOException;\n\nimport javax.servlet.jsp.JspException;\nimport javax.servlet.jsp.tagext.TagSupport;\n\npublic class Test0001Tag extends TagSupport {\n\n public Test0001Tag() {\n }\n\n public int doStartTag() throws JspException {\n\n try {\n pageContext.getOut().print(\"<div class=\\\"Test0001\\\">\");\n } catch (IOException e) {\n throw new JspException(e);\n }\n return EVAL_BODY_INCLUDE;\n }\n\n public int doEndTag() throws JspException {\n try {\n pageContext.getOut().print(\"</div>\");\n } catch (IOException e) {\n throw new JspException(e);\n }\n return EVAL_PAGE;\n }\n\n public void release() {\n super.release();\n }\n}\n <tag>\n <name>test0001</name>\n <tagclass>XX.XX.XX.XX.Test0001Tag</tagclass>\n <bodycontent>JSP</bodycontent> \n</tag>\n <!-- \n<%long start = System.currentTimeMillis();%>\n<% for (int i = 0; i < 1000; i++) { %>\n<div class=\"Test0001\">X</div>\n<div class=\"Test0002\">X</div>\n<div class=\"Test0003\">X</div>\n...\n<div class=\"Test0498\">X</div>\n<div class=\"Test0499\">X</div>\n<div class=\"Test0500\">X</div>\n<% } %>\n<%System.out.println(System.currentTimeMillis()-start);%>\n -->\n <!-- \n<%long start = System.currentTimeMillis();%>\n<% for (int i = 0; i < 1000; i++) { %>\n<bddesign:test0001>X</bddesign:test0001>\n<bddesign:test0002>X</bddesign:test0002>\n<bddesign:test0003>X</bddesign:test0003>\n...\n<bddesign:test0498>X</bddesign:test0498>\n<bddesign:test0499>X</bddesign:test0499>\n<bddesign:test0500>X</bddesign:test0500>\n<% } %>\n<%System.out.println(System.currentTimeMillis()-start);%>\n -->\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28683/"
] |
228,875
|
<p>I have data coming from the database in the form of a <code>DataSet</code>. I then set it as the <code>DataSource</code> of a grid control before doing a <code>DataBind()</code>. I want to sort the <code>DataSet</code>/<code>DataTable</code> on one column. The column is to complex to sort in the database but I was hoping I could sort it like I would sort a generic list i.e. using a deligate.</p>
<p>Is this possible or do I have to transfer it to a different data structure?</p>
<p><strong>Edit</strong> I can't get any of these answer to work for me, I think because I am using <strong>.Net 2.0.</strong></p>
|
[
{
"answer_id": 228890,
"author": "Toby",
"author_id": 291137,
"author_profile": "https://Stackoverflow.com/users/291137",
"pm_score": 2,
"selected": false,
"text": "var dt = new DataTable();\ngvWhatever.DataSource = dt.Select().ToList().Sort();\n"
},
{
"answer_id": 228892,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "var sorted = table.Rows.Cast<DataRow>().OrderBy(row => your code);\nint sequence = 0;\nforeach(var row in sorted)\n{\n row[\"sequence\"] = sequence++;\n}\n List<T> List<DataRow> sorted = new List<DataRow>();\n foreach(DataRow row in table.Rows)\n {\n sorted.Add(row);\n }\n sorted.Sort(delegate(DataRow x, DataRow y) { your code });\n int sequence = 0;\n foreach(DataRow row in sorted)\n {\n row[\"sequence\"] = sequence++;\n }\n"
},
{
"answer_id": 760330,
"author": "0100110010101",
"author_id": 88702,
"author_profile": "https://Stackoverflow.com/users/88702",
"pm_score": 1,
"selected": false,
"text": "myTableName.DefaultView.Sort = \"MyFieldName DESC\";\n"
},
{
"answer_id": 3935404,
"author": "Irina",
"author_id": 476020,
"author_profile": "https://Stackoverflow.com/users/476020",
"pm_score": 1,
"selected": false,
"text": "protected void grdResult_Sorting(object sender, GridViewSortEventArgs e)\n {\n DataTable dt = ((DataTable)Session[\"myDatatable\"]);\n grdResult.DataSource = dt;\n DataTable dataTable = grdResult.DataSource as DataTable;\n\n //Code added to fix issue with sorting for Date datatype fields\n if (dataTable != null)\n { \n\n DataView dataView = new DataView(dataTable);\n for (int i = 0; i < dataView.Table.Rows.Count; i++)\n {\n try\n {\n dataView.Table.Rows[i][\"RESP_DUE_DT\"] = common.FormatDateWithYYYYMMDD(Convert.ToDateTime(dataView.Table.Rows[i][\"RESP_DUE_DT\"]));\n dataView.Table.Rows[i][\"RECD_DT\"] = common.FormatDateWithYYYYMMDD(Convert.ToDateTime(dataView.Table.Rows[i][\"RECD_DT\"]));\n }\n catch (Exception ex)\n {\n\n }\n }\n\n dataView.Sort = \"[\" + e.SortExpression + \"]\" + \" \" + GetSortDirection(e.SortExpression);\n\n for (int i = 0; i < dataView.Table.Rows.Count; i++)\n {\n try\n {\n dataView.AllowEdit = true;\n dataView[i].BeginEdit();\n dataView[i][\"RESP_DUE_DT\"] = common.FormatDateFromStringYYYYMMDD(dataView[i][\"RESP_DUE_DT\"].ToString());\n dataView[i][\"RECD_DT\"] = common.FormatDateFromStringYYYYMMDD(dataView[i][\"RECD_DT\"].ToString());\n }\n catch (Exception ex)\n {\n\n }\n }\n //End code added to fix the issue with sorting for Date data type fields\n\n\n grdResult.DataSource = dataView;\n grdResult.DataBind();\n\n\n }\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
228,908
|
<p>Recently, I noticed some people mentioning that <code>std::list::size()</code> has a linear complexity.<br>
According to <a href="http://www.cplusplus.com/reference/stl/list/size.html" rel="noreferrer">some</a> <a href="http://bytes.com/forum/thread60248.html" rel="noreferrer">sources</a>, this is in fact implementation dependent as the standard doesn't say what the complexity has to be.<br>
The comment <a href="http://ahlamnote.blogspot.com/2006/11/stl-list-size-method-is-slow.html" rel="noreferrer">in this blog entry</a> says:</p>
<blockquote>
<p>Actually, it depends on which STL you
are using. Microsoft Visual Studio V6
implements size() as {return (_Size);
} whereas gcc (at least in versions
3.3.2 and 4.1.0) do it as { return std::distance(begin(), end()); } The
first has constant speed, the second
has o(N) speed</p>
</blockquote>
<ol>
<li>So my guess is that for the VC++ crowd <code>size()</code> has constant complexity as Dinkumware
probably won't have changed that fact since VC6. Am I right there?<br></li>
<li>What does it look like currently in <code>gcc</code>? If it is really O(n), why did the
developers choose to do so?</li>
</ol>
|
[
{
"answer_id": 228914,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 7,
"selected": true,
"text": "list::size() list::size() list::size() list::splice() list::size() list::size() size() list::size() size() size() size() size() container::distance( begin(), end()) splice() n distance( first, last)"
},
{
"answer_id": 230629,
"author": "introp",
"author_id": 8398,
"author_profile": "https://Stackoverflow.com/users/8398",
"pm_score": 4,
"selected": false,
"text": "list::size std::distance(head, tail) std::distance std::list std::list size() std::deque"
},
{
"answer_id": 13751799,
"author": "kennytm",
"author_id": 224671,
"author_profile": "https://Stackoverflow.com/users/224671",
"pm_score": 6,
"selected": false,
"text": ".size() .size() .size() /** Returns the number of elements in the %list. */\n size_type\n size() const _GLIBCXX_NOEXCEPT\n { return std::distance(begin(), end()); }\n std::list::size() .size() _LIBCPP_INLINE_VISIBILITY\nsize_type size() const _NOEXCEPT {return base::__sz();}\n\n...\n\n__compressed_pair<size_type, __node_allocator> __size_alloc_;\n\n_LIBCPP_INLINE_VISIBILITY\nconst size_type& __sz() const _NOEXCEPT\n {return __size_alloc_.first();}\n"
},
{
"answer_id": 73133672,
"author": "BruceSun",
"author_id": 4277805,
"author_profile": "https://Stackoverflow.com/users/4277805",
"pm_score": 0,
"selected": false,
"text": " _GLIBCXX_NODISCARD\n size_type\n size() const _GLIBCXX_NOEXCEPT\n { return _M_node_count(); }\n #if _GLIBCXX_USE_CXX11_ABI\n static size_t\n _S_distance(const_iterator __first, const_iterator __last)\n { return std::distance(__first, __last); }\n\n // return the stored size\n size_t\n _M_node_count() const\n { return this->_M_get_size(); }\n#else\n // dummy implementations used when the size is not stored\n static size_t\n _S_distance(const_iterator, const_iterator)\n { return 0; }\n\n // count the number of nodes\n size_t\n _M_node_count() const\n { return std::distance(begin(), end()); }\n#endif\n add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=0)\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27596/"
] |
228,912
|
<p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
|
[
{
"answer_id": 228961,
"author": "Blauohr",
"author_id": 22176,
"author_profile": "https://Stackoverflow.com/users/22176",
"pm_score": 2,
"selected": false,
"text": "for item in self.inventory_names:\n t = (item,)\n self.cursor.execute(\"SELECT weight FROM Equipment WHERE name = ?\", t)\n self.cursor.close()\n"
},
{
"answer_id": 228981,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 8,
"selected": true,
"text": "Cursor.execute() self.cursor.execute(\"SELECT weight FROM Equipment WHERE name = ?\", [item])\n"
},
{
"answer_id": 597198,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "cursor.execute(\"SELECT * from ? WHERE name = ?\", (table_name, name))\n"
},
{
"answer_id": 3346710,
"author": "JBE",
"author_id": 403743,
"author_profile": "https://Stackoverflow.com/users/403743",
"pm_score": -1,
"selected": false,
"text": "execute(\"select fact from factoids where key like ?\", \"%%s%\" % val)\n ?"
},
{
"answer_id": 7305758,
"author": "jgtumusiime",
"author_id": 820591,
"author_profile": "https://Stackoverflow.com/users/820591",
"pm_score": 5,
"selected": false,
"text": "cursor.execute >>> ('jason')\n'jason'\n\n>>> ('jason',)\n('jason',)\n self.cursor.execute(\"SELECT weight FROM Equipment WHERE name = ?\", (item,))\n cursor.execute"
},
{
"answer_id": 23729861,
"author": "Joey Nelson",
"author_id": 2600246,
"author_profile": "https://Stackoverflow.com/users/2600246",
"pm_score": 0,
"selected": false,
"text": "names = ['Joe', 'Bob', 'Mary']\n for item in self.inventory_names:\nself.cursor.execute(\"SELECT weight FROM Equipment WHERE name = ?\", (item, ))\n"
},
{
"answer_id": 51570095,
"author": "Mike T",
"author_id": 327026,
"author_profile": "https://Stackoverflow.com/users/327026",
"pm_score": 3,
"selected": false,
"text": "sqlite3 ? curs.execute(\"SELECT weight FROM Equipment WHERE name = ? AND price = ?\",\n ['lead', 24])\n :par curs.execute(\"SELECT weight FROM Equipment WHERE name = :name AND price = :price\",\n {name: 'lead', price: 24})\n :par"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
228,926
|
<p>How do you find out the local time of the user browsing your website in ASP.NET? </p>
|
[
{
"answer_id": 229020,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 4,
"selected": true,
"text": "function setNow(hiddenInputId)\n{\n var now = new Date();\n var input = document.getElementById(hiddenInputId);\n\n if(input) input.value = now.toString();\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16628/"
] |
228,931
|
<p>I'm using this code, to make a request to a given URL:</p>
<pre><code>private static string GetWebRequestContent(string url)
{
string sid = String.Empty;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.KeepAlive = false;
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
sid = sr.ReadToEnd().Trim();
}
}
return sid;
}
</code></pre>
<p>I'm using it to test the stickyness of a Work Load Balancer, with 3 servers behind it. They all have a static HTM file called sid.htm, where the server's Server ID is written.</p>
<p>For URL's with HTTP this works fine. But with HTTPS it doesn't work. I get this exception:</p>
<blockquote>
<p>The request was aborted: Could not create SSL/TLS secure channel.</p>
</blockquote>
<p>At the moment, I have only 2 servers behind the WLB and one on its own with a public IP behind a firewall. HTTPS requests works fine if I hit the stand-alone server - but when I hit the WLB I get the above error.</p>
<p>One thing: In order to switch between hitting the single server, and the WLB I use my hosts file. The DNS records for my domain points to the single server at the moment. So I put a record in my hosts file to hit the WLB. This shouldn't be causing problems...</p>
<p><strong>My question</strong>: Which SSL credentials/certificates does the HttpWebRequest use? If it uses 40 bit DES or 56 bit DES, that's the reason, because those are disabled in the WLB. But those certificates haven't been used in browsers since IE3 and Netscape 1 and 2.</p>
|
[
{
"answer_id": 228954,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 4,
"selected": true,
"text": "ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2972/"
] |
228,945
|
<p>I find System.Monitor very confusing, although I understand threading, locks, deadlocks, race conditions, dining philosophers and all that jazz. Normally I use a ManualResetEvent() to do inter-thread co-ordination, but I know that that's a heavyweight kernel object, and that System.Monitor (Enter/Pulse, etc.) is much more efficient. I've Googled and Googled but cannot find a sensible example.</p>
<p>I would be most grateful if the SO crew could explain this potentially wonderful construct to me :-)</p>
|
[
{
"answer_id": 228983,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "Wait Worker Main Worker Pulse Main Worker Main lock(obj) {...} Monitor.Enter Monitor.Exit lock(sync) static void Main()\n {\n object sync = new object();\n lock (sync)\n {\n ThreadPool.QueueUserWorkItem(Worker, sync);\n Console.WriteLine(\"Main sleeping\");\n\n // wait for the worker to tell us it is ready\n Monitor.Wait(sync);\n Console.WriteLine(\"Main woke up!\");\n }\n Console.WriteLine(\"Press any key...\");\n Console.ReadKey();\n }\n static void Worker(object sync)\n {\n Console.WriteLine(\"Worker started; about to sleep\");\n Thread.Sleep(5000);\n Console.WriteLine(\"Worker about pulse\");\n lock (sync)\n { // notify Main that we did something interesting\n Monitor.Pulse(sync);\n Console.WriteLine(\"Worker pulsed; about to release lock\");\n }\n Console.WriteLine(\"Worker all done\");\n }\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25462/"
] |
228,969
|
<p>I am getting the following error when I post back a page from the client-side. I have JavaScript code that modifies an asp:ListBox on the client side.</p>
<p>How do we fix this?</p>
<p>Error details below:</p>
<pre><code>Server Error in '/XXX' Application.
--------------------------------------------------------------------------------
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +2132728
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
</code></pre>
|
[
{
"answer_id": 245512,
"author": "Andy C.",
"author_id": 28541,
"author_profile": "https://Stackoverflow.com/users/28541",
"pm_score": 5,
"selected": false,
"text": "<select> <asp:ListBox> <select>"
},
{
"answer_id": 275724,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "EnableEventValidation=\"false\" void Grid_SelectedIndexChanged(object sender, EventArgs e) ClientScript.RegisterForEventValidation protected override void Render(HtmlTextWriter writer)\n{\n foreach (DataGridItem item in this.Grid.Items)\n {\n Page.ClientScript.RegisterForEventValidation(item.UniqueID);\n foreach (TableCell cell in (item as TableRow).Cells)\n {\n Page.ClientScript.RegisterForEventValidation(cell.UniqueID);\n foreach (System.Web.UI.Control control in cell.Controls)\n {\n if (control is Button)\n Page.ClientScript.RegisterForEventValidation(control.UniqueID);\n }\n }\n }\n}\n PushButton LinkButton"
},
{
"answer_id": 3346940,
"author": "cem",
"author_id": 403774,
"author_profile": "https://Stackoverflow.com/users/403774",
"pm_score": 1,
"selected": false,
"text": "LinkButton"
},
{
"answer_id": 3758957,
"author": "Jeff Pang",
"author_id": 453722,
"author_profile": "https://Stackoverflow.com/users/453722",
"pm_score": 8,
"selected": false,
"text": "if (!Page.IsPostBack)\n{ //do something }\n"
},
{
"answer_id": 3937787,
"author": "Murad Dodhiya",
"author_id": 476330,
"author_profile": "https://Stackoverflow.com/users/476330",
"pm_score": 1,
"selected": false,
"text": "lstMain.DataBind();\nImage img = (Image)lstMain.Items[0].FindControl(\"imgMain\");\n\n// Define the name and type of the client scripts on the page.\nString csname1 = \"PopupScript\";\nType cstype = this.GetType();\n\n// Get a ClientScriptManager reference from the Page class.\nClientScriptManager cs = Page.ClientScript;\n\n// Check to see if the startup script is already registered.\nif (!cs.IsStartupScriptRegistered(cstype, csname1))\n{\n cs.RegisterStartupScript(cstype, csname1, \"<script language=javascript> p=\\\"\" + img.ClientID + \"\\\"</script>\");\n}\n"
},
{
"answer_id": 4178314,
"author": "pamelo",
"author_id": 484265,
"author_profile": "https://Stackoverflow.com/users/484265",
"pm_score": 3,
"selected": false,
"text": "DropDownList DD = (DropDownList)F.FindControl(\"DDlista\");\nHiddenField HF = (HiddenField)F.FindControl(\"HFlista\");\nstring[] opcoes = HF.value.Split('\\n');\nforeach (string opcao in opcoes) DD.Items.Add(opcao);\n HF.value = \"option 1\\n\\roption 2\\n\\roption 3\";\n DropDownList DD = (DropDownList)F.FindControl(\"DDlista\");\nHiddenField HF = (HiddenField)F.FindControl(\"HFlista\");\nstring dados = HF.Value.Replace(\"\\r\", \"\");\nstring[] opcoes = dados.Split('\\n');\nforeach (string opcao in opcoes) DD.Items.Add(opcao);\n"
},
{
"answer_id": 5033280,
"author": "Tushar",
"author_id": 621947,
"author_profile": "https://Stackoverflow.com/users/621947",
"pm_score": 2,
"selected": false,
"text": "</form>"
},
{
"answer_id": 5055843,
"author": "ali joodie",
"author_id": 625067,
"author_profile": "https://Stackoverflow.com/users/625067",
"pm_score": 2,
"selected": false,
"text": "UseSubmitBehavior=\"True\" UseSubmitBehavior=\"False\" <asp:Button ID=\"BtnDis\" runat=\"server\" CommandName=\"BtnDis\" CommandArgument='<%#Eval(\"Id\")%>' Text=\"Discription\" CausesValidation=\"True\" UseSubmitBehavior=\"False\" />\n"
},
{
"answer_id": 5144268,
"author": "Mike C.",
"author_id": 637966,
"author_profile": "https://Stackoverflow.com/users/637966",
"pm_score": 3,
"selected": false,
"text": "public class ListBoxNoEventValidation : ListBox \n{\n}\n"
},
{
"answer_id": 5744178,
"author": "Swathi",
"author_id": 718933,
"author_profile": "https://Stackoverflow.com/users/718933",
"pm_score": 3,
"selected": false,
"text": "<asp:TemplateField ItemStyle-Width=\"9\">\n <ItemTemplate>\n <asp:ImageButton ID=\"ImgBtn\" ImageUrl=\"Include/images/gridplus.gif\" CommandName=\"Expand\"\n runat=\"server\" />\n </ItemTemplate>\n</asp:TemplateField>\n <asp:TemplateField>\n<ItemTemplate>\n <asp:LinkButton CommandName=\"Expand\" ID=\"lnkBtn\" runat=\"server\" ><asp:Image ID=\"Img\" runat=\"server\" ImageUrl=\"~/Images/app/plus.gif\" /></asp:LinkButton>\n </ItemTemplate>\n</asp:TemplateField> \n"
},
{
"answer_id": 5883678,
"author": "devo882",
"author_id": 738013,
"author_profile": "https://Stackoverflow.com/users/738013",
"pm_score": 1,
"selected": false,
"text": "<Triggers> <asp:PostBackTrigger .../>"
},
{
"answer_id": 6953748,
"author": "Niket",
"author_id": 880215,
"author_profile": "https://Stackoverflow.com/users/880215",
"pm_score": 2,
"selected": false,
"text": "if(!IsPostBack)"
},
{
"answer_id": 7750203,
"author": "Josh",
"author_id": 960978,
"author_profile": "https://Stackoverflow.com/users/960978",
"pm_score": 4,
"selected": false,
"text": "protected override void Render(HtmlTextWriter writer)\n{\n foreach (string val in allPossibleListBoxValues)\n {\n Page.ClientScript.RegisterForEventValidation(myListBox.UniqueID, val);\n }\n base.Render(writer);\n}\n protected override void Render(HtmlTextWriter writer)\n{\n foreach (ListItem i in listBoxAll.Items)\n {\n Page.ClientScript.RegisterForEventValidation(listBoxSelected.UniqueID, i.Value);\n }\n base.Render(writer);\n}\n"
},
{
"answer_id": 13949590,
"author": "CraigS",
"author_id": 1363554,
"author_profile": "https://Stackoverflow.com/users/1363554",
"pm_score": 1,
"selected": false,
"text": "Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)\n\n Dim ClientScript As ClientScriptManager = Page.ClientScript\n\n ClientScript.RegisterForEventValidation(\"ddCar\", \"Mercedes\")\n\n MyBase.Render(writer)\nEnd Sub\n protected override void Render(HtmlTextWriter writer)\n{\n Page.ClientScript.RegisterForEventValidation(\"ddCar\", \"Mercedes\");\n base.Render(writer);\n}\n <script>"
},
{
"answer_id": 15714437,
"author": "yilee",
"author_id": 2156481,
"author_profile": "https://Stackoverflow.com/users/2156481",
"pm_score": 3,
"selected": false,
"text": "protected override void OnInit(EventArgs e) {\n foreach (GridViewRow grdRw in gvEvent.Rows) {\n\n Button deleteButton = (Button)grdRw.Cells[2].Controls[1];\n\n deleteButton.ID = \"btnDelete_\" + grdRw.RowIndex.ToString(); \n }\n}\n"
},
{
"answer_id": 20786904,
"author": "Balaji Selvarajan",
"author_id": 3135882,
"author_profile": "https://Stackoverflow.com/users/3135882",
"pm_score": 2,
"selected": false,
"text": "If(!IsPostBack){\n\n //do something\n\n}\n"
},
{
"answer_id": 31187805,
"author": "Andre RB",
"author_id": 2944964,
"author_profile": "https://Stackoverflow.com/users/2944964",
"pm_score": 1,
"selected": false,
"text": "<asp:DropDownList ID=\"DropDownList1\" runat=\"server\">\n <asp:ListItem Selected=\"True\">\n Item 1</asp:ListItem>\n <asp:ListItem>\n Item 2</asp:ListItem>\n <asp:ListItem>\n Item 3</asp:ListItem>\n</asp:DropDownList>\n <asp:DropDownList ID=\"DropDownList1\" runat=\"server\">\n <asp:ListItem Selected=\"True\">Item 1</asp:ListItem>\n <asp:ListItem>Item 2</asp:ListItem>\n <asp:ListItem>Item 3</asp:ListItem>\n</asp:DropDownList>\n"
},
{
"answer_id": 36724438,
"author": "biggles",
"author_id": 5579080,
"author_profile": "https://Stackoverflow.com/users/5579080",
"pm_score": 4,
"selected": false,
"text": "<body>\n<form id=\"form1\" runat=\"server\">\n<div>\n <form action=\"#\" method=\"post\" class=\"form\" role=\"form\">\n <div>\n ...\n <asp:Button ID=\"submitButton\" runat=\"server\"\n </div>\n</div>\n</body>\n"
},
{
"answer_id": 42356691,
"author": "Sudhakar Rao",
"author_id": 2798049,
"author_profile": "https://Stackoverflow.com/users/2798049",
"pm_score": 0,
"selected": false,
"text": " private void Page_Load()\n {\n if (!IsPostBack)\n { \n }\n }\n"
},
{
"answer_id": 49427870,
"author": "Akhil Singh",
"author_id": 7528842,
"author_profile": "https://Stackoverflow.com/users/7528842",
"pm_score": 2,
"selected": false,
"text": " protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n bindGridview();\n }\n"
},
{
"answer_id": 51951356,
"author": "Zolfaghari",
"author_id": 2155778,
"author_profile": "https://Stackoverflow.com/users/2155778",
"pm_score": 0,
"selected": false,
"text": "protected void grdEducation_RowEditing(object sender, GridViewEditEventArgs e)\n{\n // do your processing ...\n\n // at end<br />\n e.Cancel = true;\n}\n"
},
{
"answer_id": 56668980,
"author": "Marisol Gutiérrez",
"author_id": 8656365,
"author_profile": "https://Stackoverflow.com/users/8656365",
"pm_score": 1,
"selected": false,
"text": "<appSettings>\n <add key=\"ValidationSettings:UnobtrusiveValidationMode\" value=\"None\" />\n...\n</appSettings>\n<system.web>\n <machineKey compatibilityMode=\"Framework45\" decryptionKey=\"somekey\" validationKey=\"otherkey\" validation=\"SHA1\" decryption=\"AES />\n <pages [...] controlRenderingCompatibilityVersion=\"4.0\" enableEventValidation=\"true\" renderAllHiddenFieldsAtTopOfForm=\"true\" />\n <httpRuntime [...] requestValidationMode=\"2.0\" targetFramework=\"4.5\" />\n...\n</system.web>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
228,978
|
<p>I have this Perl script with many defined constants of configuration files. For example:</p>
<pre><code>use constant {
LOG_DIR => "/var/log/",
LOG_FILENAME => "/var/log/file1.log",
LOG4PERL_CONF_FILE => "/etc/app1/log4perl.conf",
CONF_FILE1 => "/etc/app1/config1.xml",
CONF_FILE2 => "/etc/app1/config2.xml",
CONF_FILE3 => "/etc/app1/config3.xml",
CONF_FILE4 => "/etc/app1/config4.xml",
CONF_FILE5 => "/etc/app1/config5.xml",
};
</code></pre>
<p>I want to reduce duplication of "/etc/app1" and "/var/log" , but using variables does not work. Also using previously defined constants does not work in the same "use constant block". For example:</p>
<pre><code>use constant {
LOG_DIR => "/var/log/",
FILE_FILENAME => LOG_DIR . "file1.log"
};
</code></pre>
<p>does not work.</p>
<p>Using separate "use constant" blocks does workaround this problem, but that adds a lot of unneeded code.</p>
<p>What is the correct way to do this?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 228991,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "constant->import use constant LOG_DIR CONF_DIR"
},
{
"answer_id": 229061,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 4,
"selected": true,
"text": "use Readonly;\n\nReadonly my $LOG_DIR => \"/var/log\";\nReadonly my $LOG_FILENAME => \"$LOG_DIR/file1.log\";\nReadonly my $ETC => '/etc/app1';\nReadonly my $LOG4PERL_CONF_FILE => \"$ETC/log4perl.con\";\n\n# hash because we don't have an index '0'\nReadonly my %CONF_FILES => map { $_ => \"$ETC/config$_.xml\" } 1 .. 5;\n"
},
{
"answer_id": 229550,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 3,
"selected": false,
"text": "use constant BASE_PATH => \"/etc/app1\";\n\nuse constant {\n LOG4PERL_CONF_FILE => BASE_PATH . \"/log4perl.conf\",\n CONF_FILE1 => BASE_PATH . \"/config1.xml\",\n CONF_FILE2 => BASE_PATH . \"/config2.xml\",\n CONF_FILE3 => BASE_PATH . \"/config3.xml\",\n CONF_FILE4 => BASE_PATH . \"/config4.xml\",\n CONF_FILE5 => BASE_PATH . \"/config5.xml\",\n};\n use constant BASE_PATH => $ENV{MY_BASE_PATH} || \"/etc/app1\";\n use strict;\nuse warnings;\n\nuse constant BASE_PATH => $ENV{MY_PATH} || '/etc/apps';\n\nBEGIN {\n my %conf = (\n FILE1 => \"/config1.xml\",\n FILE2 => \"/config2.xml\",\n );\n\n for my $constant (keys %conf) {\n no strict 'refs';\n *{__PACKAGE__ . \"::CONF_$constant\"}\n = sub () {BASE_PATH . \"$conf{$constant}\"};\n }\n}\n\nprint \"Config is \", CONF_FILE1, \".\\n\";\n"
},
{
"answer_id": 230051,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "use constant +{\n map { sprintf $_, '/var/log' } (\n LOG_DIR => \"%s/\",\n LOG_FILENAME => \"%s/file1.log\",\n ),\n map { sprintf $_, '/etc/app1' } (\n LOG4PERL_CONF_FILE => \"%s/log4perl.conf\",\n CONF_FILE1 => \"%s/config1.xml\",\n CONF_FILE2 => \"%s/config2.xml\",\n CONF_FILE3 => \"%s/config3.xml\",\n CONF_FILE4 => \"%s/config4.xml\",\n CONF_FILE5 => \"%s/config5.xml\",\n ),\n};\n"
},
{
"answer_id": 241296,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 0,
"selected": false,
"text": " sub base_log_dir { '...' }\n\n sub get_log_file\n {\n my( $self, $number ) = @_;\n\n my $log_file = catfile( \n $self->base_log_dir, \n sprintf \"foo%03d\", $number\n );\n }\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] |
228,987
|
<p>We try to convert from string to <code>Byte[]</code> using the following Java code:</p>
<pre><code>String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16");
</code></pre>
<p>We get a byte array of length 22 bytes, we are not sure where this padding comes from.
How do I get an array of length 20?</p>
|
[
{
"answer_id": 229006,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "String source = \"0123456789\";\nbyte[] byteArray = source.getBytes(\"UTF-16LE\"); // Or UTF-16BE\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/228987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30704/"
] |
229,007
|
<p>I am running the free version of Helicon ISAPI Rewrite on IIS and have several sites running through the same set of rewrite rules. Up 'til now this has been fine as all the rules have applied to all the sites. I have recently added a new site which I don't want to run through all the rules. Is there any way to make requests to this site break out of the rule set after it's executed its own rules.</p>
<p>I've tried the following with no luck; all requests to mysite.com result in a 404. I guess what I'm looking for is a rule that does nothing and is marked as the last rule to execute [L].</p>
<pre><code>## New site rule for mysite.com only
RewriteCond Host: (?:www\.)?mysite\.com
RewriteRule /content([\w/]*) /content.aspx?page=$1 [L]
## Break out of processing for all other requests to mysite.com
RewriteCond Host: (?:www\.)?mysite\.com
RewriteRule (.*) - [L]
## Rules for all other sites
RewriteRule ^/([^\.\?]+)/?(\?.*)?$ /$1.aspx$2 [L]
...
</code></pre>
|
[
{
"answer_id": 229026,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 2,
"selected": false,
"text": "RewriteCond Host: (?:www\\.)?mysite\\.com\nRewriteRule ^(.*)$ $1 [QSA,L]\n"
},
{
"answer_id": 229523,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 5,
"selected": true,
"text": "# stop processing if we're in the webdav folder\nRewriteCond %{REQUEST_URI} ^/webdav [NC]\nRewriteRule .* - [L]\n"
},
{
"answer_id": 1128867,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 1,
"selected": false,
"text": "## Break out of processing for all other requests to mysite.com\nRewriteCond %{SERVER_NAME} ^(?:www\\.)?mysite\\.com$\nRewriteRule (.*) - [L]\n ## Break out of processing for all other requests to mysite.com\nRewriteCond %{HTTP_HOST} ^(?:www\\.)?mysite\\.com$\nRewriteRule (.*) - [L]\n"
},
{
"answer_id": 47487534,
"author": "Frank N",
"author_id": 444255,
"author_profile": "https://Stackoverflow.com/users/444255",
"pm_score": 3,
"selected": false,
"text": "RewriteRule ^ - [END] . .*"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2179408/"
] |
229,009
|
<p>Is there a way I can access (for printout) a list of sub + module to arbitrary depth of sub-calls preceding a current position in a Perl script?</p>
<p>I need to make changes to some Perl modules (.pm's). The workflow is initiated from a web-page thru a cgi-script, passing input through several modules/objects ending in the module where I need to use the data. Somewhere along the line the data got changed and I need to find out where.</p>
|
[
{
"answer_id": 229030,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 7,
"selected": true,
"text": "use Devel::StackTrace;\nmy $trace = Devel::StackTrace->new;\nprint $trace->as_string; # like carp\n"
},
{
"answer_id": 229151,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 4,
"selected": false,
"text": "Carp::confess Carp::cluck"
},
{
"answer_id": 231863,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 4,
"selected": false,
"text": "Carp::longmess use Carp qw<longmess>;\nuse Data::Dumper;\nsub A { &B; }\nsub B { &C; }\nsub C { &D; }\nsub D { &E; }\n\nsub E { \n # Uncomment below if you want to see the place in E\n # local $Carp::CarpLevel = -1; \n my $mess = longmess();\n print Dumper( $mess );\n}\n\nA();\n__END__\n$VAR1 = ' at - line 14\n main::D called at - line 12\n main::C called at - line 10\n main::B called at - line 8\n main::A() called at - line 23\n';\n my $stack_frame_re = qr{\n ^ # Beginning of line\n \\s* # Any number of spaces\n ( [\\w:]+ ) # Package + sub\n (?: [(] ( .*? ) [)] )? # Anything between two parens\n \\s+ # At least one space\n called [ ] at # \"called\" followed by a single space\n \\s+ ( \\S+ ) \\s+ # Spaces surrounding at least one non-space character\n line [ ] (\\d+) # line designation\n}x;\n\nsub get_stack {\n my @lines = split /\\s*\\n\\s*/, longmess;\n shift @lines;\n my @frames\n = map { \n my ( $sub_name, $arg_str, $file, $line ) = /$stack_frame_re/;\n my $ref = { sub_name => $sub_name\n , args => [ map { s/^'//; s/'$//; $_ } \n split /\\s*,\\s*/, $arg_str \n ]\n , file => $file\n , line => $line \n };\n bless $ref, $_[0] if @_;\n $ref\n } \n @lines\n ;\n return wantarray ? @frames : \\@frames;\n}\n"
},
{
"answer_id": 24822871,
"author": "user2291758",
"author_id": 2291758,
"author_profile": "https://Stackoverflow.com/users/2291758",
"pm_score": 2,
"selected": false,
"text": "use Devel::PrettyTrace;\nbt;\n"
},
{
"answer_id": 39011773,
"author": "Thariama",
"author_id": 346063,
"author_profile": "https://Stackoverflow.com/users/346063",
"pm_score": 5,
"selected": false,
"text": "my $i = 1;\nprint STDERR \"Stack Trace:\\n\";\nwhile ( (my @call_details = (caller($i++))) ){\n print STDERR $call_details[1].\":\".$call_details[2].\" in function \".$call_details[3].\"\\n\";\n}\n"
},
{
"answer_id": 56596630,
"author": "x-yuri",
"author_id": 52499,
"author_profile": "https://Stackoverflow.com/users/52499",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nsub printstack {\n my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash);\n my $i = 1;\n my @r;\n while (@r = caller($i)) {\n ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) = @r;\n print \"$filename:$line $subroutine\\n\";\n $i++;\n }\n}\n\nsub i {\n printstack();\n}\n\nsub h {\n i;\n}\n\nsub g {\n h;\n}\n\ng;\n /root/_/1.pl:21 main::i\n/root/_/1.pl:25 main::h\n/root/_/1.pl:28 main::g\n for (my $i = 0; my @r = caller($i); $i++) { print \"$r[1]:$r[2] $r[3]\\n\"; }\n"
},
{
"answer_id": 59791844,
"author": "Pablo Bianchi",
"author_id": 4970442,
"author_profile": "https://Stackoverflow.com/users/4970442",
"pm_score": 2,
"selected": false,
"text": "cpanm Devel::Confess\n perl -d:Confess myscript.pl\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
] |
229,010
|
<pre><code>$("#dvMyDIV").bind("resize", function(){
alert("Resized");
});
</code></pre>
<p>or</p>
<pre><code>$("#dvMyDIV").resize(function(){
alert("Resized");
});
</code></pre>
<p>The questions</p>
<ol>
<li>Why is this not working at FireFox, Chrome and Safari?</li>
<li>Can this be considered a jQuery bug since the resize is not handled for other browsers?</li>
<li>Could the only workaround be calling a SetTimeout function checking the clientHeight and clientWidth?</li>
<li>Any workarounds using jQuery?</li>
</ol>
|
[
{
"answer_id": 229028,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "$(window).resize(function() { });"
},
{
"answer_id": 229054,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 0,
"selected": false,
"text": "$(window).resize(function(){alert(\"Resized\");});\n"
},
{
"answer_id": 229182,
"author": "Matt Goddard",
"author_id": 5185,
"author_profile": "https://Stackoverflow.com/users/5185",
"pm_score": 1,
"selected": false,
"text": "function setMovieHeight(value) {\n var height = Number(value) + 50;\ndocument.getElementById(\"video\").height = height;\n}\n function setHeight(value) {\n var height = number(value) + 50;\n $('#MyDiv').attr('height') = height;\n}\n"
},
{
"answer_id": 4894469,
"author": "Ludmil Tinkov",
"author_id": 519553,
"author_profile": "https://Stackoverflow.com/users/519553",
"pm_score": 0,
"selected": false,
"text": "$(elem).bind('DOMAttrModified', func)"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17447/"
] |
229,012
|
<p>How can I convert a relative path to an absolute path in C on Unix?
Is there a convenient system function for this?</p>
<p>On Windows there is a <code>GetFullPathName</code> function that does the job, but I didn't find something similar on Unix...</p>
|
[
{
"answer_id": 229038,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 7,
"selected": true,
"text": "realpath() file_name . .. {PATH_MAX} resolved_name resolved_name realpath() #include <stdlib.h>\n...\nchar *symlinkpath = \"/tmp/symlink/file\";\nchar actualpath [PATH_MAX+1];\nchar *ptr;\n\n\nptr = realpath(symlinkpath, actualpath);\n"
},
{
"answer_id": 41212150,
"author": "PADYMKO",
"author_id": 6003870,
"author_profile": "https://Stackoverflow.com/users/6003870",
"pm_score": 0,
"selected": false,
"text": "#include <unistd.h>\n\nchar cwd[100000];\ngetcwd(cwd, sizeof(cwd));\nstd::cout << \"Absolute path: \"<< cwd << \"/\" << __FILE__ << std::endl;\n Absolute path: /media/setivolkylany/WorkDisk/Programming/Sources/MichailFlenov/main.cpp\n setivolkylany@localhost$/ lsb_release -a\nNo LSB modules are available.\nDistributor ID: Debian\nDescription: Debian GNU/Linux 8.6 (jessie)\nRelease: 8.6\nCodename: jessie\nsetivolkylany@localhost$/ uname -a\nLinux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux\nsetivolkylany@localhost$/ g++ --version\ng++ (Debian 4.9.2-10) 4.9.2\nCopyright (C) 2014 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
},
{
"answer_id": 53808693,
"author": "Scott Yang",
"author_id": 4751658,
"author_profile": "https://Stackoverflow.com/users/4751658",
"pm_score": 3,
"selected": false,
"text": "realpath() stdlib.h char filename[] = \"../../../../data/000000.jpg\";\nchar* path = realpath(filename, NULL);\nif(path == NULL){\n printf(\"cannot find file with name[%s]\\n\", filename);\n} else{\n printf(\"path[%s]\\n\", path);\n free(path);\n}\n"
},
{
"answer_id": 54970463,
"author": "Julius",
"author_id": 10674275,
"author_profile": "https://Stackoverflow.com/users/10674275",
"pm_score": 2,
"selected": false,
"text": "#include <cwalk.h>\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n char buffer[FILENAME_MAX];\n\n cwk_path_get_absolute(\"/hello/there\", \"./world\", buffer, sizeof(buffer));\n printf(\"The absolute path is: %s\", buffer);\n\n return EXIT_SUCCESS;\n}\n The absolute path is: /hello/there/world\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9280/"
] |
229,015
|
<p>Is there any free java library which I can use to convert string in one encoding to other encoding, something like <a href="https://en.wikipedia.org/wiki/Iconv" rel="nofollow noreferrer"><code>iconv</code></a>? I'm using Java version 1.3.</p>
|
[
{
"answer_id": 229022,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "CharsetDecoder ISO-8859-1 ISO-Latin-1 Charset UTF16 US-ASCII ISO-8859-1 ISO-LATIN-1 UTF-8 UTF-16BE UTF-16LE UTF-16 ISO-8859-1 ByteBuffer CharBuffer // Create the encoder and decoder for ISO-8859-1\nCharset charset = Charset.forName(\"ISO-8859-1\");\nCharsetDecoder decoder = charset.newDecoder();\nCharsetEncoder encoder = charset.newEncoder();\n\ntry {\n // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer\n // The new ByteBuffer is ready to be read.\n ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(\"a string\"));\n\n // Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.\n // The new ByteBuffer is ready to be read.\n CharBuffer cbuf = decoder.decode(bbuf);\n String s = cbuf.toString();\n} catch (CharacterCodingException e) {\n}\n"
},
{
"answer_id": 229023,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "%20"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15878/"
] |
229,021
|
<p>We want to show a hint for a JList that the user can select multiple items with the platform dependent key for multiselect. </p>
<p>However I have not found any way to show the OS X COMMAND symbol in a JLabel, which means the symbol that's printed on the apple keyboard on the command key, also called apple key.</p>
<p>Here's a picture of the symbol I want to display on OS X. <a href="https://i.stack.imgur.com/VKGb4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VKGb4.png" alt="COMMAND SYMBOL"></a><br>
<sub>(source: <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Command_key.svg/120px-Command_key.svg.png" rel="nofollow noreferrer">wikimedia.org</a>)</sub> </p>
<p>Also I do want to have it platform independent.</p>
<p>I.e. something like </p>
<pre><code>component.add( new JList() , BorderLayout.CENTER );
component.add( new JLabel( MessageFormat.format("With {0} you can "
+ "select multiple items",
KeyStroke.getKeyStroke( ... , ... ) ) ) , BorderLayout.SOUTH );
</code></pre>
<p>Where instead of the <em>{0}</em> there should appear above seen symbol...</p>
<p>Does any one of you guys know how to do this? I know it must be possible somehow since in the JMenuItems there is the symbol...</p>
<p>My own (non graphical solutions) looks like this:</p>
<pre><code>add( new JLabel( MessageFormat.format(
"With {0} you can select multiple items" ,
System.getProperty( "mrj.version" ) != null ? "COMMAND" : "CTRL" ) ) ,
BorderLayout.SOUTH );
</code></pre>
|
[
{
"answer_id": 232786,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 0,
"selected": false,
"text": "add( new JLabel( MessageFormat.format(\n \"With {0} you can select multiple items\", \n getMetaKeyHint(),\n BorderLayout.SOUTH );\n\npublic String getMetaKeyHint() {\n return System.getProperty( \"mrj.version\" ) != null ? \"COMMAND\" : \"CTRL\" );\n}\n"
},
{
"answer_id": 233062,
"author": "Dan",
"author_id": 9774,
"author_profile": "https://Stackoverflow.com/users/9774",
"pm_score": 0,
"selected": false,
"text": "(System.getProperty(\"os.name\").toUpperCase(Locale.US).indexOf(\"MAC OS X\") == 0 )\n"
},
{
"answer_id": 236642,
"author": "banjollity",
"author_id": 29620,
"author_profile": "https://Stackoverflow.com/users/29620",
"pm_score": 3,
"selected": true,
"text": "JLabel label = new JLabel( \"<html>⌘ is the Apple command symbol.\" );\n"
},
{
"answer_id": 236771,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "\\u2318"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16193/"
] |
229,031
|
<p>I need to test a web form that takes a file upload.
The filesize in each upload will be about 10 MB.
I want to test if the server can handle over 100 simultaneous uploads, and still remain
responsive for the rest of the site.</p>
<p>Repeated form submissions from our office will be limited by our local DSL line.
The server is offsite with higher bandwidth.</p>
<p>Answers based on experience would be great, but any suggestions are welcome.</p>
|
[
{
"answer_id": 229051,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "/dev/urandom"
},
{
"answer_id": 323983,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 4,
"selected": true,
"text": "test.jpg http://localhost/ ab -n 100 -c 4 -p test.jpg http://localhost/\n Server Software: \nServer Hostname: localhost\nServer Port: 80\n\nDocument Path: /\nDocument Length: 0 bytes\n\nConcurrency Level: 4\nTime taken for tests: 0.78125 seconds\nComplete requests: 100\nFailed requests: 0\nWrite errors: 0\nNon-2xx responses: 100\nTotal transferred: 2600 bytes\nHTML transferred: 0 bytes\nRequests per second: 1280.00 [#/sec] (mean)\nTime per request: 3.125 [ms] (mean)\nTime per request: 0.781 [ms] (mean, across all concurrent requests)\nTransfer rate: 25.60 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 2.6 0 15\nProcessing: 0 2 5.5 0 15\nWaiting: 0 1 4.8 0 15\nTotal: 0 2 6.0 0 15\n\nPercentage of the requests served within a certain time (ms)\n 50% 0\n 66% 0\n 75% 0\n 80% 0\n 90% 15\n 95% 15\n 98% 15\n 99% 15\n 100% 15 (longest request)\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18333/"
] |
229,058
|
<p>When using something like <code>object.methods.sort.to_yaml</code> I'd like to have irb interpret the \n characters rather than print them. </p>
<p>I currently get the following output:</p>
<pre><code>--- \n- "&"\n- "*"\n- +\n- "-"\n- "<<"\n- <=>\n ...
</code></pre>
<p>What I'd like is something similar to this:</p>
<pre><code>---
- "&"
- "*"
- +
- "-"
- "<<"
- <=>
</code></pre>
<p>Is this possible? Is there another method I can be calling which will interpret the string perhaps?</p>
|
[
{
"answer_id": 229064,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 0,
"selected": false,
"text": "return print puts"
},
{
"answer_id": 229065,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "puts > puts object.methods.sort.to_yaml\n--- \n - \"&\"\n - \"*\"\n - +\n - \"-\"\n - \"<<\"\n - <=>\n => nil\n"
},
{
"answer_id": 229148,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 1,
"selected": false,
"text": "C:\\>irb --noinspect\nirb(main):001:0> Object.methods.to_yaml\n=> ---\n- instance_method\n- yaml_tag_read_class\n.....\n- constants\n- is_a?\n\nirb(main):002:0>\n"
},
{
"answer_id": 238354,
"author": "slothbear",
"author_id": 2464,
"author_profile": "https://Stackoverflow.com/users/2464",
"pm_score": 1,
"selected": false,
"text": "y object.methods.sort\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17453/"
] |
229,069
|
<p>How would you go about dead code detection in C/C++ code? I have a pretty large code base to work with and at least 10-15% is dead code. Is there any Unix based tool to identify this areas? Some pieces of code still use a lot of preprocessor, can automated process handle that?</p>
|
[
{
"answer_id": 562957,
"author": "Thomas L Holaday",
"author_id": 29403,
"author_profile": "https://Stackoverflow.com/users/29403",
"pm_score": 2,
"selected": false,
"text": "int foo() { \n return 21; // point a\n}\n\nint bar() {\n int a = 7;\n return a;\n a += 9; // point b\n return a;\n}\n\nint main(int, char **) {\n return bar();\n}\n"
},
{
"answer_id": 1140246,
"author": "Pascal Cuoq",
"author_id": 139746,
"author_profile": "https://Stackoverflow.com/users/139746",
"pm_score": 3,
"selected": false,
"text": "printf"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3579/"
] |
229,071
|
<p>how to show all values of a particular field in a text box ???
ie. for eg. when u run the SP, u'll be getting 3 rows. and i want to show the (eg.empname)
in a textbox each value separated by a comma.
(ram, john, sita). </p>
|
[
{
"answer_id": 229282,
"author": "CaRDiaK",
"author_id": 15628,
"author_profile": "https://Stackoverflow.com/users/15628",
"pm_score": 1,
"selected": false,
"text": "Structure; \nID TYPE TEXT\n1 1 Ram\n2 1 Jon\n3 2 Sita\n4 2 Joe\n\n\nExpecteed Output;\nID TYPE TEXT\n1 1 Ram, Jon\n2 2 Sita, Joe\n\nQuery; \nSELECT t.TYPE,LEFT(tl.txtlist,LEN(tl.txtlist)-1)\nFROM(SELECT DISTINCT TYPE FROM Table)t\nCROSS APPLY (SELECT TEXT + ','\n FROM Table\n WHERE TYPE=t.TYPE\n FOR XML PATH(''))tl(txtlist)\n"
},
{
"answer_id": 345101,
"author": "jerryhung",
"author_id": 37568,
"author_profile": "https://Stackoverflow.com/users/37568",
"pm_score": 0,
"selected": false,
"text": "SELECT \nCustomerID, \nSalesOrderIDs = REPLACE( \n ( \n SELECT \n SalesOrderID AS [data()] \n FROM \n Sales.SalesOrderHeader soh \n WHERE \n soh.CustomerID = c.CustomerID \n ORDER BY \n SalesOrderID \n FOR XML PATH ('') \n ), ' ', ',') \n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29867/"
] |
229,078
|
<p>The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.</p>
<p>Any help would be much appreciated.</p>
<pre><code>function validate_phone($phone)
{
$phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$";
$phonevalid = 0;
if (ereg($phoneregexp, $phone))
{
$phonevalid = 1;
}else{
$phonevalid = 0;
}
}
</code></pre>
|
[
{
"answer_id": 229089,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": true,
"text": "preg preg_match return preg_match($regex, $phone) !== 0;\n ereg return ereg($regex, $phone) !== FALSE;\n FALSE ereg bool"
},
{
"answer_id": 229095,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 2,
"selected": false,
"text": "preg_match() <?php\nfunction validate_phone($phone) {\n $phoneregexp ='/^(\\+[1-9][0-9]*(\\([0-9]*\\)|-[0-9]*-))?[0]?[1-9][0-9\\- ]*$/';\n\n $phonevalid = 0;\n\n if (preg_match($phoneregexp, $phone)) {\n $phonevalid = 1;\n } else {\n $phonevalid = 0;\n }\n}\nvalidate_phone(\"123456\");\n?>\n"
},
{
"answer_id": 229109,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "[0-9\\\\- ] - [0-9 -] -"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
229,080
|
<p>Is there a best-practice or common way in JavaScript to have class members as event handlers?</p>
<p>Consider the following simple example:</p>
<pre><code><head>
<script language="javascript" type="text/javascript">
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked;
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="Click me" />
<script language="javascript" type="text/javascript">
var btn1counter = new ClickCounter('btn1');
</script>
</body>
</code></pre>
<p>The event handler buttonClicked gets called, but the _clickCount member is inaccessible, or <em>this</em> points to some other object.</p>
<p>Any good tips/articles/resources about this kind of problems?</p>
|
[
{
"answer_id": 229110,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 6,
"selected": true,
"text": "ClickCounter = function(buttonId) {\n this._clickCount = 0;\n var that = this;\n document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };\n}\n\nClickCounter.prototype = {\n buttonClicked: function() {\n this._clickCount++;\n alert('the button was clicked ' + this._clickCount + ' times');\n }\n}\n class ClickCounter {\n count = 0;\n constructor( buttonId ){\n document.getElementById(buttonId)\n .addEventListener( \"click\", this.buttonClicked );\n }\n buttonClicked = e => {\n this.count += 1;\n console.log(`clicked ${this.count} times`);\n }\n}\n"
},
{
"answer_id": 229189,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 3,
"selected": false,
"text": "this function MyClass() {this.count = 0;}\nMyClass.prototype.onclickHandler = function(target)\n{\n // use target when you need values from the object that had the handler attached\n this.count++;\n}\nMyClass.prototype.attachOnclick = function(elem)\n{\n var self = this;\n elem.onclick = function() {self.onclickHandler(this); }\n elem = null; //prevents memleak\n}\n\nvar o = new MyClass();\no.attachOnclick(document.getElementById('divThing'))\n"
},
{
"answer_id": 36102050,
"author": "kucherenkovova",
"author_id": 3900376,
"author_profile": "https://Stackoverflow.com/users/3900376",
"pm_score": 4,
"selected": false,
"text": "Function.prototype.bind ClickCounter = function(buttonId) {\n this._clickCount = 0;\n document.getElementById(buttonId).onclick = this.buttonClicked.bind(this);\n}\n\nClickCounter.prototype = {\n buttonClicked: function() {\n this._clickCount++;\n alert('the button was clicked ' + this._clickCount + ' times');\n }\n}\n"
},
{
"answer_id": 36104114,
"author": "Tero Tolonen",
"author_id": 2287682,
"author_profile": "https://Stackoverflow.com/users/2287682",
"pm_score": 3,
"selected": false,
"text": "function doIt() {\n this.f = () => {\n console.log(\"f called ok\");\n this.g();\n }\n this.g = () => {\n console.log(\"g called ok\");\n }\n}\n var n = new doIt();\nsetTimeout(n.f,1000);\n"
},
{
"answer_id": 65633153,
"author": "Herman Van Der Blom",
"author_id": 2111313,
"author_profile": "https://Stackoverflow.com/users/2111313",
"pm_score": 2,
"selected": false,
"text": "unnamed this.navToggle.addEventListener('click', () => this.toggleNav() );\n this.toggleNav() Class this.navToggle.addEventListener('click', () => { [any code] } );\n arrow functions Classes Methods"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30056/"
] |
229,117
|
<p>I <em>sometimes</em> get the following exception for a custom control of mine:</p>
<p><code>XamlParseException occurred</code> <code>Unknown attribute Points in element SectionClickableArea [Line: 10 Position 16]</code></p>
<p>The stack trace:</p>
<pre><code>{System.Windows.Markup.XamlParseException: Unknown attribute Points on element SectionClickableArea. [Line: 10 Position: 16]
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at SomeMainDialog.InitializeComponent()
at SomeMainDialog..ctor()}
</code></pre>
<p>The element declaration where this happens looks like this (the <strong>event handler</strong> referenced here is defined, of course):</p>
<pre><code><l:SectionClickableArea x:Name="SomeButton"
Points="528,350, 508,265, 520,195, 515,190, 517,165, 530,120, 555,75, 570,61, 580,60, 600,66, 615,80, 617,335, 588,395, 550,385, 540,390, 525,393, 520,385"
Click="SomeButton_Click"/>
</code></pre>
<p>This is part of the code of <code>SectionClickableArea</code>:</p>
<pre><code>public partial class SectionClickableArea : Button {
public static readonly DependencyProperty PointsProperty
= DependencyProperty.Register("Points", typeof(PointCollection), typeof(SectionClickableArea),
new PropertyMetadata((s, e) => {
SectionClickableArea area = (SectionClickableArea) s;
area.areaInfo.Points = (PointCollection) e.NewValue;
area.UpdateLabelPosition();
}));
public PointCollection Points {
get { return (PointCollection) GetValue(PointsProperty); }
set { SetValue(PointsProperty, value); }
}
</code></pre>
<p>I use this control for something like a polygon-shaped button. Therefore I'm inheriting from button. I've had similar problems (<code>E_AG_BAD_PROPERTY_VALUE</code> on another <code>DependencyProperty</code> of type string, according to the line and column given, etc) with this control for weeks, but I have absolutely no idea why.</p>
<hr>
<p>Another exception for the same control occurred this morning for another user (taken from a log and translated from German):</p>
<pre><code>Type: System.InvalidCastException Message: The object of type System.Windows.Controls.ContentControl could not be converted to type [...]SectionClickableArea. at SomeOtherMainDialog.InitializeComponent()
at SomeOtherMainDialog..ctor()
</code></pre>
<p>Inner exception:</p>
<pre><code>Type: System.Exception Message: An HRESULT E_FAIL error was returned when calling COM component at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper obj, DependencyProperty property, DependencyObject doh)
at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper doh, DependencyProperty property, Object obj)
at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet, Boolean isSetByStyle, Boolean isSetByBuiltInStyle)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
at System.Windows.Controls.Control.set_DefaultStyleKey(Object value)
at System.Windows.Controls.ContentControl..ctor()
at System.Windows.CoreTypes.GetCoreWrapper(Int32 typeId)
at MS.Internal.ManagedPeerTable.EnsureManagedPeer(IntPtr unmanagedPointer, Int32 typeIndex, Type type, Boolean preserveManagedObjectReference)
at MS.Internal.ManagedPeerTable.EnsureManagedPeer(IntPtr unmanagedPointer, Int32 typeIndex, Type type)
at MS.Internal.ManagedPeerTable.GetManagedPeer(IntPtr nativeObject)
at MS.Internal.FrameworkCallbacks.SetPropertyAttribute(IntPtr nativeTarget, String attrName, String attrValue, String attachedDPOwnerNamespace, String attachedDPOwnerAssembly)
</code></pre>
<p>Any ideas what's wrong with the control, or what I can do to find the source of these exceptions? As I said, these problem occur only every few dozen times the control is instantiated.</p>
|
[
{
"answer_id": 1063206,
"author": "Nikolay R",
"author_id": 18635,
"author_profile": "https://Stackoverflow.com/users/18635",
"pm_score": 1,
"selected": false,
"text": "<UserControl.Resources>\n <customNamespace:InheritedControl x:Name=\"dummyInstance\"/>\n</UserControl.Resources>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23222/"
] |
229,137
|
<p>This question is related to another question which I asked yesterday! </p>
<p><a href="https://stackoverflow.com/questions/220796/list-all-links-in-web-site">List all links in web site</a></p>
<p>I think renaming all the .html files to .asp and changing the links is not good for SEP purposes. Some one told me that isapi plug-in can be used to redirect(301) all .html files to .asp files. </p>
<p>Can any one explain this for me? Searching did not help me much.</p>
<p>Thanks</p>
|
[
{
"answer_id": 293110,
"author": "TAG",
"author_id": 36400,
"author_profile": "https://Stackoverflow.com/users/36400",
"pm_score": 1,
"selected": false,
"text": "<redirect url=\"^(.+)\\.html(.+)$\" to=\"$1.aspx$2\" permanent='true' />\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12178/"
] |
229,153
|
<pre><code><div>
<h1>Title</h1>
<table>
...
</table>
</div>
</code></pre>
<p>Now, the</p>
<pre><code><h1>
</code></pre>
<p>has a margin: 0;
so it is at the top of the div. The height of the div is 300px.</p>
<p>However I'd like the table to be placed at the bottom of the div, eg. valign="bottom" but for the whole table.</p>
|
[
{
"answer_id": 229184,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "<style type=\"text/css\">\n#container { \n position: absolute; \n margin: 0;\n height:300px;\n border:1px solid #000; }\n#container h1 { \n margin:0; }\n#tableContainer { \n position: absolute;\n bottom:0; }\n</style>\n\n<div id=\"container\">\n <h1>Title</h1>\n <div id=\"tableContainer\">\n <table id=\"tableLayout\">\n <tr><td>...</td></tr>\n </table>\n </div>\n</div>\n"
},
{
"answer_id": 229223,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 2,
"selected": false,
"text": "<style type=\"text/css\" media=\"screen\">\n#container { \n position: relative; \n margin: 0;\n height:300px;\n border:1px solid #000; \n}\n#container h1 { \n margin:0; \n}\n#tableLayout { \n position: absolute;\n bottom:0; \n border: 1px solid #c00;\n}\n</style>\n\n<div id=\"container\">\n <h1>Title</h1>\n <table id=\"tableLayout\">\n <tr><td>example cell</td></tr>\n </table>\n</div>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
229,168
|
<p>I find print_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?</p>
|
[
{
"answer_id": 229175,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "use Data::Dumper;\n\npackage Foo;\nsub new {bless {'a' => 1, 'b' => sub { return \"foo\" }}, $_[0]};\n\npackage Fuz; # a weird REF-REF-SCALAR object\nsub new {bless \\($_ = \\ 'fu\\'z'), $_[0]};\n\npackage main;\n$foo = Foo->new;\n$fuz = Fuz->new;\n$boo = [ 1, [], \"abcd\", \\*foo,\n {1 => 'a', 023 => 'b', 0x45 => 'c'}, \n \\\\\"p\\q\\'r\", $foo, $fuz];\n\n########\n# simple usage\n########\n\n$bar = eval(Dumper($boo));\nprint($@) if $@;\nprint Dumper($boo), Dumper($bar); # pretty print (no array indices)\n\n$Data::Dumper::Terse = 1; # don't output names where feasible\n$Data::Dumper::Indent = 0; # turn off all pretty print\nprint Dumper($boo), \"\\n\";\n\n$Data::Dumper::Indent = 1; # mild pretty print\nprint Dumper($boo);\n\n$Data::Dumper::Indent = 3; # pretty print with array indices\nprint Dumper($boo);\n\n$Data::Dumper::Useqq = 1; # print strings in double quotes\nprint Dumper($boo);\n"
},
{
"answer_id": 230010,
"author": "mirod",
"author_id": 11095,
"author_profile": "https://Stackoverflow.com/users/11095",
"pm_score": 3,
"selected": false,
"text": "x 2 $complex_structure"
},
{
"answer_id": 230020,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "x"
},
{
"answer_id": 489152,
"author": "Stan James",
"author_id": 59913,
"author_profile": "https://Stackoverflow.com/users/59913",
"pm_score": 2,
"selected": false,
"text": "print objectToString($json_data);\n HASH {\ntime => 1233173875\nerror => 0\nnode => HASH {\n vid => 1011\n moderate => 0\n field_datestring => ARRAY {\n HASH {\n value => August 30, 1979\n }\n }\n\n field_tagged_persons => ARRAY {\n HASH {\n nid => undef\n }\n }\n\n...and so on...\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] |
229,186
|
<p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
|
[
{
"answer_id": 229192,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "os.listdir() os.stat()"
},
{
"answer_id": 229219,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 8,
"selected": false,
"text": "import os\n\nroot = \"C:\\\\\"\nfor item in os.listdir(root):\n if os.path.isfile(os.path.join(root, item)):\n print item\n"
},
{
"answer_id": 229293,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 5,
"selected": false,
"text": "listdir root, dirs, files = os.walk(dir_name).next() root, dirs, files = next(os.walk(dir_name))"
},
{
"answer_id": 229300,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "def _dir_list(self, dir_name, whitelist):\n outputList = []\n for root, dirs, files in os.walk(dir_name):\n dirs[:] = [d for d in dirs if is_good(d)]\n for f in files:\n do_stuff()\n"
},
{
"answer_id": 234329,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 8,
"selected": true,
"text": "walklevel import os\n\ndef walklevel(some_dir, level=1):\n some_dir = some_dir.rstrip(os.path.sep)\n assert os.path.isdir(some_dir)\n num_sep = some_dir.count(os.path.sep)\n for root, dirs, files in os.walk(some_dir):\n yield root, dirs, files\n num_sep_this = root.count(os.path.sep)\n if num_sep + level <= num_sep_this:\n del dirs[:]\n os.walk level"
},
{
"answer_id": 12965151,
"author": "Diana G",
"author_id": 187696,
"author_profile": "https://Stackoverflow.com/users/187696",
"pm_score": 2,
"selected": false,
"text": "for path, subdirs, files in os.walk(dir_name):\n for name in files:\n if path == \".\": #this will filter the files in the current directory\n #code here\n"
},
{
"answer_id": 20868760,
"author": "Pieter",
"author_id": 2367867,
"author_profile": "https://Stackoverflow.com/users/2367867",
"pm_score": 6,
"selected": false,
"text": "break\n for root, dirs, files in os.walk(dir_name):\n for f in files:\n ...\n ...\n break\n...\n def _dir_list(self, dir_name, whitelist):\n outputList = []\n for root, dirs, files in os.walk(dir_name):\n for f in files:\n if os.path.splitext(f)[1] in whitelist:\n outputList.append(os.path.join(root, f))\n else:\n self._email_to_(\"ignore\")\n break\n return outputList\n"
},
{
"answer_id": 24418093,
"author": "Oleg Gryb",
"author_id": 1152643,
"author_profile": "https://Stackoverflow.com/users/1152643",
"pm_score": 2,
"selected": false,
"text": "listdir [f for f in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, f))]\n"
},
{
"answer_id": 27804208,
"author": "Deifyed",
"author_id": 1037328,
"author_profile": "https://Stackoverflow.com/users/1037328",
"pm_score": 0,
"selected": false,
"text": "if recursive:\n items = os.walk(target_directory)\nelse:\n items = [next(os.walk(target_directory))]\n\n...\n"
},
{
"answer_id": 32747111,
"author": "Kemin Zhou",
"author_id": 2407363,
"author_profile": "https://Stackoverflow.com/users/2407363",
"pm_score": 0,
"selected": false,
"text": "for dirname in os.listdir(rootdir):\n if os.path.isdir(os.path.join(rootdir, dirname)):\n print(\"I got a subdirectory: %s\" % dirname)\n"
},
{
"answer_id": 36358596,
"author": "Jay Sheth",
"author_id": 2761777,
"author_profile": "https://Stackoverflow.com/users/2761777",
"pm_score": 2,
"selected": false,
"text": "import os\ndir = \"/path/to/files/\"\n\n#List all files immediately under this folder:\nprint ( next( os.walk(dir) )[2] )\n\n#List all folders immediately under this folder:\nprint ( next( os.walk(dir) )[1] )\n"
},
{
"answer_id": 37008598,
"author": "masterxilo",
"author_id": 524504,
"author_profile": "https://Stackoverflow.com/users/524504",
"pm_score": 3,
"selected": false,
"text": "for path, dirs, files in os.walk('.'):\n print path, dirs, files\n del dirs[:] # go only one level deep\n"
},
{
"answer_id": 39118773,
"author": "alexandre-rousseau",
"author_id": 5935198,
"author_profile": "https://Stackoverflow.com/users/5935198",
"pm_score": 0,
"selected": false,
"text": "for root, dirs, files in os.walk(directory):\n if level > 0:\n # do some stuff\n else:\n break\n level-=1\n"
},
{
"answer_id": 44323989,
"author": "Matt R",
"author_id": 8102025,
"author_profile": "https://Stackoverflow.com/users/8102025",
"pm_score": 3,
"selected": false,
"text": "baselevel = len(rootdir.split(os.path.sep))\nfor subdirs, dirs, files in os.walk(rootdir):\n curlevel = len(subdirs.split(os.path.sep))\n if curlevel <= baselevel + 1:\n [do stuff]\n"
},
{
"answer_id": 47409969,
"author": "Hamsavardhini",
"author_id": 5348858,
"author_profile": "https://Stackoverflow.com/users/5348858",
"pm_score": 0,
"selected": false,
"text": "excludes= ['a\\*\\b', 'c\\d\\e']\nfor root, directories, files in os.walk('Start_Folder'):\n if not any(fnmatch.fnmatch(nf_root, pattern) for pattern in excludes):\n for root, directories, files in os.walk(nf_root):\n ....\n do the process\n ....\n if **any**(fnmatch.fnmatch(nf_root, pattern) for pattern in **includes**):\n"
},
{
"answer_id": 53547750,
"author": "PiMathCLanguage",
"author_id": 5462449,
"author_profile": "https://Stackoverflow.com/users/5462449",
"pm_score": 0,
"selected": false,
"text": "range os.walk zip # your part before\nfor count, (root, dirs, files) in zip(range(0, 1), os.walk(dir_name)):\n # logic stuff\n# your later part\n break"
},
{
"answer_id": 54442325,
"author": "Oleg",
"author_id": 1555328,
"author_profile": "https://Stackoverflow.com/users/1555328",
"pm_score": 0,
"selected": false,
"text": "__next__() print(next(os.walk('d:/'))[2]) print(os.walk('d:/').__next__()[2]) [2] file root, dirs, file"
},
{
"answer_id": 56325893,
"author": "ascripter",
"author_id": 3104974,
"author_profile": "https://Stackoverflow.com/users/3104974",
"pm_score": 2,
"selected": false,
"text": "os.scandir os.listdir DirEntry scandir() listdir() DirEntry DirEntry is_dir() is_file() DirEntry.stat() DirEntry.name os.listdir"
},
{
"answer_id": 56463621,
"author": "Pedro J. Sola",
"author_id": 6460022,
"author_profile": "https://Stackoverflow.com/users/6460022",
"pm_score": 0,
"selected": false,
"text": "def _dir_list(self, dir_name, whitelist):\n outputList = []\n for root, dirs, files in os.walk(dir_name):\n if root == dir_name: #This only meet parent folder\n for f in files:\n if os.path.splitext(f)[1] in whitelist:\n outputList.append(os.path.join(root, f))\n else:\n self._email_to_(\"ignore\")\n return outputList\n"
},
{
"answer_id": 58172376,
"author": "Rich",
"author_id": 12144392,
"author_profile": "https://Stackoverflow.com/users/12144392",
"pm_score": 1,
"selected": false,
"text": "import os\n\ndef listFiles(self, dir_name):\n names = []\n for root, directory, files in os.walk(dir_name):\n if root == dir_name:\n for name in files:\n names.append(name)\n return names\n"
},
{
"answer_id": 65420645,
"author": "Alon Barad",
"author_id": 8622976,
"author_profile": "https://Stackoverflow.com/users/8622976",
"pm_score": 0,
"selected": false,
"text": "def walk_with_depth(root_path, depth):\n if depth < 0:\n for root, dirs, files in os.walk(root_path):\n yield [root, dirs[:], files]\n\n return\n\n elif depth == 0:\n return\n\n base_depth = root_path.rstrip(os.path.sep).count(os.path.sep)\n for root, dirs, files in os.walk(root_path):\n yield [root, dirs[:], files]\n\n cur_depth = root.count(os.path.sep)\n \n if base_depth + depth <= cur_depth:\n del dirs[:]\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
229,201
|
<p>I would like to do remote deployment from my build machine onto a server. The remoting can be done via ssh commands from a script, but I would rather use phing and a deploy.xml file that would do the automation.</p>
<p>What alternatives do I have to do ssh (and also scp) tasks from within a phing build file?</p>
|
[
{
"answer_id": 229372,
"author": "user30684",
"author_id": 30684,
"author_profile": "https://Stackoverflow.com/users/30684",
"pm_score": 3,
"selected": false,
"text": "<exec command=\"scp -i keys/id_rsa myfile user@$server:myfile\" dir=\".\" />\n"
},
{
"answer_id": 26971137,
"author": "Rob Allen",
"author_id": 23060,
"author_profile": "https://Stackoverflow.com/users/23060",
"pm_score": 0,
"selected": false,
"text": "sudo pecl install pecl.php.net/ssh2-0.12 <?xml version=\"1.0\"?>\n<project name=\"test\" default=\"test\">\n <target name=\"test\">\n <ssh username=\"vagrant\" password=\"vagrant\" host=\"192.168.123.456\"\n command=\"pwd\" property=\"pwd\" display=\"false\" />\n <echo>The current working directory is ${pwd}</echo>\n </target>\n</project>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26639/"
] |
229,206
|
<p>I have some code which needs to ensure some data is in a mysql enum prior to insertion in the database. The cleanest way I've found of doing this is the following code:</p>
<pre><code>sub enum_values {
my ( $self, $schema, $table, $column ) = @_;
# don't eval to let the error bubble up
my $columns = $schema->storage->dbh->selectrow_hashref(
"SHOW COLUMNS FROM `$table` like ?",
{},
$column
);
unless ($columns) {
X::Internal::Database::UnknownColumn->throw(
column => $column,
table => $table,
);
}
my $type = $columns->{Type} or X::Panic->throw(
details => "Could not determine type for $table.$column",
);
unless ( $type =~ /\Aenum\((.*)\)\z/ ) {
X::Internal::Database::IncorrectTypeForColumn->throw(
type_wanted => 'enum',
type_found => $type,
);
}
$type = $1;
require Text::CSV_XS;
my $csv = Text::CSV_XS->new;
$csv->parse($type) or X::Panic->throw(
details => "Could not parse enum CSV data: ".$csv->error_input,
);
return map { /\A'(.*)'\z/; $1 }$csv->fields;
}
</code></pre>
<p>We're using <a href="http://search.cpan.org/dist/DBIx-Class/" rel="noreferrer">DBIx::Class</a>. Surely there is a better way of accomplishing this? (Note that the $table variable is coming from our code, <em>not</em> from any external source. Thus, no security issue).</p>
|
[
{
"answer_id": 229278,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "my @fields = $type =~ / ' ([^']+) ' (?:,|\\z) /msgx;\n"
},
{
"answer_id": 229561,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 5,
"selected": true,
"text": "mysql_values my $sth = $dbh->column_info(undef, undef, 'mytable', '%');\n\nforeach my $col_info ($sth->fetchrow_hashref)\n{\n if($col_info->{'TYPE_NAME'} eq 'ENUM')\n {\n # The mysql_values key contains a reference to an array of valid enum values\n print \"Valid enum values for $col_info->{'COLUMN_NAME'}: \", \n join(', ', @{$col_info->{'mysql_values'}}), \"\\n\";\n }\n ...\n}\n"
},
{
"answer_id": 28756632,
"author": "cjac",
"author_id": 1110823,
"author_profile": "https://Stackoverflow.com/users/1110823",
"pm_score": 0,
"selected": false,
"text": "my $cfg = new Config::Simple( $rc_file );\nmy $mysql = $cfg->get_block('mysql');\nmy $dsn =\n \"DBI:mysql:database=$mysql->{database};\".\n \"host=$mysql->{hostname};port=$mysql->{port}\";\n\nmy $schema =\n DTSS::CDN::Schema->connect( $dsn, $mysql->{user}, $mysql->{password} );\n\nmy $valid_enum_values =\n $schema->source('Cdnurl')->column_info('scheme')->{extra}->{list};\n 14:40 < cj> is there a cross-platform way to get the valid values of an \n enum?\n15:11 < cj> it looks like I could add 'InflateColumn::Object::Enum' to the \n __PACKAGE__->load_components(...) list for tables with enum \n columns\n15:12 < cj> and then call values() on the enum column\n15:13 < cj> but how do I get dbic-dump to add \n 'InflateColumn::Object::Enum' to \n __PACKAGE__->load_components(...) for only tables with enum \n columns?\n15:20 < cj> I guess I could just add it for all tables, since I'm doing \n the same for InflateColumn::DateTime\n15:39 < cj> hurm... is there a way to get a column without making a \n request to the db?\n15:40 < cj> I know that we store in the DTSS::CDN::Schema::Result::Cdnurl \n class all of the information that I need to know about the \n scheme column before any request is issued\n15:42 <@ilmari> cj: for Pg and mysql Schema::Loader will add the list of \n valid values to the ->{extra}->{list} column attribute\n15:43 <@ilmari> cj: if you're using some other database that has enums, \n patches welcome :)\n15:43 <@ilmari> or even just a link to the documentation on how to extract \n the values\n15:43 <@ilmari> and a willingness to test if it's not a database I have \n access to\n15:43 < cj> thanks, but I'm using mysql. if I were using sqlite for this \n project, I'd probably oblige :-)\n15:44 <@ilmari> cj: to add components to only some tables, use \n result_components_map\n15:44 < cj> and is there a way to get at those attributes without making a \n query?\n15:45 < cj> can we do $schema->resultset('Cdnurl') without having it issue \n a query, for instance?\n15:45 <@ilmari> $result_source->column_info('colname')->{extra}->{list}\n15:45 < cj> and $result_source is $schema->resultset('Cdnurl') ?\n15:45 <@ilmari> dbic never issues a query until you start retrieving the \n results\n15:45 < cj> oh, nice.\n15:46 <@ilmari> $schema->source('Cdnurl')\n15:46 <@ilmari> the result source is where the result set gets the results \n from when they are needed\n15:47 <@ilmari> names have meanings :)\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8003/"
] |
229,254
|
<p>I have a server application that receives information over a network and processes it.
The server is multi-threaded and handles multiple sockets at time, and threads are created without my control through BeginInvoke and EndInvoke style methods, which are chained by corresponding callback functions.</p>
<p>I'm trying to create a form, in addition to the main GUI, that displays a ListBox item populated by items describing the currently connected sockets.
So, what I'm basically trying to do is add an item to the ListBox using its Add() function, from the thread the appropriate callback function is running on.
I'm accessing my forms controls through the Controls property - I.E:</p>
<pre><code>(ListBox)c.Controls["listBox1"].Items.Add();
</code></pre>
<p>Naturally I don't just call the function, I've tried several ways I've found here and on the web to communicate between threads, including <code>MethodInvoker</code>, using a <code>delegate</code>, in combination with <code>Invoke()</code>, <code>BeginInvoke()</code> etc.
Nothing seems to work, I always get the same exception telling me my control was accessed from a thread other than the one it was created on.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 229292,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 3,
"selected": false,
"text": " c = <your control>\n if (c.InvokeRequired)\n {\n c.BeginInvoke((MethodInvoker)delegate\n {\n //do something with c\n });\n }\n else\n {\n //do something with c\n }\n using System;\nusing System.ComponentModel;\npublic static class CrossThreadHelper\n{\n public static bool CrossThread<T,R>(this ISynchronizeInvoke value, Action<T, R> action, T sender, R e)\n {\n if (value.InvokeRequired)\n {\n value.BeginInvoke(action, new object[] { sender, e });\n }\n\n return value.InvokeRequired;\n }\n}\n private void OnServerMessageReceived(object sender, ClientStateArgs e)\n {\n if (this.CrossThread((se, ev) => OnServerMessageReceived(se, ev), sender, e)) return;\n this.statusTextBox.Text += string.Format(\"Message Received From: {0}\\r\\n\", e.ClientState);\n }\n"
},
{
"answer_id": 229294,
"author": "Magnus Lindhe",
"author_id": 966,
"author_profile": "https://Stackoverflow.com/users/966",
"pm_score": 3,
"selected": true,
"text": "ListBox listBox = c.Controls[\"listBox1\"] as ListBox;\nif(listBox != null)\n{\n listBox.Invoke(...);\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
229,269
|
<p>PHP 4.4 and PHP 5.2.3 under Apache 2.2.4 on ubuntu.</p>
<p>I am running Moodle 1.5.3 and have recently had a problem when updating a course. The $_POST variable is empty but only if a lot of text was entered into the textarea on the form. If only a short text is entered it works fine.</p>
<p>I have increased the post_max_size from 8M to 200M and increased the memory_limit to 256M but this has not helped.
I have doubled the LimitRequestFieldSize and LimitRequestLine to 16380 and set LimitRequestBody to 0 with no improvement.</p>
<p>I have googled for an answer but have been unable to find one.</p>
<p>HTTP Headers on firefox shows the content size of 3816 with the correct data, so its just not getting to $_POST.</p>
<p>The system was running fine until a few weeks ago. The only change was to /etc/hosts to correct a HELO issue with the exim4 email server.</p>
<p>I can replicate the issue on a development machine that has exim4 not running so I think it is just coincidence.</p>
<p>Thanks for your assistance.</p>
|
[
{
"answer_id": 229431,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "file_get_contents('php://input');\n"
},
{
"answer_id": 229618,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "/form.php\n/directory/index.php\n <form action=\"/directory\" method=\"post\">\n...\n</form>\n /directory /directory/ $_POST"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30738/"
] |
229,272
|
<pre><code><div style="width: 300px">
<div id="one" style="float: left">saved</div><input type="submit" id="two" style="float: right" value="Submit" />
</div>
</code></pre>
<p>I would like div#one to be centred in the space between the left edge of the parent div and the left edge of the submit button.</p>
|
[
{
"answer_id": 229277,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 1,
"selected": false,
"text": "<div style=\"width: 300px\">\n<div id=\"one\" style=\"float: left;text-align:center;width:80%\">saved</div>\n<input type=\"submit\" id=\"two\" style=\"float: right;width:20%\" value=\"Submit\" />\n</div>\n"
},
{
"answer_id": 229323,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<div style=\"width: 300px\">\n <input type=\"submit\" id=\"two\" style=\"float: right\" value=\"Submit\" />\n <div id=\"one\" style=\"text-align:center;\">saved</div>\n</div>\n saved div <div style=\"width: 300px;\">\n <input type=\"submit\" id=\"two\" style=\"float: right; width:64px;\" value=\"Submit\" />\n <div id=\"one\" style=\"text-align:center;margin-right:64px;\">saved</div>\n</div>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
229,310
|
<p>I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't:</p>
<pre><code>DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance();
docfactory.setIgnoringElementContentWhitespace(true);
</code></pre>
<p>I see in Javadoc that setIgnoringElementContentWhitespace method operates only when the validating flag is enabled, but I haven't the DTD or XML Schema for the document.</p>
<p>What can I do?</p>
<p>Update</p>
<p>I don't like the idea of introduce mySelf < !ELEMENT... declarations and i have tried the
solution proposed in the <a href="http://forums.sun.com/thread.jspa?messageID=2054303#2699961" rel="noreferrer">forum</a> pointed by Tomalak, but it doesn't work, i have used java 1.6 in an linux environment. I think if no more is proposed i will make a few methods to ignore whitespace text nodes</p>
|
[
{
"answer_id": 5851888,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 3,
"selected": false,
"text": "NodeList private static class NdLst implements NodeList, Iterable<Node> {\n\n private List<Node> nodes;\n\n public NdLst(NodeList list) {\n nodes = new ArrayList<Node>();\n for (int i = 0; i < list.getLength(); i++) {\n if (!isWhitespaceNode(list.item(i))) {\n nodes.add(list.item(i));\n }\n }\n }\n\n @Override\n public Node item(int index) {\n return nodes.get(index);\n }\n\n @Override\n public int getLength() {\n return nodes.size();\n }\n\n private static boolean isWhitespaceNode(Node n) {\n if (n.getNodeType() == Node.TEXT_NODE) {\n String val = n.getNodeValue();\n return val.trim().length() == 0;\n } else {\n return false;\n }\n }\n\n @Override\n public Iterator<Node> iterator() {\n return nodes.iterator();\n }\n}\n NodeList"
},
{
"answer_id": 19602644,
"author": "huppyuy",
"author_id": 528900,
"author_profile": "https://Stackoverflow.com/users/528900",
"pm_score": 2,
"selected": false,
"text": "DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n dbFactory.setIgnoringElementContentWhitespace(true);\n dbFactory.setSchema(schema);\n dbFactory.setNamespaceAware(true);\nNodeList nodeList = element.getElementsByTagNameNS(\"*\", \"associate\");\n"
},
{
"answer_id": 48835894,
"author": "ImGroot",
"author_id": 2203209,
"author_profile": "https://Stackoverflow.com/users/2203209",
"pm_score": -1,
"selected": false,
"text": "private static Document prepareXML(String param) throws ParserConfigurationException, SAXException, IOException {\n\n param = param.replaceAll(\">\\\\s+<\", \"><\").trim();\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setIgnoringElementContentWhitespace(true);\n DocumentBuilder builder = factory.newDocumentBuilder();\n InputSource in = new InputSource(new StringReader(param));\n return builder.parse(in);\n\n }\n"
},
{
"answer_id": 51219452,
"author": "Tamias",
"author_id": 5799033,
"author_profile": "https://Stackoverflow.com/users/5799033",
"pm_score": 1,
"selected": false,
"text": "// A small portion of my main class.\n// Other imports may be necessary...\nimport org.w3c.dom.bootstrap.DOMImplementationRegistry;\nimport org.w3c.dom.ls.DOMImplementationLS;\nimport org.w3c.dom.ls.LSParser;\nimport org.w3c.dom.ls.LSParserFilter;\n\nDocument controlDoc = null;\nDocument testDoc = null;\ntry {\n System.setProperty(DOMImplementationRegistry.PROPERTY, \"org.apache.xerces.dom.DOMImplementationSourceImpl\");\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(\"LS\");\n LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);\n LSParserFilter filter = new InputFilter();\n builder.setFilter(filter);\n controlDoc = builder.parseURI(files[0].getPath());\n testDoc = builder.parseURI(files[1].getPath());\n} catch (Exception exc) {\n System.out.println(exc.getMessage());\n}\n\n//--------------------------------------\n\nimport org.w3c.dom.ls.LSParserFilter;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.traversal.NodeFilter;\n\npublic class InputFilter implements LSParserFilter {\n\n public short acceptNode(Node node) {\n if (Utils.isNewline(node)) {\n return NodeFilter.FILTER_REJECT;\n }\n return NodeFilter.FILTER_ACCEPT;\n }\n\n public int getWhatToShow() {\n return NodeFilter.SHOW_ALL;\n }\n\n public short startElement(Element elem) {\n return LSParserFilter.FILTER_ACCEPT;\n }\n\n}\n\n//-------------------------------------\n// From my Utils.java:\n\n public static boolean isNewline(Node node) {\n return (node.getNodeType() == Node.TEXT_NODE) && node.getTextContent().equals(\"\\n\");\n }\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518/"
] |
229,346
|
<p>I have a String which I would like to modify in some way. For example: reverse it or upcase it. </p>
<p>I have discovered that the fastest way to do this is by using a unsafe block and pointers. </p>
<p>For example: </p>
<pre><code> unsafe
{
fixed (char* str = text)
{
*str = 'X';
}
}
</code></pre>
<p>Are there any reasons why I should never ever do this? </p>
|
[
{
"answer_id": 229351,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 5,
"selected": true,
"text": "String.intern // these strings get interned\n string hello = \"hello\";\n string hello2 = \"hello\";\n\n string helloworld, helloworld2;\n\n helloworld = hello;\n helloworld += \" world\";\n\n helloworld2 = hello;\n helloworld2 += \" world\"; \n\n unsafe\n {\n // very bad, this changes an interned string which affects \n // all app domains.\n fixed (char* str = hello2)\n {\n *str = 'X';\n }\n\n fixed (char* str = helloworld2)\n {\n *str = 'X';\n }\n\n }\n\n Console.WriteLine(\"hello = {0} , hello2 = {1}\", hello, hello2);\n // output: hello = Xello , hello2 = Xello \n\n\n Console.WriteLine(\"helloworld = {0} , helloworld2 = {1}\", helloworld, helloworld2);\n // output : helloworld = hello world , helloworld2 = Xello world \n"
},
{
"answer_id": 229354,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "s.SubString(0, s.Length) StringBuilder"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
229,352
|
<p>I am using Python to extract the filename from a link using rfind like below:</p>
<pre><code>url = "http://www.google.com/test.php"
print url[url.rfind("/") +1 : ]
</code></pre>
<p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "<a href="http://www.google.com/test.php/" rel="nofollow noreferrer">http://www.google.com/test.php/</a>". I am have trouble getting the page name when there is a "/" at the end, can anyone help?</p>
<p>Cheers</p>
|
[
{
"answer_id": 229386,
"author": "Tim Pietzcker",
"author_id": 20670,
"author_profile": "https://Stackoverflow.com/users/20670",
"pm_score": -1,
"selected": false,
"text": "print url[url.rstrip(\"/\").rfind(\"/\") +1 : ]\n"
},
{
"answer_id": 229394,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 1,
"selected": false,
"text": "test.php/ url = url.rstrip('/')\n"
},
{
"answer_id": 229401,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": false,
"text": "http://www.google.com/test.php?filepath=tests/hey.xml\n from urlparse import urlparse\nurl = \"http://www.google.com/test.php?something=heyharr/sir/a.txt\"\nf = urlparse(url)[2].rstrip(\"/\")\nprint f[f.rfind(\"/\")+1:]\n"
},
{
"answer_id": 229417,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 0,
"selected": false,
"text": "import re\nprint re.search('/([^/]+)/?$', url).group(1)\n"
},
{
"answer_id": 229430,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 2,
"selected": false,
"text": "url.rstrip('/').rsplit('/', 1)[-1]\n path= urlparse.urlparse(url).path\nreturn path.rstrip('/').rsplit('/', 1)[-1] or '(root path)'\n"
},
{
"answer_id": 229650,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": -1,
"selected": false,
"text": "filter(None, url.split('/'))[-1]\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
229,353
|
<p>In my main page (call it <code>index.aspx</code>) I call </p>
<pre><code><%Html.RenderPartial("_PowerSearch", ViewData.Model);%>
</code></pre>
<p>Here the <code>viewdata.model != null</code>
When I arrive at my partial:</p>
<pre><code><%=ViewData.Model%>
</code></pre>
<p>Says <code>viewdata.model == null</code></p>
<p>What gives?!</p>
|
[
{
"answer_id": 229367,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 2,
"selected": true,
"text": " /// <summary>\n /// Renders a LoggingWeb user control.\n /// </summary>\n /// <param name=\"helper\">Helper to extend.</param>\n /// <param name=\"control\">Type of control.</param>\n /// <param name=\"data\">ViewData to pass in.</param>\n public static void RenderLoggingControl(this System.Web.Mvc.HtmlHelper helper, LoggingControls control, object data)\n {\n string controlName = string.Format(\"{0}.ascx\", control);\n string controlPath = string.Format(\"~/Controls/{0}\", controlName);\n string absControlPath = VirtualPathUtility.ToAbsolute(controlPath);\n if (data == null)\n {\n helper.RenderPartial(absControlPath, helper.ViewContext.ViewData);\n }\n else\n {\n helper.RenderPartial(absControlPath, data, helper.ViewContext.ViewData);\n }\n }\n"
},
{
"answer_id": 229453,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 0,
"selected": false,
"text": "<%=Html.RenderPartial(\"_ColorList.ascx\", new ViewDataDictionary(ViewData.Model.Colors));%>\n <%=Html.RenderPartial(\"_ColorList.ascx\", new ViewDataDictionary(new { Colors = ViewData.Model.Colors }));%>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
229,357
|
<p>What is the best way in <strong>Perl</strong> to copy files to a yet-to-be-created destination directory tree?</p>
<p>Something like</p>
<pre><code>copy("test.txt","tardir/dest1/dest2/text.txt");
</code></pre>
<p>won't work since the directory <em>tardir/dest1/dest2</em> does not yet exist. What is the best way to copy with directory creation in Perl?</p>
|
[
{
"answer_id": 229382,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 3,
"selected": false,
"text": "use File::Basename qw/dirname/;\nuse File::Copy;\n\nsub mkdir_recursive {\n my $path = shift;\n mkdir_recursive(dirname($path)) if not -d dirname($path);\n mkdir $path or die \"Could not make dir $path: $!\" if not -d $path;\n return;\n}\n\nsub mkdir_and_copy {\n my ($from, $to) = @_;\n mkdir_recursive(dirname($to));\n copy($from, $to) or die \"Couldn't copy: $!\";\n return;\n}\n"
},
{
"answer_id": 229402,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 6,
"selected": true,
"text": "use File::Path;\nuse File::Copy;\n\nmy $path = \"tardir/dest1/dest2/\";\nmy $file = \"test.txt\";\n\nif (! -d $path)\n{\n my $dirs = eval { mkpath($path) };\n die \"Failed to create $path: $@\\n\" unless $dirs;\n}\n\ncopy($file,$path) or die \"Failed to copy $file: $!\\n\";\n"
},
{
"answer_id": 232812,
"author": "EvdB",
"author_id": 5349,
"author_profile": "https://Stackoverflow.com/users/5349",
"pm_score": 1,
"selected": false,
"text": "use Path::Class;\n\nmy $destination_file = file('tardir/dest1/dest2/test.txt');\n$destination_file->dir->mkpath;\n\n# ... do the copying here\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6511/"
] |
229,362
|
<p>I am trying to call out to a legacy dll compiled from FORTRAN code. I am new to Interop, but I've read some articles on it and it seems like my case should be fairly straightforward. </p>
<p>The method I really want to call has a complex method signature, but I can't even call this simple GetVersion method without getting a protected memory violation.</p>
<p>Here's my DllImport code:</p>
<pre><code>[DllImport("GeoConvert.dll",
EntryPoint="_get_version@4",
CallingConvention=CallingConvention.StdCall)]
public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPStr, SizeConst=8)]
ref string version);
</code></pre>
<p>Here's the FORTRAN code:</p>
<pre><code>SUBROUTINE GetVer( VRSION )
C
!MS$DEFINE MSDLL
!MS$IF DEFINED (MSDLL)
ENTRY Get_Version (VRSION)
!MS$ATTRIBUTES DLLEXPORT,STDCALL :: Get_Version
!MS$ATTRIBUTES REFERENCE :: VRSION
!MS$ENDIF
!MS$UNDEFINE MSDLL
C
CHARACTER*8 VRSION
C
VRSION = '1.0a_FhC'
C
RETURN
END
</code></pre>
<p>Here's my unit test that fails:</p>
<pre><code>[Test]
public void TestGetVersion()
{
string version = "";
LatLonUtils.GetGeoConvertVersion(ref version);
StringAssert.IsNonEmpty(version);
}
</code></pre>
<p>Here's the error message I get:</p>
<pre><code>System.AccessViolationException
Message: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
</code></pre>
<p>Other things I've tried:</p>
<ul>
<li>Using the default marshalling</li>
<li>Passing a char[] instead of a string (get method signature errors instead)</li>
</ul>
|
[
{
"answer_id": 229525,
"author": "brien",
"author_id": 4219,
"author_profile": "https://Stackoverflow.com/users/4219",
"pm_score": 2,
"selected": true,
"text": "[DllImport(\"GeoConvert.dll\", \n EntryPoint=\"_get_version@4\", \n CallingConvention=CallingConvention.StdCall)]\n public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPArray)]\n byte[] version);\n [Test]\n public void TestGetVersion()\n {\n //string version = \"\";\n byte[] version = new byte[8];\n LatLonUtils.GetGeoConvertVersion(version);\n char[] versionChars = System.Text.Encoding.ASCII.GetChars(version);\n\n string versionString = new string(versionChars);\n }\n"
},
{
"answer_id": 229873,
"author": "Jeremy",
"author_id": 19174,
"author_profile": "https://Stackoverflow.com/users/19174",
"pm_score": 0,
"selected": false,
"text": " [DllImport(\"GeoConvert.dll\", \n EntryPoint=\"_get_version@4\", \n CallingConvention=CallingConvention.StdCall,\n CharSet=CharSet.Ansi)]\n public static extern void GetGeoConvertVersion(StringBuilder version);\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4219/"
] |
229,385
|
<p>Visual Studio gives many navigation hotkeys:
<kbd>F8</kbd> for next item in current panel (search results, errors ...),
<kbd>Control</kbd>+<kbd>K</kbd>, <kbd>N</kbd> for bookmarks,
<kbd>Alt</kbd>+<kbd>-</kbd> for going back and more.</p>
<p>There is one hotkey that I can't find, and I can't even find the menu-command for it, so I can't create the hotkey myself.</p>
<p>I don't know if such exist: Previous and Next call-stack frame.</p>
<p>I try not using the mouse when programming, but when I need to go back the stack, I must use it to double click the previous frame.</p>
<p>Anyone? How about a macro that does it?</p>
|
[
{
"answer_id": 1211782,
"author": "Oleg Svechkarenko",
"author_id": 148405,
"author_profile": "https://Stackoverflow.com/users/148405",
"pm_score": 4,
"selected": false,
"text": "PreviousStackFrame NextStackFrame Function StackFrameIndex(ByRef aFrames As EnvDTE.StackFrames, ByRef aFrame As EnvDTE.StackFrame) As Long\n For StackFrameIndex = 1 To aFrames.Count\n If aFrames.Item(StackFrameIndex) Is aFrame Then Exit Function\n Next\n StackFrameIndex = -1\nEnd Function\n\nSub NavigateStack(ByVal aShift As Long)\n If DTE.Debugger.CurrentProgram Is Nothing Then\n DTE.StatusBar.Text = \"No program is currently being debugged.\"\n Exit Sub\n End If\n\n Dim ind As Long = StackFrameIndex(DTE.Debugger.CurrentThread.StackFrames, DTE.Debugger.CurrentStackFrame)\n If ind = -1 Then\n DTE.StatusBar.Text = \"Stack navigation failed\"\n Exit Sub\n End If\n\n ind = ind + aShift\n If ind <= 0 Or ind > DTE.Debugger.CurrentThread.StackFrames.Count Then\n DTE.StatusBar.Text = \"Stack frame index is out of range\"\n Exit Sub\n End If\n\n DTE.Debugger.CurrentStackFrame = DTE.Debugger.CurrentThread.StackFrames.Item(ind)\n DTE.StatusBar.Text = \"Stack frame index: \" & ind & \" of \" & DTE.Debugger.CurrentThread.StackFrames.Count\nEnd Sub\n\nSub PreviousStackFrame()\n NavigateStack(1)\nEnd Sub\n\nSub NextStackFrame()\n NavigateStack(-1)\nEnd Sub\n"
},
{
"answer_id": 26718512,
"author": "Programmer Paul",
"author_id": 2482416,
"author_profile": "https://Stackoverflow.com/users/2482416",
"pm_score": 2,
"selected": false,
"text": "^1::SendInput !^c{down}{enter}\n^2::SendInput !^c{up}{enter}\n"
},
{
"answer_id": 51183643,
"author": "Mills",
"author_id": 1088467,
"author_profile": "https://Stackoverflow.com/users/1088467",
"pm_score": 1,
"selected": false,
"text": "MoveStackIndex() using EnvDTE;\nusing EnvDTE80;\nusing System;\n\npublic class C : VisualCommanderExt.ICommand\n{\n enum MoveDirection\n {\n Up,\n Down,\n }\n\n private bool IsValidFrame(StackFrame frame)\n {\n string language = frame.Language;\n\n bool result = (language == \"C#\" || \n language == \"C++\" || \n language == \"VB\" || \n language == \"Python\");\n\n return result;\n }\n\n private void MoveStackIndex(EnvDTE80.DTE2 DTE, MoveDirection direction)\n {\n StackFrame currentFrame = DTE.Debugger.CurrentStackFrame;\n\n bool foundTarget = false;\n bool pastCurrent = false;\n\n StackFrame lastValid = null;\n foreach (StackFrame frame in DTE.Debugger.CurrentThread.StackFrames)\n {\n bool isCurrent = frame == currentFrame;\n\n if (direction == MoveDirection.Down)\n {\n if (isCurrent)\n {\n if (lastValid == null)\n {\n // No valid frames below this one\n break;\n }\n else\n {\n DTE.Debugger.CurrentStackFrame = lastValid;\n foundTarget = true;\n break; \n }\n }\n else\n {\n if (IsValidFrame(frame))\n {\n lastValid = frame;\n }\n }\n }\n\n if (direction == MoveDirection.Up && pastCurrent)\n {\n if (IsValidFrame(frame))\n {\n DTE.Debugger.CurrentStackFrame = frame;\n foundTarget = true;\n break;\n } \n }\n\n if (isCurrent)\n {\n pastCurrent = true;\n }\n }\n\n if (!foundTarget)\n {\n DTE.StatusBar.Text = \"Failed to find valid stack frame in that direction.\";\n }\n }\n\n public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) \n {\n if (DTE.Debugger.CurrentProgram == null)\n {\n DTE.StatusBar.Text = \"Debug session not active.\";\n }\n else\n {\n // NOTE: Change param 2 to MoveDirection.Up for the up command\n MoveStackIndex(DTE, MoveDirection.Down);\n }\n }\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
229,395
|
<p>I have an array of 1000 strings to load into a combo box. What is the fastest way to load the array of strings into the combo box?</p>
<p>Is there some way other than iterating over the list of strings, putting each string into the combo box one at a time?</p>
<p>And how to copy the combo box data once loaded to some 10 other combo boxes?</p>
|
[
{
"answer_id": 229490,
"author": "Hapkido",
"author_id": 27646,
"author_profile": "https://Stackoverflow.com/users/27646",
"pm_score": 0,
"selected": false,
"text": "#define NB_ITEM 1000\n#define ITEM_LENGTH 10\n\nvoid CMFCComboDlg::InitMyCombo()\n{\n CString _strData;\n m_cbMyCombo.SetRedraw( FALSE );\n\n m_cbMyCombo.Clear();\n\n m_cbMyCombo.InitStorage(NB_ITEM, ITEM_LENGTH); \n\n for( int i = 0; i < NB_ITEM; i++ )\n {\n _strData.Format( L\"Test %ld\", i );\n m_cbMyCombo.InsertString( i, _strData );\n }\n\n m_cbMyCombo.SetCurSel(0);\n\n m_cbMyCombo.SetRedraw( TRUE );\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
229,404
|
<p>I am trying to extract a table of values from an excel (2003) spreadsheet using vb6, the result of which needs to be stored in a (adodb) recordset. The table looks like this:</p>
<pre>
Name Option.1 Option.2 Option.3 Option.4 Option.5 Option.6
-----------------------------------------------------------------
Name1 2 3 4
Name2 2 3 4
Name3 2 3 4
Name4 2 3 4
Name5 2 3 4
Name6 2 3 4
Name7 2 3 4
Name8 2 3 4
Name9 2 3 4 5 6 7
</pre>
<p>Upon connecting and executing the query "<code>SELECT * FROM [Sheet1$]</code>" or even a column-specific, "<code>SELECT [Option#6] FROM [Sheet1$]</code>" (see footnote 1) and looping through the results, I am given <code>Null</code> values for the row <code>Name9</code>, <code>Option.4</code> --> <code>Option.6</code> rather than the correct values 5, 6, and 7. It seems the connection to the spreadsheet is using a "best guess" of deciding what the valid table limits are, and only takes a set number of rows into account. </p>
<p>To connect to the spreadsheet, I have tried both connection providers <code>Microsoft.Jet.OLEDB.4.0</code> and <code>MSDASQL</code> and get the same problem.</p>
<p>Here are the connection settings I use:</p>
<pre><code>Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & filePath & ";Extended Properties=Excel 8.0;"
- - - - OR - - - -
.Provider = "MSDASQL"
.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};" & _
"DBQ=" & filePath & ";MaxScanRows=0;"
.CursorLocation = adUseClient
.Open
End With
Set rsSelects = New ADODB.Recordset
Set rsSelects = cn.Execute("SELECT [Option#5] FROM " & "[" & strTbl & "]")
</code></pre>
<p>This problem only occurs when there are more than 8 rows (excluding the column names), and I have set <code>MaxScanRow=0</code> for the <code>MSDASQL</code> connection, but this has produced the same results.</p>
<p>Notable project references I have included are: </p>
<ul>
<li>MS ActiveX Data Objects 2.8 Library</li>
<li>MS ActiveX Data Objects Recordset 2.8 Library</li>
<li>MS Excel 11.0 Object Library</li>
<li>MS Data Binding Collection VB 6.0 (SP4)</li>
</ul>
<p>Any help in this matter would be very appreciated!</p>
<p>(1) For some reason, when including a decimal point in the column name, it is interpreted as a #.</p>
<hr>
<p>Thanks everyone! Halfway through trying to set up a <code>Schema.ini</code> "programmatically" from <a href="http://support.microsoft.com/kb/155512" rel="nofollow noreferrer">KB155512</a> <a href="https://stackoverflow.com/questions/229404/ignored-columns-using-vb6-to-extract-from-excel#229721">onedaywhen</a>'s excellent <a href="http://www.dailydoseofexcel.com/archives/2004/06/03/external-data-mixed-data-types/" rel="nofollow noreferrer">post</a> pointed me towards the solution:</p>
<pre><code>.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & filePath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
</code></pre>
<p>I would encourage anyone with similar problems to read the post and comments, since there are slight variations to a solution from one person to another.</p>
|
[
{
"answer_id": 229477,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "MaxScanRows=0"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30757/"
] |
229,423
|
<p>We have a need to take dozens of different protocols from systems such as security systems, fire alarms, camera systems etc.. and integrate them into a single common protocol.</p>
<p>I would like this to be a messaging server that many systems could subscribe to and or communicate through.</p>
<ul>
<li>polling and non-polling "drivers" (protocol converters)</li>
<li>handle RS232 / RS485 / tcp</li>
<li>programmable "drivers" in a managed language like Java or C#</li>
<li>rules engine capability</li>
</ul>
<p>Does biztalk fit this? </p>
<p>Are there open source alternatives?</p>
<p>Is there a Java / Java EE way to do this?</p>
<p>At one end the system would be a SCADA system at the other is is kind of a middleware / messaging server.</p>
<p>Any thoughts on the best way to proceed would be appreciated. I know that there will be a considerable amount of programming involved on the driver side, however as tempted as I am, building the whole system from scratch would not be appropriate.</p>
|
[
{
"answer_id": 229793,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 3,
"selected": true,
"text": "// route all messages from foo\n// to a single queue on JMS\nfrom(\"foo://somehost:1234\").\n to(\"jms:MyQueue\");\n\n// route all messages from foo component\n// to a queue using a header\nfrom(\"foo://somehost:1234\").\n recipientList().\n simple(\"activemq:MyPrefix.${headers.cheese}\");\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
229,425
|
<p>I'm trying to populate a DataTable, to build a LocalReport, using the following:<br></p>
<pre><code>MySqlCommand cmd = new MySqlCommand();
cmd.Connection = new MySqlConnection(Properties.Settings.Default.dbConnectionString);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ... LEFT JOIN ... WHERE ..."; /* query snipped */
// prepare data
dataTable.Clear();
cn.Open();
// fill datatable
dt.Load(cmd.ExecuteReader());
// fill report
rds = new ReportDataSource("InvoicesDataSet_InvoiceTable",dt);
reportViewerLocal.LocalReport.DataSources.Clear();
reportViewerLocal.LocalReport.DataSources.Add(rds);
</code></pre>
<p>At one point I noticed that the report was incomplete and it was missing one record. I've changed a few conditions so that the query would return exactly two rows and... <b>surprise</b>: The report shows only one row instead of two. I've tried to debug it to find where the problem is and I got stuck at</p>
<pre><code> dt.Load(cmd.ExecuteReader());
</code></pre>
<p>When I've noticed that the <code>DataReader</code> contains two records but the <code>DataTable</code> contains only one. By accident, I've added an <code>ORDER BY</code> clause to the query and noticed that this time the report showed correctly.<br><br>
Apparently, the DataReader contains two rows but the DataTable only reads both of them if the SQL query string contains an <code>ORDER BY</code> (otherwise it only reads the last one). Can anyone explain why this is happening and how it can be fixed?</p>
<p><b>Edit:</b>
When I first posted the question, I said it was skipping the first row; later I realized that it actually only read the last row and I've edited the text accordingly (at that time all the records were grouped in two rows and it appeared to skip the first when it actually only showed the last). This may be caused by the fact that it didn't have a unique identifier by which to distinguish between the rows returned by MySQL so adding the <code>ORDER BY</code> statement caused it to create a unique identifier for each row.<br />
This is just a theory and I have nothing to support it, but all my tests seem to lead to the same result.</p>
|
[
{
"answer_id": 241423,
"author": "thismat",
"author_id": 14045,
"author_profile": "https://Stackoverflow.com/users/14045",
"pm_score": 0,
"selected": false,
"text": " Dim deals As New DealsProvider()\n Dim adapter As New ReportingDataTableAdapters.ReportDealsAdapter\n Dim report As ReportingData.ReportDealsDataTable = deals.GetActiveDealsReport()\n rptReports.LocalReport.DataSources.Add(New ReportDataSource(\"ActiveDeals_Data\", report))\n"
},
{
"answer_id": 243563,
"author": "Brian",
"author_id": 17356,
"author_profile": "https://Stackoverflow.com/users/17356",
"pm_score": 0,
"selected": false,
"text": "dt.AcceptChanges() dt.Load(cmd.ExecuteReader())"
},
{
"answer_id": 4640518,
"author": "tant",
"author_id": 568956,
"author_profile": "https://Stackoverflow.com/users/568956",
"pm_score": 3,
"selected": false,
"text": "DataReader.Read DataReader.HasRows dt.load(DataReader)"
},
{
"answer_id": 9210238,
"author": "Majnu",
"author_id": 1016144,
"author_profile": "https://Stackoverflow.com/users/1016144",
"pm_score": 4,
"selected": false,
"text": "DataTable.Load"
},
{
"answer_id": 20471735,
"author": "James",
"author_id": 2865852,
"author_profile": "https://Stackoverflow.com/users/2865852",
"pm_score": 3,
"selected": false,
"text": "dr.Read()\n"
},
{
"answer_id": 22664787,
"author": "waka",
"author_id": 2099119,
"author_profile": "https://Stackoverflow.com/users/2099119",
"pm_score": 0,
"selected": false,
"text": "PrimaryKey SELECT a\n , b\nFROM table\n SELECT a as gurgleurp\n , b\nFROM table\n"
},
{
"answer_id": 23083491,
"author": "Jamie Hartnoll",
"author_id": 956482,
"author_profile": "https://Stackoverflow.com/users/956482",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM (\n SELECT ..... < YOUR NORMAL SQL STATEMENT HERE />\n) allrecords\n"
},
{
"answer_id": 36909763,
"author": "ullevi83",
"author_id": 1712112,
"author_profile": "https://Stackoverflow.com/users/1712112",
"pm_score": 1,
"selected": false,
"text": " if(dataset.read()) - Misses a row.\n\n if(dataset.hasrows) - Missing row appears.\n"
},
{
"answer_id": 73047332,
"author": "mohammadAli",
"author_id": 9826453,
"author_profile": "https://Stackoverflow.com/users/9826453",
"pm_score": 0,
"selected": false,
"text": "select uniqueData,.....\nfrom mytable\ngroup by uniqueData;\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26155/"
] |
229,432
|
<p>Is there a way of programmatically determining a rough geographical position of a mobile phone using J2ME application, for example determining the current cell? This question especially applies to non-GPS enabled devices. </p>
<p>I am not looking for a set of geographical coordinates, but an ability for a user to define location specific software behaviours.</p>
<p>Solution for any hardware will be highly appreciated; however the more generic a solution is — the better. Many thanks!</p>
|
[
{
"answer_id": 250008,
"author": "user32691",
"author_id": 32691,
"author_profile": "https://Stackoverflow.com/users/32691",
"pm_score": 3,
"selected": false,
"text": "System.getProperty(String arg) try{\n String[] cellIDTags = {\"com.sonyericsson.net.cellid\", \"phone.cid\", \"Siemens.CID\", \"CellID\"};\n for(int i = 0; i < cellIDTags.length; i++){\n cellID = System.getProperty(cellIDTags[i]);\n if(cellID != null && cellID != \"\"){\n location.setCellId(cellID);\n break;\n }\n }\n}catch(Exception e){\n cellID = \"\";\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22088/"
] |
229,438
|
<p>I am just embarking on my first large-scale refactor, and need to split an (unfortunately large) class into two, which then communicate only via an interface. (My Presenter has turned out to be a Controller, and needs to split GUI logic from App logic). Using C# in VisualStudio 2008 and Resharper, what is the easiest way to achieve this? </p>
<p>What I am going to try is
a) Collect the members for the new class and "extract new class"
b) clean up the resulting mess
c) "Extract Interface"
d) chase down any references to the class and convert them to interface references</p>
<p>but I have never done this before, and wonder whether anyone knows any good tips or gotchas before I start ripping everything apart...
Thanks!</p>
|
[
{
"answer_id": 229634,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 0,
"selected": false,
"text": "class PresenterAndController\n {\n public void Control()\n {\n Present();\n }\n\n public void Present()\n {\n // present something\n }\n }\n internal class Presenter\n {\n public void Present()\n {\n // present something\n }\n }\n\n class PresenterAndController : Presenter\n {\n public void Control()\n {\n Present();\n }\n }\n internal class Presenter\n {\n public void Present()\n {\n // present something\n }\n }\n\n class PresenterAndController : Presenter\n {\n private Presenter myPresenter;\n\n public void Present() // hides base method\n {\n myPresenter.Present();\n }\n\n public void Control()\n {\n Present(); // it now references method from this type\n }\n }\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091/"
] |
229,441
|
<p>in my application (c# 3.5) there are various processes accessing a single xml file (read and write) very frequently. the code accessing the file is placed in an assembly referenced by quite a couple of other applications. for example a windows service might instanciate the MyFileReaderWriter class (locatied in the previously mentioned assembly) and use the read/write methods of this class. </p>
<p>i'm looking for the best/fastest way to read and create/append the file with the least amount of locking. caching the files data and flushing new content periodically is not an option, since the data is critical.</p>
<p>I forgot to mention that I currently use the XDocument (LInq2Xml infrastructure) for reading/writing the content to the file.</p>
|
[
{
"answer_id": 229476,
"author": "biozinc",
"author_id": 30698,
"author_profile": "https://Stackoverflow.com/users/30698",
"pm_score": 1,
"selected": false,
"text": "public static object GetReadWriteToken(String fileName)\n{\n //use a hashtable to retreive an object, with filename as key\n return token;\n}\n lock(GetReadWriteToken(@\"C:\\important.xml\"))\n{\n //io code\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
] |
229,443
|
<p>I've made a custom DataGridViewCell that displays a custom control instead of the cell; but if the DataGridView uses shared rows, then the custom control instance is also shared, so you get strange behaviour (for example, hovering over buttons highlights all the buttons). Also, I can't access the DataGridViewCell.Selected property, so I don't know what colour to paint the row.</p>
<p>How do I prevent a DataGridView from sharing rows? I know I can add the rows using the Rows.Add(object[]) override, but then the first row is still shared (i.e. has index -1) so the problem with colours still applies.</p>
<p>I need to be able to tell the DataGridView not to share a row containing a custom cell. Can that be done with attributes? Can it be done at all?</p>
|
[
{
"answer_id": 1820040,
"author": "Ptr",
"author_id": 221369,
"author_profile": "https://Stackoverflow.com/users/221369",
"pm_score": 1,
"selected": false,
"text": "DataGridViewRowCollection.AddRange(params DataGridViewRow[] dataGridViewRows)\n new[]{someDataGridviewRow}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
229,446
|
<p>On our site, we get a large amount of photos uploaded from various sources. </p>
<p>In order to keep the file sizes down, we strip all <a href="http://en.wikipedia.org/wiki/Exif" rel="noreferrer">exif data</a> from the source using <a href="http://www.imagemagick.org/www/mogrify.html" rel="noreferrer">mogrify</a>:</p>
<pre><code>mogrify -strip image.jpg
</code></pre>
<p>What we'd like to be able to do is to insert some basic exif data (Copyright Initrode, etc) back onto this new "clean" image, but I can't seem to find anything in the docs that would achieve this.</p>
<p>Has anybody any experience of doing this? </p>
<p>If it can't be done through imagemagick, a PHP-based solution would be the next best thing!</p>
<p>Thanks.</p>
|
[
{
"answer_id": 230480,
"author": "Ciaran",
"author_id": 5048,
"author_profile": "https://Stackoverflow.com/users/5048",
"pm_score": 5,
"selected": true,
"text": "2#110#Credit=\"My Company\"\n2#05#Object Name=\"THE_OBJECT_NAME\"\n2#55#Date Created=\"2011-02-03 12:45\"\n2#80#By-line=\"BY-LINE?\"\n2#110#Credit=\"The CREDIT\"\n2#115#Source=\"SOURCE\"\n2#116#Copyright Notice=\"THE COPYRIGHT\"\n2#118#Contact=\"THE CONTACT\"\n2#120#Caption=\"AKA Title\"\n mogrify -strip image.jpg\n mogrify -profile 8BIMTEXT:text.txt image.jpg\n"
},
{
"answer_id": 46179681,
"author": "Andreas Bergström",
"author_id": 1202214,
"author_profile": "https://Stackoverflow.com/users/1202214",
"pm_score": 1,
"selected": false,
"text": "// Load image data\n$data = new PelDataWindow(file_get_contents('IMAGE PATH'));\n\n// Prepare image data\n$jpeg = $file = new PelJpeg();\n$jpeg->load($data);\n\n// Create new EXIF-headers, overwriting any existing ones (when writing to disk)\n$exif = new PelExif();\n$jpeg->setExif($exif);\n$tiff = new PelTiff();\n$exif->setTiff($tiff);\n\n// Create Ifd-data that will hold EXIF-tags\n$ifd0 = new PelIfd(PelIfd::IFD0);\n$tiff->setIfd($ifd0);\n\n// Create EXIF-data for copyright\n$make = new PelEntryAscii(PelTag::COPYRIGHT, '2008-2017 Conroy');\n$ifd0->addEntry($make);\n\n// Add more EXIF-data...\n\n// Save to disk\n$file->saveFile('IMAGE.jpg');\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287/"
] |
229,447
|
<p>How can I efficiently create a unique index on two fields in a table like this:
create table t (a integer, b integer);</p>
<p>where any unique combination of two different numbers cannot appear more than once on the same row in the table.</p>
<p>In order words if a row exists such that a=1 and b=2, another row cannot exist where a=2 and b=1 or a=1 and b=2. In other words two numbers cannot appear together more than once in any order.</p>
<p>I have no idea what such a constraint is called, hence the 'two-sided unique index' name in the title.</p>
<p><strong>Update</strong>: If I have a composite key on columns (a,b), and a row (1,2) exists in the database, it is possible to insert another row (2,1) without an error. What I'm looking for is a way to prevent the same pair of numbers from being used more than once <strong><em>in any order</em></strong>...</p>
|
[
{
"answer_id": 229521,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "BEFORE UPDATE CREATE TRIGGER tr_CheckDuplicates_insert\nBEFORE INSERT ON t\nFOR EACH ROW\nBEGIN\n DECLARE rowCount INT;\n SELECT COUNT(*) INTO rowCount\n FROM t\n WHERE a = NEW.b AND b = NEW.a;\n\n IF rowCount > 0 THEN\n -- Oops, we need a temporary variable here. Oh well.\n -- Switch the values so that the key will cause the insert to fail.\n SET rowCount = NEW.a, NEW.a = NEW.b, NEW.b = rowCount;\n END IF;\nEND;\n"
},
{
"answer_id": 229527,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "create unique index mytab_idx on mytab (least(a,b), greatest(a,b));\n"
},
{
"answer_id": 229803,
"author": "neonski",
"author_id": 17112,
"author_profile": "https://Stackoverflow.com/users/17112",
"pm_score": 4,
"selected": true,
"text": "COLUMN A : 2\nCOLUMN B : 1\n\nCOLUMN A_PK : 1 ( if new.a < new.b then new.a else new.b )\nCOLUMN B_PK : 2 ( if new.b > new.a then new.b else new.a )\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6475/"
] |
229,468
|
<p>I am new to programming, and am wondering if there is a correct way to order your control structure logic.</p>
<p>It seems more natural to check for the most likely case first, but I have the feeling that some control structures won't work unless they check everything that's false to arrive at something that's true (logical deduction?)</p>
<p>It would be hard to adapt to this 'negative' view, I prefer a more positive outlook, presuming everything is true :)</p>
|
[
{
"answer_id": 229493,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 3,
"selected": false,
"text": "if( condition is true ) {\n do something small;\n} else { \n do something;\n and something else; \n . . .\n and the 20th something;\n}\n if( variable is defined ) {\n if( variable == value ) {\n ...\n }\n}\n if( (variable is defined) && (variable == value) ) {\n ...\n}\n"
},
{
"answer_id": 229714,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "if (condition) {\n smallBlock();\n} else {\n bigBlockStart();\n ........\n bigBlockEnd();\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
229,491
|
<pre><code>foreach($arrayOne as $value){
do function
}
</code></pre>
<p>In the above example, I'd like to pass $arrayOne into a loop, have a function operate that removes some elements of $arrayOne and then have the loop pass over the reduced $arrayOne on the elements that are left until the loop returns false.</p>
<p>Recommendations?</p>
|
[
{
"answer_id": 229799,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "$arrayOne = array('example', 'listing of', 'stuff');\n\nforeach ($arrayOne as $key => &$value) {\n $value .= ' alteration';\n\n if ($value == 'listing of alteration') {\n unset($arrayOne[ $key ]);\n }\n\n}\n"
},
{
"answer_id": 230132,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "foreach ($array AS $key => &$value) {\n //& reference only needed if execFunction must edit $value\n if (execFunction(&$value)) { \n unset($array[$key]);\n } else {\n $value['exec_failed']+=1;\n }\n}\nunset($value);\n"
},
{
"answer_id": 230607,
"author": "kevtrout",
"author_id": 1149,
"author_profile": "https://Stackoverflow.com/users/1149",
"pm_score": 0,
"selected": false,
"text": "//array to be processed\n$one=array('1','2','3');\n//array of terms previously defined as a group to compare against\n$against=array('1','2');\n\nforeach($one as $key=>$value){\n\n //pull out matching terms \n $match=array_intersect($one,$against);\n //my need is to sum grouped numbers\n $sum=array_sum($match);\n echo $sum.\"<br />\";\n\n //remove matching terms from original array\n foreach($match as $key=>$value){\n unset($one[$key]);\n }\n}\n//now a parent looping function will process the remaining array elements. In this case, the only one left is '3'.\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149/"
] |
229,508
|
<p>Can anyone tell me why this code behaves the way it does? See comments embedded in the code...</p>
<p>Am I missing something really obvious here?</p>
<pre><code>using System;
namespace ConsoleApplication3
{
public class Program
{
static void Main(string[] args)
{
var c = new MyChild();
c.X();
Console.ReadLine();
}
}
public class MyParent
{
public virtual void X()
{
Console.WriteLine("Executing MyParent");
}
}
delegate void MyDelegate();
public class MyChild : MyParent
{
public override void X()
{
Console.WriteLine("Executing MyChild");
MyDelegate md = base.X;
// The following two calls look like they should behave the same,
// but they behave differently!
// Why does Invoke() call the base class as expected here...
md.Invoke();
// ... and yet BeginInvoke() performs a recursive call within
// this child class and not call the base class?
md.BeginInvoke(CallBack, null);
}
public void CallBack(IAsyncResult iAsyncResult)
{
return;
}
}
}
</code></pre>
|
[
{
"answer_id": 229537,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "using System;\n\ndelegate void MyDelegate();\n\npublic class Program\n{\n static void Main(string[] args)\n {\n var c = new MyChild();\n c.DisplayOddity();\n Console.ReadLine();\n }\n}\n\npublic class MyParent\n{\n public virtual void X()\n {\n Console.WriteLine(\"Executing MyParent.X\");\n }\n}\n\npublic class MyChild : MyParent\n{\n public void DisplayOddity()\n {\n MyDelegate md = base.X;\n\n Console.WriteLine(\"Calling Invoke()\");\n md.Invoke(); // Executes base method... fair enough\n\n Console.WriteLine(\"Calling BeginInvoke()\");\n md.BeginInvoke(null, null); // Executes overridden method!\n }\n\n public override void X()\n {\n Console.WriteLine(\"Executing MyChild.X\");\n }\n}\n Calling Invoke()\nExecuting MyParent.X\nCalling BeginInvoke()\nExecuting MyChild.X\n"
},
{
"answer_id": 230049,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "ThreadPool.QueueUserWorkItem(x => md());\n new Thread(() => md()).Start();\n"
},
{
"answer_id": 255360,
"author": "foson",
"author_id": 22539,
"author_profile": "https://Stackoverflow.com/users/22539",
"pm_score": 1,
"selected": false,
"text": "\n\n public class Program\n {\n static void Main(string[] args)\n {\n MyChild a = new MyChild();\n MyDelegate ma = new MyDelegate(a.X);\n\n MyParent b = new MyChild();\n MyDelegate mb = new MyDelegate(b.X);\n\n ma.Invoke();\n mb.Invoke();\n ma.BeginInvoke(CallBack, null);\n mb.BeginInvoke(CallBack, null); //all four calls call derived MyChild.X\n\n Console.ReadLine();\n }\n\n public static void CallBack(IAsyncResult iAsyncResult)\n {\n return;\n }\n }\n\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24207/"
] |
229,534
|
<p>I have to migrate a table from MSSQL Server to MySql. The problem is that the table is quite big (65 millions records) and the whole process takes too much time. Does anyone have any idea how to speed things up ? Any useful tools that could improve this?</p>
|
[
{
"answer_id": 229570,
"author": "SWD",
"author_id": 3034,
"author_profile": "https://Stackoverflow.com/users/3034",
"pm_score": 1,
"selected": true,
"text": "'/somefolder/text_file_with_data.txt' '\\t' '\\n' '/somefolder_on_the_mysql_server/text_file_with_data.txt' '\\t' '\\n'"
},
{
"answer_id": 230760,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 0,
"selected": false,
"text": "innodb_data_file_path=ibdata1:1000M:autoextend\n"
},
{
"answer_id": 1215182,
"author": "Costo",
"author_id": 1130,
"author_profile": "https://Stackoverflow.com/users/1130",
"pm_score": 1,
"selected": false,
"text": "SELECT [PostalCode] + ' ' +\n [StateCode] + ' ' +\n [Latitude] + ' ' +\n [Longitude] + ' ' +\n [CityName] \nFROM [dbo].[PostalCode]\n mysqlimport.exe --user=user_name\n --columns=postalcode,statecode,latitude,longitude,cityname \n --ignore-lines=2 databaseName pathToFile\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29891/"
] |
229,551
|
<p>I have a string in Bash:</p>
<pre class="lang-sh prettyprint-override"><code>string="My string"
</code></pre>
<p>How can I test if it contains another string?</p>
<pre class="lang-sh prettyprint-override"><code>if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
</code></pre>
<p>Where <code>??</code> is my unknown operator. Do I use <code>echo</code> and <code>grep</code>?</p>
<pre class="lang-sh prettyprint-override"><code>if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
</code></pre>
<p>That looks a bit clumsy.</p>
|
[
{
"answer_id": 229585,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 9,
"selected": false,
"text": "case \"$string\" in \n *foo*)\n # Do stuff\n ;;\nesac\n"
},
{
"answer_id": 229606,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 13,
"selected": true,
"text": "string='My long string'\nif [[ $string == *\"My long\"* ]]; then\n echo \"It's there!\"\nfi\n * == =~"
},
{
"answer_id": 229993,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 7,
"selected": false,
"text": "if [ \"$string\" != \"${string/foo/}\" ]; then\n echo \"It's there!\"\nfi\n ${var/search/replace} $var search replace $var foo foo"
},
{
"answer_id": 231298,
"author": "Matt Tardiff",
"author_id": 27925,
"author_profile": "https://Stackoverflow.com/users/27925",
"pm_score": 10,
"selected": false,
"text": "string='My string';\n\nif [[ $string =~ \"My\" ]]; then\n echo \"It's there!\"\nfi\n"
},
{
"answer_id": 240181,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 7,
"selected": false,
"text": "if [ [[ grep [ if grep -q foo <<<\"$string\"; then\n echo \"It's there\"\nfi\n if ## Instead of this\nfiletype=\"$(file -b \"$1\")\"\nif grep -q \"tar archive\" <<<\"$filetype\"; then\n#...\n\n## Simply do this\nif file -b \"$1\" | grep -q \"tar archive\"; then\n#...\n -q <<< <<"
},
{
"answer_id": 384516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "grep -q awk string=\"unix-bash 2389\"\ncharacter=\"@\"\nprintf '%s' \"$string\" | awk -vc=\"$character\" '{ if (gsub(c, \"\")) { print \"Found\" } else { print \"Not Found\" } }'\n string=\"unix-bash 2389\"\ncharacter=\"-\"\nprintf '%s' \"$string\" | awk -vc=\"$character\" '{ if (gsub(c, \"\")) { print \"Found\" } else { print \"Not Found\" } }'\n"
},
{
"answer_id": 527231,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "text=\" <tag>bmnmn</tag> \"\nif [[ \"$text\" =~ \"<tag>\" ]]; then\n echo \"matched\"\nelse\n echo \"not matched\"\nfi\n"
},
{
"answer_id": 3587443,
"author": "andreas",
"author_id": 432376,
"author_profile": "https://Stackoverflow.com/users/432376",
"pm_score": 2,
"selected": false,
"text": "-base64Decode -base64Encode -capitalize -center -charAt -concat -contains -count -endsWith -equals -equalsIgnoreCase -reverse -hashCode -indexOf -isAlnum -isAlpha -isAscii -isDigit -isEmpty -isHexDigit -isLowerCase -isSpace -isPrintable -isUpperCase -isVisible -lastIndexOf -length -matches -replaceAll -replaceFirst -startsWith -substring -swapCase -toLowerCase -toString -toUpperCase -trim -zfill [Desktop]$ String a testXccc\n[Desktop]$ a.contains tX\ntrue\n[Desktop]$ a.contains XtX\nfalse\n"
},
{
"answer_id": 8090175,
"author": "chemila",
"author_id": 889064,
"author_profile": "https://Stackoverflow.com/users/889064",
"pm_score": 3,
"selected": false,
"text": "[ $(expr $mystring : \".*${search}.*\") -ne 0 ] && echo 'yes' || echo 'no'\n"
},
{
"answer_id": 11281580,
"author": "Kurt Pfeifle",
"author_id": 359307,
"author_profile": "https://Stackoverflow.com/users/359307",
"pm_score": 3,
"selected": false,
"text": ".bashrc function stringinstring()\n{\n case \"$2\" in\n *\"$1\"*)\n return 0\n ;;\n esac\n return 1\n}\n $string1 $string2 stringinstring \"$string1\" \"$string2\" stringinstring \"$str1\" \"$str2\" && echo YES || echo NO\n"
},
{
"answer_id": 13660953,
"author": "kevinarpe",
"author_id": 257299,
"author_profile": "https://Stackoverflow.com/users/257299",
"pm_score": 5,
"selected": false,
"text": "if printf -- '%s' \"$haystack\" | egrep -q -- \"$needle\"\nthen\n printf \"Found needle in haystack\"\nfi\n if ! printf -- '%s' \"$haystack\" | egrep -q -- \"$needle\"\nthen\n echo \"Did not find needle in haystack\"\nfi\n -- --abc -a"
},
{
"answer_id": 18441709,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 4,
"selected": false,
"text": "# For null cmd arguments checking \nto_check=' -t'\nspace_n_dash_chars=' -'\n[[ $to_check == *\"$space_n_dash_chars\"* ]] && echo found\n"
},
{
"answer_id": 20460402,
"author": "F. Hauri - Give Up GitHub",
"author_id": 1765658,
"author_profile": "https://Stackoverflow.com/users/1765658",
"pm_score": 8,
"selected": false,
"text": "stringContain [ -z \"${string##*$reqsubstr*}\" ]\n string='echo \"My string\"'\nfor reqsubstr in 'o \"M' 'alt' 'str';do\n if [ -z \"${string##*$reqsubstr*}\" ] ;then\n echo \"String '$string' contain substring: '$reqsubstr'.\"\n else\n echo \"String '$string' don't contain substring: '$reqsubstr'.\"\n fi\n done\n ksh String 'echo \"My string\"' contain substring: 'o \"M'.\nString 'echo \"My string\"' don't contain substring: 'alt'.\nString 'echo \"My string\"' contain substring: 'str'.\n myfunc() {\n reqsubstr=\"$1\"\n shift\n string=\"$@\"\n if [ -z \"${string##*$reqsubstr*}\" ] ;then\n echo \"String '$string' contain substring: '$reqsubstr'.\";\n else\n echo \"String '$string' don't contain substring: '$reqsubstr'.\"\n fi\n}\n $ myfunc 'o \"M' 'echo \"My String\"'\nString 'echo \"My String\"' contain substring 'o \"M'.\n\n$ myfunc 'alt' 'echo \"My String\"'\nString 'echo \"My String\"' don't contain substring 'alt'.\n $ myfunc 'o \"M' echo \"My String\"\nString 'echo My String' don't contain substring: 'o \"M'.\n\n$ myfunc 'o \"M' echo \\\"My String\\\"\nString 'echo \"My String\"' contain substring: 'o \"M'.\n stringContain() { [ -z \"${2##*$1*}\" ]; }\n $ if stringContain 'o \"M3' 'echo \"My String\"';then echo yes;else echo no;fi\nno\n$ if stringContain 'o \"M' 'echo \"My String\"';then echo yes;else echo no;fi\nyes\n stringContain() { [ -z \"${2##*$1*}\" ] && [ -z \"$1\" -o -n \"$2\" ]; }\n -o stringContain() { [ -z \"${2##*$1*}\" ] && { [ -z \"$1\" ] || [ -n \"$2\" ];};}\n stringContain() { [ -z \"$1\" ] || { [ -z \"${2##*$1*}\" ] && [ -n \"$2\" ];};}\n $ if stringContain '' ''; then echo yes; else echo no; fi\nyes\n$ if stringContain 'o \"M' ''; then echo yes; else echo no; fi\nno\n stringContain() {\n local _lc=${2,,}\n [ -z \"$1\" ] || { [ -z \"${_lc##*${1,,}*}\" ] && [ -n \"$2\" ] ;} ;}\n stringContain 'o \"M3' 'echo \"my string\"' && echo yes || echo no\nno\nstringContain 'o \"My' 'echo \"my string\"' && echo yes || echo no\nyes\nif stringContain '' ''; then echo yes; else echo no; fi\nyes\nif stringContain 'o \"M' ''; then echo yes; else echo no; fi\nno\n"
},
{
"answer_id": 25535717,
"author": "Paul Hedderly",
"author_id": 75528,
"author_profile": "https://Stackoverflow.com/users/75528",
"pm_score": 6,
"selected": false,
"text": "/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do TEST ; x=$(($x-1)); done'\n [[ $b =~ $a ]] 2.92 user 0.06 system 0:02.99 elapsed 99% CPU\n\n[ \"${b/$a//}\" = \"$b\" ] 3.16 user 0.07 system 0:03.25 elapsed 99% CPU\n\n[[ $b == *$a* ]] 1.85 user 0.04 system 0:01.90 elapsed 99% CPU\n\ncase $b in *$a):;;esac 1.80 user 0.02 system 0:01.83 elapsed 99% CPU\n\ndoContain $a $b 4.27 user 0.11 system 0:04.41 elapsed 99%CPU\n echo $b|grep -q $a 12.68 user 30.86 system 3:42.40 elapsed 19% CPU !ouch!\n"
},
{
"answer_id": 27726913,
"author": "Samuel",
"author_id": 1045004,
"author_profile": "https://Stackoverflow.com/users/1045004",
"pm_score": 5,
"selected": false,
"text": "if echo \"abcdefg\" | grep -q \"bcdef\"; then\n echo \"String contains is true.\"\nelse\n echo \"String contains is not true.\"\nfi\n"
},
{
"answer_id": 29928695,
"author": "Jahid",
"author_id": 3744681,
"author_profile": "https://Stackoverflow.com/users/3744681",
"pm_score": 4,
"selected": false,
"text": "[[ $string == *foo* ]] && echo \"It's there\" || echo \"Couldn't find\"\n"
},
{
"answer_id": 35780975,
"author": "ride",
"author_id": 3457750,
"author_profile": "https://Stackoverflow.com/users/3457750",
"pm_score": 3,
"selected": false,
"text": "substr=\"foo\"\nnonsub=\"$(echo \"$string\" | sed \"s/$substr//\")\"\nhassub=0 ; [ \"$string\" != \"$nonsub\" ] && hassub=1\n"
},
{
"answer_id": 40530610,
"author": "Eduardo Cuomo",
"author_id": 717267,
"author_profile": "https://Stackoverflow.com/users/717267",
"pm_score": 2,
"selected": false,
"text": "string='My long string'\nexactSearch='long'\n\nif grep -E -q \"\\b${exactSearch}\\b\" <<<${string} >/dev/null 2>&1\n then\n echo \"It's there\"\n fi\n"
},
{
"answer_id": 41647131,
"author": "Leslie Satenstein",
"author_id": 1445782,
"author_profile": "https://Stackoverflow.com/users/1445782",
"pm_score": 3,
"selected": false,
"text": "bin # .bash_profile\n# Get the aliases and functions\nif [ -f ~/.bashrc ]; then\n . ~/.bashrc\nfi\n\nU=~/.local.bin:~/bin\n\nif ! echo \"$PATH\" | grep -q \"home\"; then\n export PATH=$PATH:${U}\nfi\n"
},
{
"answer_id": 49765399,
"author": "Ethan Post",
"author_id": 4527,
"author_profile": "https://Stackoverflow.com/users/4527",
"pm_score": 2,
"selected": false,
"text": "function str_instr {\n # Return position of ```str``` within ```string```.\n # >>> str_instr \"str\" \"string\"\n # str: String to search for.\n # string: String to search.\n typeset str string x\n # Behavior here is not the same in bash vs ksh unless we escape special characters.\n str=\"$(str_escape_special_characters \"${1}\")\"\n string=\"${2}\"\n x=\"${string%%$str*}\"\n if [[ \"${x}\" != \"${string}\" ]]; then\n echo \"${#x} + 1\" | bc -l\n else\n echo 0\n fi\n}\n\nfunction test_str_instr {\n str_instr \"(\" \"'foo@host (dev,web)'\" | assert_eq 11\n str_instr \")\" \"'foo@host (dev,web)'\" | assert_eq 19\n str_instr \"[\" \"'foo@host [dev,web]'\" | assert_eq 11\n str_instr \"]\" \"'foo@host [dev,web]'\" | assert_eq 19\n str_instr \"a\" \"abc\" | assert_eq 1\n str_instr \"z\" \"abc\" | assert_eq 0\n str_instr \"Eggs\" \"Green Eggs And Ham\" | assert_eq 7\n str_instr \"a\" \"\" | assert_eq 0\n str_instr \"\" \"\" | assert_eq 0\n str_instr \" \" \"Green Eggs\" | assert_eq 6\n str_instr \" \" \" Green \" | assert_eq 1\n}\n"
},
{
"answer_id": 52671757,
"author": "Mike Q",
"author_id": 1618630,
"author_profile": "https://Stackoverflow.com/users/1618630",
"pm_score": 6,
"selected": false,
"text": " if [[ \"${str,,}\" == *\"yes\"* ]] ;then\n if [[ \"$(echo \"$str\" | tr '[:upper:]' '[:lower:]')\" == *\"yes\"* ]] ;then\n if [[ \"${str}\" == *\"yes\"* ]] ;then\n if [[ \"${str}\" =~ \"yes\" ]] ;then\n if [[ \"${str}\" == \"yes\" ]] ;then\n if [[ \"${str,,}\" == \"yes\" ]] ;then\n if [ \"$a\" = \"$b\" ] ;then\n if echo \"$a\" | egrep -iq \"\\.(mp[3-4]|txt|css|jpg|png)\" ; then\n if echo \"SomeString\" | grep -q \"String\"; then\n if echo \"SomeString\" | grep -iq \"string\"; then\n if echo \"SomeString\" | grep -iq \"Some.*ing\"; then\n if [[ ! ${str##*$substr*} ]] ;then #found\n"
},
{
"answer_id": 54490453,
"author": "Alex Skrypnyk",
"author_id": 712666,
"author_profile": "https://Stackoverflow.com/users/712666",
"pm_score": 3,
"selected": false,
"text": "# contains(string, substring)\n#\n# Returns 0 if the specified string contains the specified substring,\n# otherwise returns 1.\ncontains() {\n string=\"$1\"\n substring=\"$2\"\n\n if echo \"$string\" | $(type -p ggrep grep | head -1) -F -- \"$substring\" >/dev/null; then\n return 0 # $substring is in $string\n else\n return 1 # $substring is not in $string\n fi\n}\n\ncontains \"abcd\" \"e\" || echo \"abcd does not contain e\"\ncontains \"abcd\" \"ab\" && echo \"abcd contains ab\"\ncontains \"abcd\" \"bc\" && echo \"abcd contains bc\"\ncontains \"abcd\" \"cd\" && echo \"abcd contains cd\"\ncontains \"abcd\" \"abcd\" && echo \"abcd contains abcd\"\ncontains \"\" \"\" && echo \"empty string contains empty string\"\ncontains \"a\" \"\" && echo \"a contains empty string\"\ncontains \"\" \"a\" || echo \"empty string does not contain a\"\ncontains \"abcd efgh\" \"cd ef\" && echo \"abcd efgh contains cd ef\"\ncontains \"abcd efgh\" \" \" && echo \"abcd efgh contains a space\"\n\ncontains \"abcd [efg] hij\" \"[efg]\" && echo \"abcd [efg] hij contains [efg]\"\ncontains \"abcd [efg] hij\" \"[effg]\" || echo \"abcd [efg] hij does not contain [effg]\"\n\ncontains \"abcd *efg* hij\" \"*efg*\" && echo \"abcd *efg* hij contains *efg*\"\ncontains \"abcd *efg* hij\" \"d *efg* h\" && echo \"abcd *efg* hij contains d *efg* h\"\ncontains \"abcd *efg* hij\" \"*effg*\" || echo \"abcd *efg* hij does not contain *effg*\"\n"
},
{
"answer_id": 59179141,
"author": "FifthAxiom",
"author_id": 8353248,
"author_profile": "https://Stackoverflow.com/users/8353248",
"pm_score": 3,
"selected": false,
"text": "[ ${_string_##*$_substring_*} ] || echo Substring found!\n [ \"${_string_##*$_substring_*}\" ] || echo 'Substring found!'\n ash [ stringvalue ] [ ] * [ -z \"${_string_##*$_substring_*}\" ] && echo 'Substring found!'\n [ -n \"${_string_##*$_substring_*}\" ] || echo 'Substring found!'\n [ \"${_string_##$_substring_}\" != \"$_string_\" ] && echo 'Substring found!'\n [ \"${_string_##$_substring_}\" = \"$_string_\" ] || echo 'Substring found!'\n"
},
{
"answer_id": 60198800,
"author": "BobMonk",
"author_id": 7351088,
"author_profile": "https://Stackoverflow.com/users/7351088",
"pm_score": 0,
"selected": false,
"text": "msg=\"message\"\n\nfunction check {\n echo $msg | egrep [abc] 1> /dev/null\n\n if [ $? -ne 1 ];\n then \n echo \"found\" \n else \n echo \"not found\" \n fi\n}\n\ncheck\n"
},
{
"answer_id": 60720551,
"author": "Pipo",
"author_id": 2118777,
"author_profile": "https://Stackoverflow.com/users/2118777",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\n\nneedle=\"a_needle\"\nhaystack=\"a_needle another_needle a_third_needle\"\nif [[ $haystack == *\"$needle\"* ]]; then\n echo \"needle found\"\nelse\n echo \"needle NOT found\"\nfi\n"
},
{
"answer_id": 60884380,
"author": "Koichi Nakashima",
"author_id": 11267590,
"author_profile": "https://Stackoverflow.com/users/11267590",
"pm_score": 2,
"selected": false,
"text": "case $string in (*foo*)\n # Do stuff\nesac\n"
},
{
"answer_id": 70175482,
"author": "Piotr Henryk Dabrowski",
"author_id": 10245694,
"author_profile": "https://Stackoverflow.com/users/10245694",
"pm_score": 4,
"selected": false,
"text": "haystack='There are needles here.'\nif [[ \"$haystack\" == *\"needle\"* ]]; then\n echo \"It's there!\"\nfi\n"
},
{
"answer_id": 71937360,
"author": "franzisk",
"author_id": 2716142,
"author_profile": "https://Stackoverflow.com/users/2716142",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\n# NO MATCH EXAMPLE\nstring=\"test\"\n[[ \"$string\" == *\"foo\"* ]] && {\n echo \"YES\"\n}\n\n# MATCH EXAMPLE\nstring=\"tefoost\"\n[[ \"$string\" == *\"foo\"* ]] && {\n echo \"YES\"\n}\n"
},
{
"answer_id": 72555962,
"author": "JanB",
"author_id": 16978791,
"author_profile": "https://Stackoverflow.com/users/16978791",
"pm_score": 0,
"selected": false,
"text": "string='My long string'\necho $string | jq -Rr 'select(contains(\"long\"))|\"It is there\"'\n echo $string | jq --arg quote \"'\" -Rr 'select(contains(\"long\"))|\"It\\($quote)s there\"'\n if jq -Re 'select(contains(\"long\"))|halt' <<< $string; then\n echo \"It's there!\"\nfi\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30773/"
] |
229,554
|
<p>Just wondering what the difference between <code>BeginInvoke()</code> and <code>Invoke()</code> are? </p>
<p>Mainly what each one would be used for.</p>
<p>EDIT: What is the difference between creating a threading object and calling invoke on that and just calling <code>BeginInvoke()</code> on a delegate? or are they the same thing?</p>
|
[
{
"answer_id": 229558,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 10,
"selected": true,
"text": "Delegate.Invoke BeginInvoke Control.Invoke BeginInvoke Delegate.Invoke Delegate.BeginInvoke threadpool Control.Invoke Control.BeginInvoke BeginInvoke Delegate.BeginInvoke BeginInvoke Person FirstName LastName person.FirstName = \"Kevin\"; // person is a shared reference\nperson.LastName = \"Spacey\";\ncontrol.BeginInvoke(UpdateName);\nperson.FirstName = \"Keyser\";\nperson.LastName = \"Soze\";\n Control.BeginInvoke Control.BeginInvoke EndInvoke"
},
{
"answer_id": 12364477,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 5,
"selected": false,
"text": "Control.Invoke() Control.BeginInvoke() BeginInvoke() Invoke() Invoke() BeginInvoke()"
},
{
"answer_id": 13873045,
"author": "KMC",
"author_id": 529310,
"author_profile": "https://Stackoverflow.com/users/529310",
"pm_score": 5,
"selected": false,
"text": "new Thread(foo).Start();\n\nprivate void foo()\n{\n this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,\n (ThreadStart)delegate()\n {\n myTextBox.Text = \"bing\";\n Thread.Sleep(TimeSpan.FromSeconds(3));\n });\n MessageBox.Show(\"done\");\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
229,565
|
<p>The Mutex class is very misunderstood, and Global mutexes even more so.</p>
<p>What is good, safe pattern to use when creating Global mutexes?</p>
<p>One that will work</p>
<ul>
<li>Regardless of the locale my machine is in</li>
<li>Is guaranteed to release the mutex properly</li>
<li>Optionally does not hang forever if the mutex is not acquired</li>
<li>Deals with cases where other processes abandon the mutex </li>
</ul>
|
[
{
"answer_id": 229567,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 10,
"selected": true,
"text": "using System.Runtime.InteropServices; //GuidAttribute\nusing System.Reflection; //Assembly\nusing System.Threading; //Mutex\nusing System.Security.AccessControl; //MutexAccessRule\nusing System.Security.Principal; //SecurityIdentifier\n\nstatic void Main(string[] args)\n{\n // get application GUID as defined in AssemblyInfo.cs\n string appGuid =\n ((GuidAttribute)Assembly.GetExecutingAssembly().\n GetCustomAttributes(typeof(GuidAttribute), false).\n GetValue(0)).Value.ToString();\n\n // unique id for global mutex - Global prefix means it is global to the machine\n string mutexId = string.Format( \"Global\\\\{{{0}}}\", appGuid );\n\n // Need a place to store a return value in Mutex() constructor call\n bool createdNew;\n\n // edited by Jeremy Wiebe to add example of setting up security for multi-user usage\n // edited by 'Marc' to work also on localized systems (don't use just \"Everyone\") \n var allowEveryoneRule =\n new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid\n , null)\n , MutexRights.FullControl\n , AccessControlType.Allow\n );\n var securitySettings = new MutexSecurity();\n securitySettings.AddAccessRule(allowEveryoneRule);\n\n // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen\n using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))\n {\n // edited by acidzombie24\n var hasHandle = false;\n try\n {\n try\n {\n // note, you may want to time out here instead of waiting forever\n // edited by acidzombie24\n // mutex.WaitOne(Timeout.Infinite, false);\n hasHandle = mutex.WaitOne(5000, false);\n if (hasHandle == false)\n throw new TimeoutException(\"Timeout waiting for exclusive access\");\n }\n catch (AbandonedMutexException)\n {\n // Log the fact that the mutex was abandoned in another process,\n // it will still get acquired\n hasHandle = true;\n }\n\n // Perform your work here.\n }\n finally\n {\n // edited by acidzombie24, added if statement\n if(hasHandle)\n mutex.ReleaseMutex();\n }\n }\n}\n"
},
{
"answer_id": 1213517,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 3,
"selected": false,
"text": "// unique id for global mutex - Global prefix means it is global to the machine\nconst string mutex_id = \"Global\\\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}\";\n\nstatic void Main(string[] args)\n{\n\n using (var mutex = new Mutex(false, mutex_id))\n {\n try\n {\n try\n {\n if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))\n {\n Console.WriteLine(\"Another instance of this program is running\");\n Environment.Exit(0);\n }\n }\n catch (AbandonedMutexException)\n {\n // Log the fact the mutex was abandoned in another process, it will still get aquired\n }\n\n // Perform your work here.\n }\n finally\n {\n mutex.ReleaseMutex();\n }\n }\n}\n"
},
{
"answer_id": 7810107,
"author": "deepee1",
"author_id": 483179,
"author_profile": "https://Stackoverflow.com/users/483179",
"pm_score": 7,
"selected": false,
"text": "using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock\n{\n //Only 1 of these runs at a time\n RunSomeStuff();\n}\n class SingleGlobalInstance : IDisposable\n{\n //edit by user \"jitbit\" - renamed private fields to \"_\"\n public bool _hasHandle = false;\n Mutex _mutex;\n\n private void InitMutex()\n {\n string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;\n string mutexId = string.Format(\"Global\\\\{{{0}}}\", appGuid);\n _mutex = new Mutex(false, mutexId);\n\n var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);\n var securitySettings = new MutexSecurity();\n securitySettings.AddAccessRule(allowEveryoneRule);\n _mutex.SetAccessControl(securitySettings);\n }\n\n public SingleGlobalInstance(int timeOut)\n {\n InitMutex();\n try\n {\n if(timeOut < 0)\n _hasHandle = _mutex.WaitOne(Timeout.Infinite, false);\n else\n _hasHandle = _mutex.WaitOne(timeOut, false);\n\n if (_hasHandle == false)\n throw new TimeoutException(\"Timeout waiting for exclusive access on SingleInstance\");\n }\n catch (AbandonedMutexException)\n {\n _hasHandle = true;\n }\n }\n\n\n public void Dispose()\n {\n if (_mutex != null)\n {\n if (_hasHandle)\n _mutex.ReleaseMutex();\n _mutex.Close();\n }\n }\n}\n"
},
{
"answer_id": 15290536,
"author": "sol",
"author_id": 1936816,
"author_profile": "https://Stackoverflow.com/users/1936816",
"pm_score": 3,
"selected": false,
"text": "static class Program\n{\n [STAThread]\n static void Main()\n {\n if (SingleApplicationDetector.IsRunning()) {\n return;\n }\n\n Application.Run(new MainForm());\n\n SingleApplicationDetector.Close();\n }\n}\n SingleApplicationDetector using System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Threading;\n\npublic static class SingleApplicationDetector\n{\n public static bool IsRunning()\n {\n string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();\n var semaphoreName = @\"Global\\\" + guid;\n try {\n __semaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize);\n\n Close();\n return true;\n }\n catch (Exception ex) {\n __semaphore = new Semaphore(0, 1, semaphoreName);\n return false;\n }\n }\n\n public static void Close()\n {\n if (__semaphore != null) {\n __semaphore.Close();\n __semaphore = null;\n }\n }\n\n private static Semaphore __semaphore;\n}\n"
},
{
"answer_id": 52340464,
"author": "user3248578",
"author_id": 1051237,
"author_profile": "https://Stackoverflow.com/users/1051237",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Threading;\n\nnamespace MutexExample\n{\n class Program\n {\n static Mutex m = new Mutex(false, \"myMutex\");//create a new NAMED mutex, DO NOT OWN IT\n static void Main(string[] args)\n {\n Console.WriteLine(\"Waiting to acquire Mutex\");\n m.WaitOne(); //ask to own the mutex, you'll be queued until it is released\n Console.WriteLine(\"Mutex acquired.\\nPress enter to release Mutex\");\n Console.ReadLine();\n m.ReleaseMutex();//release the mutex so other processes can use it\n }\n }\n}\n"
},
{
"answer_id": 58326849,
"author": "Eric Ouellet",
"author_id": 452845,
"author_profile": "https://Stackoverflow.com/users/452845",
"pm_score": 0,
"selected": false,
"text": "static MutexGlobal _globalMutex = null;\nstatic MutexGlobal GlobalMutexAccessEMTP\n{\n get\n {\n if (_globalMutex == null)\n {\n _globalMutex = new MutexGlobal();\n }\n return _globalMutex;\n }\n}\n\nusing (GlobalMutexAccessEMTP.GetAwaiter())\n{\n ...\n} \n using System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading;\n\nnamespace HQ.Util.General.Threading\n{\n public class MutexGlobal : IDisposable\n {\n // ************************************************************************\n public string Name { get; private set; }\n internal Mutex Mutex { get; private set; }\n public int DefaultTimeOut { get; set; }\n public Func<int, bool> FuncTimeOutRetry { get; set; }\n\n // ************************************************************************\n public static MutexGlobal GetApplicationMutex(int defaultTimeOut = Timeout.Infinite)\n {\n return new MutexGlobal(defaultTimeOut, ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value);\n }\n\n // ************************************************************************\n public MutexGlobal(int defaultTimeOut = Timeout.Infinite, string specificName = null)\n {\n try\n {\n if (string.IsNullOrEmpty(specificName))\n {\n Name = Guid.NewGuid().ToString();\n }\n else\n {\n Name = specificName;\n }\n\n Name = string.Format(\"Global\\\\{{{0}}}\", Name);\n\n DefaultTimeOut = defaultTimeOut;\n\n FuncTimeOutRetry = DefaultFuncTimeOutRetry;\n\n var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);\n var securitySettings = new MutexSecurity();\n securitySettings.AddAccessRule(allowEveryoneRule);\n\n Mutex = new Mutex(false, Name, out bool createdNew, securitySettings);\n\n if (Mutex == null)\n {\n throw new Exception($\"Unable to create mutex: {Name}\");\n }\n }\n catch (Exception ex)\n {\n Log.Log.Instance.AddEntry(Log.LogType.LogException, $\"Unable to create Mutex: {Name}\", ex);\n throw;\n }\n }\n\n // ************************************************************************\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"timeOut\"></param>\n /// <returns></returns>\n public MutexGlobalAwaiter GetAwaiter(int timeOut)\n {\n return new MutexGlobalAwaiter(this, timeOut);\n }\n\n // ************************************************************************\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"timeOut\"></param>\n /// <returns></returns>\n public MutexGlobalAwaiter GetAwaiter()\n {\n return new MutexGlobalAwaiter(this, DefaultTimeOut);\n }\n\n // ************************************************************************\n /// <summary>\n /// This method could either throw any user specific exception or return \n /// true to retry. Otherwise, retruning false will let the thread continue\n /// and you should verify the state of MutexGlobalAwaiter.HasTimedOut to \n /// take proper action depending on timeout or not. \n /// </summary>\n /// <param name=\"timeOutUsed\"></param>\n /// <returns></returns>\n private bool DefaultFuncTimeOutRetry(int timeOutUsed)\n {\n // throw new TimeoutException($\"Mutex {Name} timed out {timeOutUsed}.\");\n\n Log.Log.Instance.AddEntry(Log.LogType.LogWarning, $\"Mutex {Name} timeout: {timeOutUsed}.\");\n return true; // retry\n }\n\n // ************************************************************************\n public void Dispose()\n {\n if (Mutex != null)\n {\n Mutex.ReleaseMutex();\n Mutex.Close();\n }\n }\n\n // ************************************************************************\n\n }\n}\n using System;\n\nnamespace HQ.Util.General.Threading\n{\n public class MutexGlobalAwaiter : IDisposable\n {\n MutexGlobal _mutexGlobal = null;\n\n public bool HasTimedOut { get; set; } = false;\n\n internal MutexGlobalAwaiter(MutexGlobal mutexEx, int timeOut)\n {\n _mutexGlobal = mutexEx;\n\n do\n {\n HasTimedOut = !_mutexGlobal.Mutex.WaitOne(timeOut, false);\n if (! HasTimedOut) // Signal received\n {\n return;\n }\n } while (_mutexGlobal.FuncTimeOutRetry(timeOut));\n }\n\n #region IDisposable Support\n private bool disposedValue = false; // To detect redundant calls\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposedValue)\n {\n if (disposing)\n {\n _mutexGlobal.Mutex.ReleaseMutex();\n }\n\n // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.\n // TODO: set large fields to null.\n\n disposedValue = true;\n }\n }\n // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.\n // ~MutexExAwaiter()\n // {\n // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.\n // Dispose(false);\n // }\n\n // This code added to correctly implement the disposable pattern.\n public void Dispose()\n {\n // Do not change this code. Put cleanup code in Dispose(bool disposing) above.\n Dispose(true);\n // TODO: uncomment the following line if the finalizer is overridden above.\n // GC.SuppressFinalize(this);\n }\n #endregion\n }\n}\n"
},
{
"answer_id": 59079638,
"author": "Wouter",
"author_id": 4491768,
"author_profile": "https://Stackoverflow.com/users/4491768",
"pm_score": 2,
"selected": false,
"text": "private Mutex mutex;\nprivate bool mutexCreated;\n\npublic App()\n{\n string mutexId = $\"Global\\\\{GetType().GUID}\";\n mutex = new Mutex(true, mutexId, out mutexCreated);\n}\n\nprotected override void OnStartup(StartupEventArgs e)\n{\n base.OnStartup(e);\n if (!mutexCreated)\n {\n MessageBox.Show(\"Already started!\");\n Shutdown();\n }\n}\n protected override void OnExit(ExitEventArgs e)\n{\n base.OnExit(e);\n mutex.Dispose();\n}\n public class SingleApplication : Application\n{\n private Mutex mutex;\n private bool mutexCreated;\n\n public SingleApplication()\n {\n string mutexId = $\"Global\\\\{GetType().GUID}\";\n\n MutexAccessRule allowEveryoneRule = new MutexAccessRule(\n new SecurityIdentifier(WellKnownSidType.WorldSid, null),\n MutexRights.FullControl, \n AccessControlType.Allow);\n MutexSecurity securitySettings = new MutexSecurity();\n securitySettings.AddAccessRule(allowEveryoneRule);\n\n // initiallyOwned: true == false + mutex.WaitOne()\n mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings); \n }\n\n protected override void OnExit(ExitEventArgs e)\n {\n base.OnExit(e);\n if (mutexCreated)\n {\n try\n {\n mutex.ReleaseMutex();\n }\n catch (ApplicationException ex)\n {\n MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n mutex.Dispose();\n }\n\n protected override void OnStartup(StartupEventArgs e)\n {\n base.OnStartup(e);\n if (!mutexCreated)\n {\n MessageBox.Show(\"Already started!\");\n Shutdown();\n }\n }\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
229,571
|
<p>I'm involved in creating a web based business solution. The idea is that the customers will use it, get their business processes and information into one place and also receive added business value by inter-system communication. In short they will use it as a core tool in their daily work and will depend highly upon it.</p>
<p>One problem in need of a solution is how to get this web system secure enough to be an alternative which both we and the customers will find satisfactory. I am looking for good advice from others who have been or are in the same situation.</p>
<p>In our specific scenario we're currently looking at using Java SE 6, Tomcat (as a Servlet container, needed as we will use Wicket), Hibernate (to interact with our database) and MySQL (as DBMS).</p>
<p>I think the problem and advice will be of interest for other technology users as well. As many of the issues are general ones regarding HDD failure, network accessibility and other things.</p>
<p>Feel free to give any advice you have! I still provide some questions and thoughts to get us going:</p>
<ul>
<li>The system needs to be reachable through the Internet. What should we think about when deciding on how to host it? (i.e. do we need our web host to have multiple physical paths connecting them to the Internet and similar questions.)</li>
<li>Are there check lists for these kinds of things? Maybe ISO standards or some other way of seeing that we are on the right track by looking through an article/check list/academic paper/book?</li>
<li>Later in the project we think it would be a good idea to get someone involved who has extensive experience in the field. In that case we're not looking for a normal web developer. It is likely that more consulting firms will tell us they are capable of providing this expertise then there actually are. Any tips on how we will get in contact with the right people? (We're based in Scandinavia, so it would be preferable to find someone there.)</li>
<li>How high up time is good enough? 99.99% seems like a reasonable goal. But any downtime might result in loss of business for our customers.</li>
<li>How do we guarantee that each customer only will be able to access its own data? As the system will be able to access it's own database, it seems hard. A proper development process, involving lots of testing, is really all we have regarding user privileges.</li>
<li>How do we deal with HDD failures? Is RAID 5 in combination with a daily incremental backup and a weekly full backup enough? Or would you go for RAID 6?</li>
<li>If one server is enough to serve the clients. Would you still use a cluster? (I would think so.) And in that case, how many nodes would you have in the cluster?</li>
<li>Which backup strategy would you use?</li>
<li>Do you think hosting the system in a computer cloud is a good alternative? (i.e. as provided by Amazon, Google or others.)</li>
<li>Would you use hard disk encryption? And if so, which kind? (One clarification: Yes it's only good if someone steals the hard disk, but that's still added security and may prevent (physical) intruders access to vital client business data.)</li>
<li>Is providing the customer with a way to do their own backups as well a good alternative? These customers won't be technically oriented. So in that case downloading the information in a ZIP archive containing Microsoft Office files might be a good way?</li>
<li>How would you monitor the solution?</li>
<li>Which of these things do you think we should do in house and which should be out sourced? We will develop the core system our self's, of course.</li>
<li>If you feel that the system is secure, as a technical person. How do you convince a non technical person that it's safe and secure?</li>
</ul>
<p>Thank you for your time! I hope you have some input to share. More questions might be added later.</p>
|
[
{
"answer_id": 229737,
"author": "Blade",
"author_id": 30004,
"author_profile": "https://Stackoverflow.com/users/30004",
"pm_score": 3,
"selected": true,
"text": "Which of these things do you think we should do in house and which should be out sourced? We will develop the core system our self's, of course. Are there check lists for these kinds of things? Maybe ISO standards or some other way of seeing that we are on the right track by looking through an article/check list/academic paper/book? Do you think hosting the system in a computer cloud is a good alternative? (i.e. as provided by Amazon, Google or others.) If you feel that the system is secure, as a technical person. How do you convince a non technical person that it's safe and secure? How do we guarantee that each customer only will be able to access its own data? As the system will be able to access it's own database, it seems hard. A proper development process, involving lots of testing, is really all we have regarding user privileges."
},
{
"answer_id": 612746,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 0,
"selected": false,
"text": "How do we guarantee that each customer only will be able to access\n If one server is enough to serve the clients. Would you still use a cluster? (I would think so.) And in that case, how many nodes would you have in the cluster? \n Which backup strategy would you use?\n Do you think hosting the system in a computer cloud is a good alternative? (i.e. as provided by Amazon, Google or others.) \n Would you use hard disk encryption? And if so, which kind? (One clarification: Yes it's only good if someone steals the hard disk, but that's still added security and may prevent (physical) intruders access to vital client business data.) \n Is providing the customer with a way to do their own backups as well a good alternative? These customers won't be technically oriented. So in that case downloading the information in a ZIP archive containing Microsoft Office files might be a good way? \n How would you monitor the solution? \n If you feel that the system is secure, as a technical person. How do you convince a non technical person that it's safe and secure? \n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
229,622
|
<p>I am working on a stored procedure with several optional parameters. Some of these parameters are single values and it's easy enough to use a WHERE clause like:</p>
<pre><code>WHERE (@parameter IS NULL OR column = @parameter)
</code></pre>
<p>However, in some instances, the WHERE condition is more complicated:</p>
<pre><code>WHERE (@NewGroupId IS NULL OR si.SiteId IN (SELECT gs.SiteId
FROM [UtilityWeb].[dbo].[GroupSites] AS gs
WHERE gs.GroupId = @NewGroupId))
</code></pre>
<p>When I uncomment these complicated WHERE clauses, the query execution time doubles and the execution plan becomes remarkably more complicated. While the execution plan doesn't bother me, doubling the execution time of a query is a definite problem.</p>
<p>Is there a best practice or pattern that others have found for working with optional parameters in their stored procedures?</p>
<p>Is this one of those instances where dynamic SQL would be a better solution?</p>
|
[
{
"answer_id": 229641,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 3,
"selected": false,
"text": "if (@parameter IS NULL) then begin\n select * from foo\nend\nelse begin\n select * from foo where value = @parameter\nend\n"
},
{
"answer_id": 229709,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": true,
"text": "SELECT * \nFROM Table as si\nJOIN (\n SELECT SiteId\n FROM [UtilityWeb].[dbo].[GroupSites]\n WHERE GroupId = ISNULL(@NewGroupId, GroupId)\n /* --Or, if all SiteIds aren't in GroupSites, or GroupSites is unusually large \n --this might work better\n SELECT @newGroupId\n UNION ALL\n SELECT SiteId FROM [UtilityWeb].[dbo].[GroupSites]\n WHERE GroupId = @NewGroupId\n */\n) as gs ON\n si.SiteId = gs.SiteId\n"
},
{
"answer_id": 229729,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 2,
"selected": false,
"text": "if (@parameter IS NULL) then begin\n select * from foo\nend\nelse begin\n select * from foo where value = @parameter\nend\n SELECT * FROM foo \nWHERE value = CASE WHEN @parameter IS NULL THEN value ELSE @parameter END\n SELECT * FROM foo \nWHERE value = ISNULL(@parameter,value)\n"
},
{
"answer_id": 729874,
"author": "Irawan Soetomo",
"author_id": 54908,
"author_profile": "https://Stackoverflow.com/users/54908",
"pm_score": 1,
"selected": false,
"text": "\ncreate proc ManyParams\n(\n @pcol1 int,\n @pcol2 int,\n @pcol3 int\n)\nas\ndeclare\n @col1 int,\n @col2 int,\n @col3 int\n\nselect\n @col1 = @pcol1,\n @col2 = @pcol2,\n @col3 = @pcol3\n\nselect \n col1,\n col2,\n col3\nfrom \n tbl \nwhere \n 1 = case when @col1 is null then 1 else case when col1 = @col1 then 1 else 0 end end\nand 1 = case when @col2 is null then 1 else case when col2 = @col2 then 1 else 0 end end\nand 1 = case when @col3 is null then 1 else case when col3 = @col3 then 1 else 0 end end\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11780/"
] |
229,623
|
<pre><code><input type="submit"/>
<style>
input {
background: url(tick.png) bottom left no-repeat;
padding-left: 18px;
}
</style>
</code></pre>
<p>But the bevel goes away, how can I add an icon to submit button and keep the bevel?<br>
Edit: I want it to look like the browser default.</p>
|
[
{
"answer_id": 229640,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "INPUT.button {\n BORDER-RIGHT: #999999 1px solid;\n BORDER-TOP: #999999 1px solid;\n FONT-SIZE: 11px;\n BACKGROUND: url(tick.png) bottom left no-repeat;\n BORDER-LEFT: #999999 1px solid;\n CURSOR: pointer;\n COLOR: #333333;\n BORDER-BOTTOM: #999999 1px solid\n}\n\n<input type=\"submit\" class=\"button\" />\n"
},
{
"answer_id": 229662,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 1,
"selected": false,
"text": "input#button {\n border: 2px outset rgb(0, 0, 0);\n}\n\ninput#button:focus {\n border: 2px inset rgb(0, 0, 0);\n}\n"
},
{
"answer_id": 229748,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 2,
"selected": false,
"text": "<button type=\"submit\"><img src=\"image.gif\" /> Text</button>\nor \n<button type=\"submit\"><span class=\"icon\"></span> Text</button>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
229,627
|
<p>I have looked over the Repository pattern and I recognized some ideas that I was using in the past which made me feel well.</p>
<p>However now I would like to write an application that would use this pattern <strong>BUT I WOULD LIKE TO HAVE THE ENTITY CLASSES DECOUPLED</strong> from the repository provider.</p>
<p>I would create several assemblies :</p>
<ol>
<li>an "Interfaces" assembly which would host common interfaces including the IRepository interface</li>
<li>an "Entities" assembly which would host the entity classes such as Product, User, Order and so on. This assembly would be referenced by the "Interfaces" assembly since some methods would return such types or arrays of them. Also it would be referenced by the main application assembly (such as the Web Application)</li>
<li>one or more Repository provider assembly/assemblies. Each would include (at least) a class that implements the IRepository interface and it would work with a certain Data Store. Data stores could include an SQL Server, an Oracle server, MySQL, XML files, Web / WCF services and so on.</li>
</ol>
<p>Studying LINQ to SQL which looks very productive in terms of time taken to implement all seems well until I discover the deep dependency between the generated classes and the CustomDataContext class.</p>
<p>How can I use LINQ to SQL in such a scenario?</p>
|
[
{
"answer_id": 232759,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": " <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <Database Name=\"DbName\" \n xmlns=\"http://schemas.microsoft.com/linqtosql/dbml/2007\">\n <Table Name=\"DbTableName\">\n <Type Name=\"EntityClassName\" >\n <Column Name=\"ID\" Type=\"System.Int64\" Member=\"Id\"\n DbType=\"BigInt NOT NULL IDENTITY\" IsPrimaryKey=\"true\"\n CanBeNull=\"false\" />\n <Column Name=\"ColumnName\" Type=\"System.String\" Member=\"PropertyA\"\n DbType=\"VarChar(1024)\" CanBeNull=\"true\" />\n </Type>\n </Table>\n </Database>\n using (var cn = GetDbConnection())\n { var mappingSrc = XmlMappingSource.FromReader(xmlReader);\n\n using (var db = new DataContext(cn, mappingSrc))\n { var q = from entity in db.GetTable<EntityClassName>()\n where entity.PropertyA = \"...\"\n select entity.ID;\n }\n }\n"
},
{
"answer_id": 232816,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 2,
"selected": false,
"text": "public static T CloneEntity<T>(T source)\n{\n DataContractSerializer dcs = new DataContractSerializer(typeof(T));\n using (Stream stream = new MemoryStream())\n {\n dcs.WriteObject(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)dcs.ReadObject(stream);\n }\n}\n"
},
{
"answer_id": 234598,
"author": "user31259",
"author_id": 31259,
"author_profile": "https://Stackoverflow.com/users/31259",
"pm_score": 2,
"selected": false,
"text": " public class Service1 : IService1\n {\n public Company GetCompany(int companyId)\n {\n using (DataClasses1DataContext dc = new DataClasses1DataContext())\n {\n return (from c in dc.Companies where c.CompanyId == companyId select c).Single();\n }\n }\n\n public void SaveCompany(Company company)\n {\n using (DataClasses1DataContext dc = new DataClasses1DataContext())\n {\n dc.Companies.Attach(company, true);\n dc.SubmitChanges();\n }\n }\n\n public void InsertCompany(Company company)\n {\n using (DataClasses1DataContext dc = new DataClasses1DataContext())\n {\n dc.Companies.InsertOnSubmit(company);\n dc.SubmitChanges();\n }\n }\n}\n\n\n public void SaveCompany(Company company)\n {\n using (DataClasses1DataContext dc = new DataClasses1DataContext())\n {\n dc.Companies.Attach(company, true);\n dc.SubmitChanges();\n }\n }\n\n public void InsertCompany(Company company)\n {\n using (DataClasses1DataContext dc = new DataClasses1DataContext())\n {\n dc.Companies.InsertOnSubmit(company);\n dc.SubmitChanges();\n }\n }\n}\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/229627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.