qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
122,175
|
<p>I'm trying to setup some friendly URLs on a SharePoint website. I know that I can do the ASP.Net 2.0 friendly URLs using RewritePath, but I was wondering if it was possible to make use of the System.Web.Routing that comes with ASP.NET 3.5 SP1. </p>
<p>I think I've figured out how to get my route table loaded, but I'm not clear on what method to use to get the correct IHttpHandler to pass out.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 127897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "var route = new Route(\"blah/{*path}\", new MyRouteHandler());\nRouteTable.Routes.Add(route);\n\npublic class MyRouteHandler : IRouteHandler\n{\n public IHttpHandler GetHttpHandler(RequestContext requestContext)\n {\n // return some HTTP handler here\n }\n}\n <add name=\"Routing\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n"
},
{
"answer_id": 1082237,
"author": "Daniel Pollard",
"author_id": 2758,
"author_profile": "https://Stackoverflow.com/users/2758",
"pm_score": 1,
"selected": true,
"text": "var route = new Route(\"blah/{*path}\", new MyRouteHandler());\nRouteTable.Routes.Add(route);\npublic class MyRouteHandler : IRouteHandler\n{ \npublic IHttpHandler GetHttpHandler(RequestContext requestContext) \n{ \n //rewrite to some know sharepoint path\n HttpContext.Current.RewritePath(\"~/Pages/Default.aspx\");\n\n // return some HTTP handler here \n return new DefaultHttpHandler(); \n\n}}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10893/"
] |
122,192
|
<p>I have a list control in GTK+ (a <code>gtk.TreeView</code> with one column), with "find-as-you type" enabled (so typing any text will open a small search field for searching through the list entries). Now, if the user enters some search text like "abc", should I search only for entries <em>starting</em> with "abc", or should I search for entries that contain "abc" somewhere in their text?</p>
<p>(links to relevant Human Interface Guidelines appreciated)</p>
|
[
{
"answer_id": 122246,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 0,
"selected": false,
"text": "Shining, The - King, Stephen\nThe Shining - Stephen King\nKing, Stephen - The Shining\n"
},
{
"answer_id": 122907,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 0,
"selected": false,
"text": "var input = getInput();\n input =~ s/(.)/$1.*/g;\nreturn find_items(input); // Assuming this takes a regexp as its input\n input = \"Shing\" {..., Sine, Shining, 'The Shining', ...} {Shining, 'The Shining'} var input = getInput();\n input =~ s/(\\w+)/$1.*/g;\nreturn find_items(input); // Assuming this takes a regexp as its input\n input = \"Th Shi\" {'The Shining'}"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148773/"
] |
122,208
|
<p>In C++, what's the easiest way to get the local computer's IP address and subnet mask?</p>
<p>I want to be able to detect the local machine's IP address in my local network. In my particular case, I have a network with a subnet mask of 255.255.255.0 and my computer's IP address is 192.168.0.5. I need to get these had two values programmatically in order to send a broadcast message to my network (in the form 192.168.0.255, for my particular case)</p>
<p>Edit: Many answers were not giving the results I expected because I had two different network IP's. <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122235">Torial</a>'s code did the trick (it gave me both IP addresses).</p>
<p>Edit 2: Thanks to <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122225">Brian R. Bondy</a> for the info about the subnet mask.</p>
|
[
{
"answer_id": 122225,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "//Example: b1 == 192, b2 == 168, b3 == 0, b4 == 100\nstruct IPv4\n{\n unsigned char b1, b2, b3, b4;\n};\n\nbool getMyIP(IPv4 & myIP)\n{\n char szBuffer[1024];\n\n #ifdef WIN32\n WSADATA wsaData;\n WORD wVersionRequested = MAKEWORD(2, 0);\n if(::WSAStartup(wVersionRequested, &wsaData) != 0)\n return false;\n #endif\n\n\n if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)\n {\n #ifdef WIN32\n WSACleanup();\n #endif\n return false;\n }\n\n struct hostent *host = gethostbyname(szBuffer);\n if(host == NULL)\n {\n #ifdef WIN32\n WSACleanup();\n #endif\n return false;\n }\n\n //Obtain the computer's IP\n myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;\n myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;\n myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;\n myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;\n\n #ifdef WIN32\n WSACleanup();\n #endif\n return true;\n}\n"
},
{
"answer_id": 122240,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 2,
"selected": false,
"text": "// Init WinSock\nWSADATA wsa_Data;\nint wsa_ReturnCode = WSAStartup(0x101,&wsa_Data);\n\n// Get the local hostname\nchar szHostName[255];\ngethostname(szHostName, 255);\nstruct hostent *host_entry;\nhost_entry=gethostbyname(szHostName);\nchar * szLocalIP;\nszLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);\nWSACleanup();\n"
},
{
"answer_id": 1317246,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "case IDC_IP:\n\n gethostname(szHostName, 255);\n host_entry=gethostbyname(szHostName);\n szLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);\n //WSACleanup(); \n writeInTextBox(\"\\n\");\n writeInTextBox(\"IP: \"); \n writeInTextBox(szLocalIP);\n break;\n //WSACleanup(); \n"
},
{
"answer_id": 1317284,
"author": "Jeremy Friesner",
"author_id": 131930,
"author_profile": "https://Stackoverflow.com/users/131930",
"pm_score": 5,
"selected": false,
"text": "fe80::1%lo0 \n127.0.0.1 \n::1 \nfe80::21f:5bff:fe3f:1b36%en1 \n10.0.0.138 \n172.16.175.1\n192.168.27.1\n"
},
{
"answer_id": 10838854,
"author": "kgriffs",
"author_id": 21784,
"author_profile": "https://Stackoverflow.com/users/21784",
"pm_score": 5,
"selected": false,
"text": "void ListIpAddresses(IpAddresses& ipAddrs)\n{\n IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);\n IP_ADAPTER_ADDRESSES* adapter(NULL);\n\n // Start with a 16 KB buffer and resize if needed -\n // multiple attempts in case interfaces change while\n // we are in the middle of querying them.\n DWORD adapter_addresses_buffer_size = 16 * KB;\n for (int attempts = 0; attempts != 3; ++attempts)\n {\n adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);\n assert(adapter_addresses);\n\n DWORD error = ::GetAdaptersAddresses(\n AF_UNSPEC, \n GAA_FLAG_SKIP_ANYCAST | \n GAA_FLAG_SKIP_MULTICAST | \n GAA_FLAG_SKIP_DNS_SERVER |\n GAA_FLAG_SKIP_FRIENDLY_NAME, \n NULL, \n adapter_addresses,\n &adapter_addresses_buffer_size);\n\n if (ERROR_SUCCESS == error)\n {\n // We're done here, people!\n break;\n }\n else if (ERROR_BUFFER_OVERFLOW == error)\n {\n // Try again with the new size\n free(adapter_addresses);\n adapter_addresses = NULL;\n\n continue;\n }\n else\n {\n // Unexpected error code - log and throw\n free(adapter_addresses);\n adapter_addresses = NULL;\n\n // @todo\n LOG_AND_THROW_HERE();\n }\n }\n\n // Iterate through all of the adapters\n for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)\n {\n // Skip loopback adapters\n if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)\n {\n continue;\n }\n\n // Parse all IPv4 and IPv6 addresses\n for (\n IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; \n NULL != address;\n address = address->Next)\n {\n auto family = address->Address.lpSockaddr->sa_family;\n if (AF_INET == family)\n {\n // IPv4\n SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);\n\n char str_buffer[INET_ADDRSTRLEN] = {0};\n inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);\n ipAddrs.mIpv4.push_back(str_buffer);\n }\n else if (AF_INET6 == family)\n {\n // IPv6\n SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);\n\n char str_buffer[INET6_ADDRSTRLEN] = {0};\n inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);\n\n std::string ipv6_str(str_buffer);\n\n // Detect and skip non-external addresses\n bool is_link_local(false);\n bool is_special_use(false);\n\n if (0 == ipv6_str.find(\"fe\"))\n {\n char c = ipv6_str[2];\n if (c == '8' || c == '9' || c == 'a' || c == 'b')\n {\n is_link_local = true;\n }\n }\n else if (0 == ipv6_str.find(\"2001:0:\"))\n {\n is_special_use = true;\n }\n\n if (! (is_link_local || is_special_use))\n {\n ipAddrs.mIpv6.push_back(ipv6_str);\n }\n }\n else\n {\n // Skip all other types of addresses\n continue;\n }\n }\n }\n\n // Cleanup\n free(adapter_addresses);\n adapter_addresses = NULL;\n\n // Cheers!\n}\n"
},
{
"answer_id": 28849513,
"author": "sashoalm",
"author_id": 492336,
"author_profile": "https://Stackoverflow.com/users/492336",
"pm_score": 4,
"selected": false,
"text": "fstream CreateFile()"
},
{
"answer_id": 33042829,
"author": "Zac",
"author_id": 971443,
"author_profile": "https://Stackoverflow.com/users/971443",
"pm_score": 0,
"selected": false,
"text": "#include <Windns.h>\n\nWSADATA wsa_Data;\n\nint wsa_ReturnCode = WSAStartup(0x101, &wsa_Data);\n\ngethostname(hostName, 256);\nPDNS_RECORD pDnsRecord;\n\nDNS_STATUS statsus = DnsQuery(hostName, DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, &pDnsRecord, NULL);\nIN_ADDR ipaddr;\nipaddr.S_un.S_addr = (pDnsRecord->Data.A.IpAddress);\nprintf(\"The IP address of the host %s is %s \\n\", hostName, inet_ntoa(ipaddr));\n\nDnsRecordListFree(&pDnsRecord, DnsFreeRecordList);\n"
},
{
"answer_id": 48160317,
"author": "Mark Yang",
"author_id": 1461744,
"author_profile": "https://Stackoverflow.com/users/1461744",
"pm_score": 0,
"selected": false,
"text": "DllExport void get_local_ips(boost::container::vector<wstring>& ips)\n{\n IP_ADAPTER_ADDRESSES* adapters = NULL;\n IP_ADAPTER_ADDRESSES* adapter = NULL;\n IP_ADAPTER_UNICAST_ADDRESS* adr = NULL;\n ULONG adapter_size = 0;\n ULONG err = 0;\n SOCKADDR_IN* sockaddr = NULL;\n\n err = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, NULL, &adapter_size);\n adapters = (IP_ADAPTER_ADDRESSES*)malloc(adapter_size);\n err = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, adapters, &adapter_size);\n\n for (adapter = adapters; NULL != adapter; adapter = adapter->Next)\n {\n if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue; // Skip Loopback\n if (adapter->OperStatus != IfOperStatusUp) continue; // Live connection only \n\n for (adr = adapter->FirstUnicastAddress;adr != NULL; adr = adr->Next)\n {\n sockaddr = (SOCKADDR_IN*)(adr->Address.lpSockaddr);\n char ipstr [INET6_ADDRSTRLEN] = { 0 };\n wchar_t ipwstr[INET6_ADDRSTRLEN] = { 0 };\n inet_ntop(AF_INET, &(sockaddr->sin_addr), ipstr, INET_ADDRSTRLEN);\n mbstowcs(ipwstr, ipstr, INET6_ADDRSTRLEN);\n wstring wstr(ipwstr);\n if (wstr != \"0.0.0.0\") ips.push_back(wstr); \n }\n }\n\n free(adapters);\n adapters = NULL; }\n"
},
{
"answer_id": 66954688,
"author": "mortalis",
"author_id": 1106547,
"author_profile": "https://Stackoverflow.com/users/1106547",
"pm_score": 0,
"selected": false,
"text": "GetAdaptersAddresses() IP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress Address inet_ntop() [ADAPTER]: Realtek PCIe\n[NAME]: Ethernet 3\n[IP]: 123.123.123.123\n cl test.cpp\n cl test.cpp Iphlpapi.lib ws2_32.lib\n #include <winsock2.h>\n#include <iphlpapi.h>\n#include <stdio.h>\n#include <ws2tcpip.h>\n\n// Link with Iphlpapi.lib and ws2_32.lib\n#pragma comment(lib, \"Iphlpapi.lib\")\n#pragma comment(lib, \"ws2_32.lib\")\n\nvoid ListIpAddresses() {\n IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);\n IP_ADAPTER_ADDRESSES* adapter(NULL);\n \n DWORD adapter_addresses_buffer_size = 16 * 1024;\n \n // Get adapter addresses\n for (int attempts = 0; attempts != 3; ++attempts) {\n adapter_addresses = (IP_ADAPTER_ADDRESSES*) malloc(adapter_addresses_buffer_size);\n\n DWORD error = ::GetAdaptersAddresses(AF_UNSPEC, \n GAA_FLAG_SKIP_ANYCAST | \n GAA_FLAG_SKIP_MULTICAST | \n GAA_FLAG_SKIP_DNS_SERVER | \n GAA_FLAG_SKIP_FRIENDLY_NAME,\n NULL, \n adapter_addresses,\n &adapter_addresses_buffer_size);\n \n if (ERROR_SUCCESS == error) {\n break;\n }\n else if (ERROR_BUFFER_OVERFLOW == error) {\n // Try again with the new size\n free(adapter_addresses);\n adapter_addresses = NULL;\n continue;\n }\n else {\n // Unexpected error code - log and throw\n free(adapter_addresses);\n adapter_addresses = NULL;\n return;\n }\n }\n\n // Iterate through all of the adapters\n for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next) {\n // Skip loopback adapters\n if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType) continue;\n \n printf(\"[ADAPTER]: %S\\n\", adapter->Description);\n printf(\"[NAME]: %S\\n\", adapter->FriendlyName);\n\n // Parse all IPv4 addresses\n for (IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; NULL != address; address = address->Next) {\n auto family = address->Address.lpSockaddr->sa_family;\n if (AF_INET == family) {\n SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);\n char str_buffer[16] = {0};\n inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, 16);\n\n printf(\"[IP]: %s\\n\", str_buffer);\n }\n }\n printf(\"\\n\");\n }\n\n free(adapter_addresses);\n adapter_addresses = NULL;\n}\n\nint main() {\n ListIpAddresses();\n return 0;\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4880/"
] |
122,215
|
<p>In my tests I need to test what happens when an OracleException is thrown (due to a stored procedure failure). I am trying to setup Rhino Mocks to </p>
<pre><code>Expect.Call(....).Throw(new OracleException());
</code></pre>
<p>For whatever reason however, OracleException seems to be sealed with no public constructor. What can I do to test this?</p>
<p><strong>Edit:</strong> Here is exactly what I'm trying to instantiate:</p>
<pre><code>public sealed class OracleException : DbException {
private OracleException(string message, int code) { ...}
}
</code></pre>
|
[
{
"answer_id": 122231,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 2,
"selected": false,
"text": "new OracleException()\n object[] args = ... ;\n(OracleException)Activator.CreateInstance(typeof(OracleException), args)\n"
},
{
"answer_id": 122469,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 3,
"selected": false,
"text": " ConstructorInfo ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(string), typeof(int)}, null);\n var c = (OracleException)ci.Invoke(new object[] { \"some message\", 123 });\n"
},
{
"answer_id": 1004956,
"author": "David Gardiner",
"author_id": 25702,
"author_profile": "https://Stackoverflow.com/users/25702",
"pm_score": 2,
"selected": false,
"text": " ConstructorInfo ci = typeof( SqlErrorCollection ).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null );\n SqlErrorCollection errorCollection = (SqlErrorCollection) ci.Invoke(new object[]{});\n\n ci = typeof( SqlException ).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof( string ), typeof( SqlErrorCollection ) }, null );\n return (SqlException) ci.Invoke( new object[] { \"some message\", errorCollection } );\n"
},
{
"answer_id": 3160057,
"author": "Charles Crawford",
"author_id": 381331,
"author_profile": "https://Stackoverflow.com/users/381331",
"pm_score": 2,
"selected": false,
"text": "object[] args = { 1, \"Test Message\" };\nConstructorInfo ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic \n | BindingFlags.Instance, null, System.Type.GetTypeArray(args), null);\nvar e = (OracleException)ci.Invoke(args);\n"
},
{
"answer_id": 5908499,
"author": "Morten Cools",
"author_id": 576855,
"author_profile": "https://Stackoverflow.com/users/576855",
"pm_score": 3,
"selected": true,
"text": "ConstructorInfo ci = typeof(OracleException)\n .GetConstructor(\n BindingFlags.NonPublic | BindingFlags.Instance, \n null, \n new Type[] { typeof(int) }, \n null\n );\n\nException ex = (OracleException)ci.Invoke(new object[] { 3113 });\n"
},
{
"answer_id": 26288906,
"author": "Kingpin2k",
"author_id": 1257694,
"author_profile": "https://Stackoverflow.com/users/1257694",
"pm_score": 3,
"selected": false,
"text": "var ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(string), typeof(string), typeof(string) }, null);\nvar c = (OracleException)ci.Invoke(new object[] { 1234, \"\", \"\", \"\" });\n"
},
{
"answer_id": 44820695,
"author": "Fredrik Hedblad",
"author_id": 318425,
"author_profile": "https://Stackoverflow.com/users/318425",
"pm_score": 2,
"selected": false,
"text": "ConstructorInfo[] all = typeof(OracleException).GetConstructors(\n BindingFlags.NonPublic | BindingFlags.Instance);`\n Oracle.DataAccess int, string, string, string, int internal OracleException(int errCode, string dataSrc, string procedure, string errMsg)\n{\n this.m_errors = new OracleErrorCollection();\n this.m_errors.Add(new OracleError(errCode, dataSrc, procedure, errMsg));\n}\n ConstructorInfo constructorInfo =\n typeof(OracleException).GetConstructor(\n BindingFlags.NonPublic | BindingFlags.Instance,\n null,\n new Type[] { typeof(int), typeof(string), typeof(string), typeof(string), typeof(int) },\n null);`\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
122,229
|
<p>I'm the only developer supporting a website that's a mix of classic asp and .NET. I had to add some .net pages to a classic asp application. This application requires users to login. The login page, written in classic asp, creates a cookie that .net pages use to identify the logged in user and stores information in session vars for the other classic asp pages to use. In classic asp the cookie code is as follows:</p>
<pre><code>response.cookies("foo")("value1") = value1
response.cookies("foo")("value2") = value2
response.cookies("foo").Expires = DateAdd("N", 15, Now())
response.cookies("foo").Path = "/"
</code></pre>
<p>In the .NET codebehind Page_Load code, I check for the cookie using the code below.</p>
<blockquote>
<p>if(!IsPostBack) {<br>
if(Request.Cookies["foo"] != null) {
... } else { //redirect to cookie creation page, cookiefoo.asp
} }</p>
</blockquote>
<p>The vast majority of the time this works with no problems. However, we have some users that get redirected to a cookie creation page because the Page_Load code can't find the cookie. No matter how many times the user is redirected to the cookie creation page, the referring page still can find the cookie, foo. The problem is happening in IE7 and I've tried modifying the privacy and cookie settings in the browser but can't seem to recreate the problem the user is having.</p>
<p>Does anyone have any ideas why this could be happening with IE7?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 2906948,
"author": "Toby Artisan",
"author_id": 243992,
"author_profile": "https://Stackoverflow.com/users/243992",
"pm_score": 1,
"selected": false,
"text": "Page.Response.Redirect(\"~/alpha\");\n Page.Response.Redirect(Page.ResolveUrl(\"~/alpha\").ToLower());\n"
},
{
"answer_id": 63600916,
"author": "Pedro Rodrigues",
"author_id": 3343753,
"author_profile": "https://Stackoverflow.com/users/3343753",
"pm_score": 0,
"selected": false,
"text": "utlização null .Replace(\"ç\", \"c\").Replace(\"ã\", \"a\")"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9809/"
] |
122,238
|
<p>JSF is setting the ID of an input field to <code>search_form:expression</code>. I need to specify some styling on that element, but that colon looks like the beginning of a pseudo-element to the browser so it gets marked invalid and ignored. Is there anyway to escape the colon or something?</p>
<pre><code>input#search_form:expression {
///...
}
</code></pre>
|
[
{
"answer_id": 122266,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 8,
"selected": true,
"text": "input#search_form\\:expression { ///...}\n"
},
{
"answer_id": 122268,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 3,
"selected": false,
"text": "input#search_form\\:expression {\n ///...\n}\n"
},
{
"answer_id": 656463,
"author": "jeremyh",
"author_id": 3802,
"author_profile": "https://Stackoverflow.com/users/3802",
"pm_score": 7,
"selected": false,
"text": "input#search_form\\3A expression { }\n"
},
{
"answer_id": 2228717,
"author": "naugtur",
"author_id": 173077,
"author_profile": "https://Stackoverflow.com/users/173077",
"pm_score": 2,
"selected": false,
"text": "input[id=\"something:something\"]"
},
{
"answer_id": 6241898,
"author": "Mathias Bynens",
"author_id": 96656,
"author_profile": "https://Stackoverflow.com/users/96656",
"pm_score": 4,
"selected": false,
"text": "\\: \\3a #search\\_form\\3a expression {}\n"
},
{
"answer_id": 19452643,
"author": "mbokil",
"author_id": 1672318,
"author_profile": "https://Stackoverflow.com/users/1672318",
"pm_score": 0,
"selected": false,
"text": "$('[id*=\"gantt1::majorAxis\"]').css('border-top', 'solid 1px ' + mediumGray);\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
122,239
|
<p>Within a table cell that is vertical-align:bottom, I have one or two divs. Each div is floated right.<br>
Supposedly, the divs should not align to the bottom, but they do (which I don't understand, but is good).<br>
However, when I have two floated divs in the cell, they align themselves to the same top line.<br>
I want the first, smaller, div to sit all the way at the bottom. Another acceptable solution is to make it full height of the table cell.</p>
<p>It's difficult to explain, so here's the code:</p>
<blockquote>
<pre><code><style type="text/css">
table {
border-collapse: collapse;
}
td {
border:1px solid black;
vertical-align:bottom;
}
.h {
float:right;
background: #FFFFCC;
}
.ha {
float:right;
background: #FFCCFF;
}
</style>
<table>
<tr>
<td>
<div class="ha">@</div>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="ha">@</div>
<div class="h">Title Text<br />Line 2<br />Line 3</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
</tr>
<tr>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
</tr>
</table>
</code></pre>
</blockquote>
<p>Here are the problems:</p>
<ol>
<li>Why does the @ sign sit at the same level as the yellow div?</li>
<li>Supposedly vertical-align doesn't apply to block elements (like a floated div) 1. But it does!</li>
<li>How can I make the @ sit at the bottom or make it full height of the table cell?</li>
</ol>
<p>I am testing in IE7 and FF2. Target support is IE6/7, FF2/3.</p>
<p><strong>Clarification:</strong> The goal is to have the red @ on the bottom line of the table cell, <em>next</em> to the yellow box. Using clear on either div will put them on different lines.
Additionally, the cells can have variable lines of text - therefore, <em>line-height</em> will not help.</p>
|
[
{
"answer_id": 122263,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "clear: both"
},
{
"answer_id": 127277,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": true,
"text": "<table>\n <tr>\n <td>\n <div class=\"t\">\n <div class=\"h\">Title Text<br />Line 2</div>\n <div class=\"ha\">@</div>\n </div>\n </td>\n <style type=\"text/css\">\ntable {\n border-collapse: collapse;\n}\ntd {\n border:1px solid black;\n vertical-align:bottom;\n}\n.t {\n position: relative;\n width:150px;\n}\n.h {\n background: #FFFFCC;\n width:135px;\n margin-right:15px;\n text-align:right;\n}\n.ha {\n background: #FFCCFF;\n width:15px;\n height:18px;\n position:absolute;\n right:0px;\n bottom:0px;\n}\n</style>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8435/"
] |
122,253
|
<p>After installing a third-party SDK, it very discourteously makes one if its templates the default item in "Add New Item..." dialog in Visual Studio 2005. This is also the case for all other similar dialogs - "Add Class...", "Add User Control..." etc.</p>
<p>Is there a way to change this behavior?</p>
|
[
{
"answer_id": 122270,
"author": "Asaf R",
"author_id": 6827,
"author_profile": "https://Stackoverflow.com/users/6827",
"pm_score": -1,
"selected": false,
"text": "HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\\n HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\9.0\n"
},
{
"answer_id": 246281,
"author": "Charles Anderson",
"author_id": 11677,
"author_profile": "https://Stackoverflow.com/users/11677",
"pm_score": 0,
"selected": false,
"text": "C:\\Program Files\\Microsoft Visual Studio 8\\VC\\VCNewItems\\NewItems.vsdir\n"
},
{
"answer_id": 421161,
"author": "shackett",
"author_id": 52194,
"author_profile": "https://Stackoverflow.com/users/52194",
"pm_score": 2,
"selected": false,
"text": " \n\n (Installed Templates) <VisualStudioInstallDir>\\Common7\\IDE\\ItemTemplates\\Language\\Locale\\\n (Custom Templates) My Documents\\Visual Studio 2005\\Templates\\ItemTemplates\\Language\\\n\n\n (Installed Templates) <VisualStudioInstallDir>\\Common7\\IDE\\ItemTemplates\\Language\\Locale\\\n (Custom Templates) My Documents\\Visual Studio 2005\\Templates\\ItemTemplates\\Language\\\n \n\n<TemplateData>\n <Name>SomeITem</Name>\n <Description>Description</Description>\n <ProjectType>>CSharp</ProjectType>\n <SortOrder>1000</SortOrder>\n <DefaultName></DefaultName>\n <ProvideDefaultName>true</ProvideDefaultName>\n </TemplateData>\n\n "
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
] |
122,254
|
<p>I have a class that defines the names of various session attributes, e.g.</p>
<pre><code>class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
</code></pre>
<p>I would like to use these constants within a JSP to test for the presence of these attributes, something like:</p>
<pre><code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.example.Constants" %>
<c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
</code></pre>
<p>But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with <code><c:set></code>, but again I'm struggling to find the correct syntax.</p>
<p><strong>UPDATE:</strong> Further to the suggestion below, I tried:</p>
<pre><code><c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
</code></pre>
<p>which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered</p>
<pre><code><c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>
</code></pre>
<p>This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help.....</p>
|
[
{
"answer_id": 122863,
"author": "Matt N",
"author_id": 20605,
"author_profile": "https://Stackoverflow.com/users/20605",
"pm_score": -1,
"selected": false,
"text": "<c:set var=\"nullUser\" \n scope=\"session\" \n value=\"${sessionScope[Constants.ATTR_CURRENT_USER] eq null}\" />\n\n<c:if test=\"${nullUser}\">\n <h2>First Test</h2>\n</c:if>\n<c:if test=\"${nullUser}\">\n <h2>Another Test</h2>\n</c:if>\n"
},
{
"answer_id": 125161,
"author": "Athena",
"author_id": 17846,
"author_profile": "https://Stackoverflow.com/users/17846",
"pm_score": 5,
"selected": true,
"text": "ATTR_CURRENT_USER package com.example;\n\npublic class Constants\n{\n // attribute, visible to the scriptlet\n public static final String ATTR_CURRENT_USER = \"current.user\";\n\n // getter function;\n // name modified to make it clear, later on, \n // that I am calling this function\n // and not accessing the constant\n public String getATTR_CURRENT_USER_FUNC()\n {\n return ATTR_CURRENT_USER;\n }\n\n\n} \n <%-- Set up the current user --%>\n<%\n session.setAttribute(\"current.user\", \"Me\");\n%>\n\n<%-- scriptlets --%>\n<%@ page import=\"com.example.Constants\" %>\n<h1>Using scriptlets</h1>\n<h3>Constants.ATTR_CURRENT_USER</h3>\n<%=Constants.ATTR_CURRENT_USER%> <br />\n<h3>Session[Constants.ATTR_CURRENT_USER]</h3>\n<%=session.getAttribute(Constants.ATTR_CURRENT_USER)%>\n\n<%-- JSTL --%>\n<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<jsp:useBean id=\"cons\" class=\"com.example.Constants\" scope=\"session\"/>\n\n<h1>Using JSTL</h1>\n<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>\n<c:out value=\"${cons.ATTR_CURRENT_USER_FUNC}\"/>\n<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>\n<c:out value=\"${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}\"/>\n<h3>Constants.ATTR_CURRENT_USER</h3>\n<c:out value=\"${sessionScope[Constants.ATTR_CURRENT_USER]}\"/>\n<%--\nCommented out, because otherwise will error:\nThe class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.\n\n<h3>cons.ATTR_CURRENT_USER</h3>\n<c:out value=\"${sessionScope[cons.ATTR_CURRENT_USER]}\"/>\n--%>\n<hr />\n"
},
{
"answer_id": 7119638,
"author": "Edgar",
"author_id": 461612,
"author_profile": "https://Stackoverflow.com/users/461612",
"pm_score": 2,
"selected": false,
"text": "${CONSTANTS[\"CONSTANT_NAME_IN_JAVA_CLASS_AS_A_STRING\"]}\n Map<String, Object> map = new HashMap<String, Object>();\nClass c = Constants.class;\nField[] fields = c.getDeclaredFields();\nfor (Field field : fields) {\n int modifier = field.getModifiers();\n if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier) && Modifier.isFinal(modifier)) {\n try {\n map.put(field.getName(), field.get(null));//Obj param of get method is ignored for static fields\n } catch (IllegalAccessException e) { /* ignorable due to modifiers check */ }\n }\n}\n"
},
{
"answer_id": 11489129,
"author": "daniel.deng",
"author_id": 1101166,
"author_profile": "https://Stackoverflow.com/users/1101166",
"pm_score": 3,
"selected": false,
"text": "<c:set var=\"ATTR_CURRENT_USER\" value=\"<%=Constants.ATTR_CURRENT_USER%>\" />\n<c:if test=\"${sessionScope[ATTR_CURRENT_USER] eq null}\"> \n <%-- Do somthing --%> \n</c:if> \n"
},
{
"answer_id": 11512392,
"author": "Roger Keays",
"author_id": 1104885,
"author_profile": "https://Stackoverflow.com/users/1104885",
"pm_score": 1,
"selected": false,
"text": "public final static String MANAGER_ROLE = 'manager';\npublic String manager_role = MANAGER_ROLE;\n ${bean.manager_role}\n"
},
{
"answer_id": 18497680,
"author": "hb5fa",
"author_id": 112951,
"author_profile": "https://Stackoverflow.com/users/112951",
"pm_score": 1,
"selected": false,
"text": "public class AppJspConstants implements Serializable {\n public static final int MAXLENGTH_SIGNON_ID = 100;\n public static final int MAXLENGTH_PASSWORD = 100;\n public static final int MAXLENGTH_FULLNAME = 30;\n public static final int MAXLENGTH_PHONENUMBER = 30;\n public static final int MAXLENGTH_EXTENSION = 10;\n public static final int MAXLENGTH_EMAIL = 235;\n}\n public class JspFieldAttributes extends SimpleTagSupport {\n public void doTag() throws JspException, IOException {\n getJspContext().setAttribute(\"maxlength_signon_id\", AppJspConstants.MAXLENGTH_SIGNON_ID);\n getJspContext().setAttribute(\"maxlength_password\", AppJspConstants.MAXLENGTH_PASSWORD);\n getJspContext().setAttribute(\"maxlength_fullname\", AppJspConstants.MAXLENGTH_FULLNAME);\n getJspContext().setAttribute(\"maxlength_phonenumber\", AppJspConstants.MAXLENGTH_PHONENUMBER);\n getJspContext().setAttribute(\"maxlength_extension\", AppJspConstants.MAXLENGTH_EXTENSION);\n getJspContext().setAttribute(\"maxlength_email\", AppJspConstants.MAXLENGTH_EMAIL);\n\n getJspBody().invoke(null);\n }\n}\n <tag>\n <name>fieldAttributes</name>\n <tag-class>package.path.JspFieldAttributes</tag-class>\n <body-content>scriptless</body-content>\n <info>This tag provide HTML field attributes that CCS is unable to do.</info>\n</tag>\n <%@ taglib uri=\"/WEB-INF/tags/StringHelper.tld\" prefix=\"stringHelper\" %>\n <stringHelper:fieldAttributes>\n[snip]\n <form:input path=\"emailAddress\" cssClass=\"formeffect\" cssErrorClass=\"formEffect error\" maxlength=\"**${maxlength_email}**\"/> \n <form:errors path=\"emailAddress\" cssClass=\"error\" element=\"span\"/>\n[snip]\n </stringHelper:fieldAttributes>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
122,267
|
<p>(using the IMAP commands, not with the assistance of any other mail package)</p>
|
[
{
"answer_id": 122296,
"author": "Sec",
"author_id": 20555,
"author_profile": "https://Stackoverflow.com/users/20555",
"pm_score": 5,
"selected": true,
"text": "a login a s\nb select source\nc copy 1 othermbox\nd store 1 +flags (\\Deleted)\ne expunge\n"
},
{
"answer_id": 3156528,
"author": "Avadhesh",
"author_id": 365148,
"author_profile": "https://Stackoverflow.com/users/365148",
"pm_score": 4,
"selected": false,
"text": "import imaplib\n\nobj = imaplib.IMAP4_SSL('imap.gmail.com', 993)\nobj.login('username', 'password')\nobj.select(src_folder_name)\napply_lbl_msg = obj.uid('COPY', msg_uid, desti_folder_name)\nif apply_lbl_msg[0] == 'OK':\n mov, data = obj.uid('STORE', msg_uid , '+FLAGS', '(\\Deleted)')\n obj.expunge()\n"
},
{
"answer_id": 15816045,
"author": "Jan Kundrát",
"author_id": 2245623,
"author_profile": "https://Stackoverflow.com/users/2245623",
"pm_score": 5,
"selected": false,
"text": "UID MOVE C: a UID MOVE 42:69 foo\nS: * OK [COPYUID 432432 42:69 1202:1229]\nS: * 22 EXPUNGE\nS: (more expunges)\nS: a OK Done\n MOVE UIDPLUS UID STORE UID COPY UID EXPUNGE C: a01 UID COPY 42:69 foo\nS: a01 OK [COPYUID 432432 42:69 1202:1229] Copied\nC: a02 UID STORE 42:69 +FLAGS.SILENT (\\Deleted)\nS: a02 OK Stored\nC: a03 UID EXPUNGE 42:69\nS: * 10 EXPUNGE\nS: * 10 EXPUNGE\nS: * 10 EXPUNGE\nS: a03 Expunged\n UIDPLUS EXPUNGE UID COPY UID STORE"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
122,271
|
<p>when putting a ScrollViewer inside a window(not keeping all the window's size)
inside the ScrollViewer there's (with other stuff) a WinFormsHost and a control inside (let's say a DateTimePicker). when scrolling, the inner winforms control keeps being visible when there's no longer a reason (it's outside of the scrolling region), so it "floats" above what's outside of the ScrollViewer</p>
<p>any solutions for that?</p>
|
[
{
"answer_id": 2638614,
"author": "Kamilos",
"author_id": 177156,
"author_profile": "https://Stackoverflow.com/users/177156",
"pm_score": -1,
"selected": false,
"text": "VerticalScrollBarVisibility=\"Auto\"\n"
},
{
"answer_id": 40342629,
"author": "Ron16",
"author_id": 3061428,
"author_profile": "https://Stackoverflow.com/users/3061428",
"pm_score": 2,
"selected": false,
"text": "class WindowsFormsHostEx : WindowsFormsHost\n {\n private PresentationSource _presentationSource;\n\n public WindowsFormsHostEx()\n {\n PresentationSource.AddSourceChangedHandler(this, SourceChangedEventHandler);\n }\n\n protected override void OnWindowPositionChanged(Rect rcBoundingBox)\n {\n base.OnWindowPositionChanged(rcBoundingBox);\n\n ParentScrollViewer.ScrollChanged += ParentScrollViewer_ScrollChanged;\n ParentScrollViewer.SizeChanged += ParentScrollViewer_SizeChanged;\n ParentScrollViewer.Loaded += ParentScrollViewer_Loaded;\n\n if (Scrolling || Resizing)\n {\n if (ParentScrollViewer == null)\n return;\n GeneralTransform tr = RootVisual.TransformToDescendant(ParentScrollViewer);\n var scrollRect = new Rect(new Size(ParentScrollViewer.ViewportWidth, ParentScrollViewer.ViewportHeight));\n\n var intersect = Rect.Intersect(scrollRect, tr.TransformBounds(rcBoundingBox));\n if (!intersect.IsEmpty)\n {\n tr = ParentScrollViewer.TransformToDescendant(this);\n intersect = tr.TransformBounds(intersect);\n }\n else\n intersect = new Rect();\n\n int x1 = (int)Math.Round(intersect.Left);\n int y1 = (int)Math.Round(intersect.Top);\n int x2 = (int)Math.Round(intersect.Right);\n int y2 = (int)Math.Round(intersect.Bottom);\n\n SetRegion(x1, y1, x2, y2);\n this.Scrolling = false;\n this.Resizing = false;\n\n }\n\n }\n\n private void ParentScrollViewer_Loaded(object sender, RoutedEventArgs e)\n {\n this.Resizing = true;\n }\n\n private void ParentScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)\n {\n this.Resizing = true;\n }\n\n private void ParentScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)\n {\n if (e.VerticalChange != 0 || e.HorizontalChange != 0 || e.ExtentHeightChange != 0 || e.ExtentWidthChange != 0)\n Scrolling = true;\n }\n\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n\n if (disposing)\n PresentationSource.RemoveSourceChangedHandler(this, SourceChangedEventHandler);\n }\n\n private void SourceChangedEventHandler(Object sender, SourceChangedEventArgs e)\n {\n ParentScrollViewer = FindParentScrollViewer();\n }\n\n private ScrollViewer FindParentScrollViewer()\n {\n DependencyObject vParent = this;\n ScrollViewer parentScroll = null;\n while (vParent != null)\n {\n parentScroll = vParent as ScrollViewer;\n if (parentScroll != null)\n break;\n\n vParent = LogicalTreeHelper.GetParent(vParent);\n }\n return parentScroll;\n }\n\n private void SetRegion(int x1, int y1, int x2, int y2)\n {\n SetWindowRgn(Handle, CreateRectRgn(x1, y1, x2, y2), true);\n }\n\n private Visual RootVisual\n {\n get\n {\n _presentationSource = PresentationSource.FromVisual(this);\n return _presentationSource.RootVisual;\n }\n }\n\n private ScrollViewer ParentScrollViewer { get; set; }\n\n private bool Scrolling { get; set; }\n private bool Resizing { get; set; }\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);\n\n [DllImport(\"gdi32.dll\")]\n static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);\n }\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21243/"
] |
122,273
|
<p>Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container? </p>
<p>I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.</p>
|
[
{
"answer_id": 122361,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 5,
"selected": true,
"text": "public ProductController() : this( new Foo() )\n{\n //the framework calls this\n}\n\npublic ProductController(IFoo foo)\n{\n _foo = foo;\n}\n"
},
{
"answer_id": 126905,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 4,
"selected": false,
"text": "public class MyControllerFactory : DefaultControllerFactory\n{\n public override IController CreateController(\n RequestContext requestContext, string controllerName)\n {\n return [construct your controller here] ;\n }\n}\n private void Application_Start(object sender, EventArgs e)\n {\n RegisterRoutes(RouteTable.Routes);\n ControllerBuilder.Current.SetControllerFactory(\n new MyNamespace.MyControllerFactory());\n }\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17902/"
] |
122,276
|
<p>I want to be able to quickly check whether I both have sudo access and my password is already authenticated. I'm not worried about having sudo access specifically for the operation I'm about to perform, but that would be a nice bonus.</p>
<p>Specifically what I'm trying to use this for is a script that I want to be runnable by a range of users. Some have sudo access. All know the root password.</p>
<p>When they run my script, I want it to use sudo permissions without prompting for a password if that is possible, and otherwise to fall back to asking for the <em>root</em> password (because they might not have sudo access).</p>
<p>My first non-working attempt was to fork off <code>sudo -S true</code> with STDIN closed or reading from /dev/null. But that still prompts for the password and waits a couple of seconds.</p>
<p>I've tried several other things, including waiting 0.3sec to see whether it succeeded immediately, but everything I try ends up failing in some situation. (And not because my timeout is too short.) It's difficult to figure out what goes on, because I can't just strace like I normally would.</p>
<p>One thing I <em>know</em> doesn't work is to close STDIN or attach it to a pipe before running <code>sudo -S true</code>. I was hoping that would make the password prompt immediately fail, but it still prompts and behaves strangely. I think it might want a terminal.</p>
|
[
{
"answer_id": 122329,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": -1,
"selected": false,
"text": "getent group admin | grep $particular_user\n"
},
{
"answer_id": 1677127,
"author": "bobomastoras",
"author_id": 203020,
"author_profile": "https://Stackoverflow.com/users/203020",
"pm_score": 0,
"selected": false,
"text": "sudo -S true < /dev/null &>/dev/null\n"
},
{
"answer_id": 22311192,
"author": "Dennis Williamson",
"author_id": 26428,
"author_profile": "https://Stackoverflow.com/users/26428",
"pm_score": 3,
"selected": true,
"text": "sudo sudo -n true\n true"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14528/"
] |
122,277
|
<p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
|
[
{
"answer_id": 122294,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 4,
"selected": false,
"text": "r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<data>.+)')\n\ndef do_foo(data):\n ...\n\ndef do_bar(data):\n ...\n\ndef do_baz(data):\n ...\n\ndispatch = {\n 'foo': do_foo,\n 'bar': do_bar,\n 'baz': do_baz,\n}\n\n\nm = r.match(var)\nif m:\n dispatch[m.group('cmd')](m.group('data'))\n"
},
{
"answer_id": 122345,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 2,
"selected": false,
"text": "prefix, data = var[:3], var[3:]\nif prefix == 'foo':\n # do something with data\nelif prefix == 'bar':\n # do something with data\nelif prefix == 'baz':\n # do something with data\nelse:\n # do something with var\n"
},
{
"answer_id": 122364,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "def find_first_match(string, *regexes):\n for regex, handler in regexes:\n m = re.search(regex, string):\n if m:\n handler(m)\n return\n else:\n raise ValueError\n\nfind_first_match(\n foo, \n (r'foo(.+)', handle_foo), \n (r'bar(.+)', handle_bar), \n (r'baz(.+)', handle_baz))\n"
},
{
"answer_id": 123083,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 3,
"selected": false,
"text": "\nimport re\n\nclass ReCheck(object):\n def __init__(self):\n self.result = None\n def check(self, pattern, text):\n self.result = re.search(pattern, text)\n return self.result\n\nvar = 'bar stuff'\nm = ReCheck()\nif m.check(r'foo(.+)',var):\n print m.result.group(1)\nelif m.check(r'bar(.+)',var):\n print m.result.group(1)\nelif m.check(r'baz(.+)',var):\n print m.result.group(1)\n"
},
{
"answer_id": 124128,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 3,
"selected": false,
"text": "import re\nvar = \"barbazfoo\"\n\nm = re.search(r'(foo|bar|baz)(.+)', var)\nif m.group(1) == 'foo':\n print m.group(1)\n # do something with m.group(1)\nelif m.group(1) == \"bar\":\n print m.group(1)\n # do something with m.group(1)\nelif m.group(1) == \"baz\":\n print m.group(2)\n # do something with m.group(2)\n"
},
{
"answer_id": 135720,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "r\"\"\"\nThis is an extension of the re module. It stores the last successful\nmatch object and lets you access it's methods and attributes via\nthis module.\n\nThis module exports the following additional functions:\n expand Return the string obtained by doing backslash substitution on a\n template string.\n group Returns one or more subgroups of the match.\n groups Return a tuple containing all the subgroups of the match.\n start Return the indices of the start of the substring matched by\n group.\n end Return the indices of the end of the substring matched by group.\n span Returns a 2-tuple of (start(), end()) of the substring matched\n by group.\n\nThis module defines the following additional public attributes:\n pos The value of pos which was passed to the search() or match()\n method.\n endpos The value of endpos which was passed to the search() or\n match() method.\n lastindex The integer index of the last matched capturing group.\n lastgroup The name of the last matched capturing group.\n re The regular expression object which as passed to search() or\n match().\n string The string passed to match() or search().\n\"\"\"\n\nimport re as re_\n\nfrom re import *\nfrom functools import wraps\n\n__all__ = re_.__all__ + [ \"expand\", \"group\", \"groups\", \"start\", \"end\", \"span\",\n \"last_match\", \"pos\", \"endpos\", \"lastindex\", \"lastgroup\", \"re\", \"string\" ]\n\nlast_match = pos = endpos = lastindex = lastgroup = re = string = None\n\ndef _set_match(match=None):\n global last_match, pos, endpos, lastindex, lastgroup, re, string\n if match is not None:\n last_match = match\n pos = match.pos\n endpos = match.endpos\n lastindex = match.lastindex\n lastgroup = match.lastgroup\n re = match.re\n string = match.string\n return match\n\n@wraps(re_.match)\ndef match(pattern, string, flags=0):\n return _set_match(re_.match(pattern, string, flags))\n\n\n@wraps(re_.search)\ndef search(pattern, string, flags=0):\n return _set_match(re_.search(pattern, string, flags))\n\n@wraps(re_.findall)\ndef findall(pattern, string, flags=0):\n matches = re_.findall(pattern, string, flags)\n if matches:\n _set_match(matches[-1])\n return matches\n\n@wraps(re_.finditer)\ndef finditer(pattern, string, flags=0):\n for match in re_.finditer(pattern, string, flags):\n yield _set_match(match)\n\ndef expand(template):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.expand(template)\n\ndef group(*indices):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.group(*indices)\n\ndef groups(default=None):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.groups(default)\n\ndef groupdict(default=None):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.groupdict(default)\n\ndef start(group=0):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.start(group)\n\ndef end(group=0):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.end(group)\n\ndef span(group=0):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.span(group)\n\ndel wraps # Not needed past module compilation\n if gre.match(\"foo(.+)\", var):\n # do something with gre.group(1)\nelif gre.match(\"bar(.+)\", var):\n # do something with gre.group(1)\nelif gre.match(\"baz(.+)\", var):\n # do something with gre.group(1)\n"
},
{
"answer_id": 1806345,
"author": "Craig McQueen",
"author_id": 60075,
"author_profile": "https://Stackoverflow.com/users/60075",
"pm_score": 3,
"selected": false,
"text": "import re\n\nclass DataHolder:\n def __init__(self, value=None, attr_name='value'):\n self._attr_name = attr_name\n self.set(value)\n def __call__(self, value):\n return self.set(value)\n def set(self, value):\n setattr(self, self._attr_name, value)\n return value\n def get(self):\n return getattr(self, self._attr_name)\n\nstring = u'test bar 123'\nsave_match = DataHolder(attr_name='match')\nif save_match(re.search('foo (\\d+)', string)):\n print \"Foo\"\n print save_match.match.group(1)\nelif save_match(re.search('bar (\\d+)', string)):\n print \"Bar\"\n print save_match.match.group(1)\nelif save_match(re.search('baz (\\d+)', string)):\n print \"Baz\"\n print save_match.match.group(1)\n"
},
{
"answer_id": 2021009,
"author": "Daniel Bingham",
"author_id": 156678,
"author_profile": "https://Stackoverflow.com/users/156678",
"pm_score": 2,
"selected": false,
"text": "matched = False;\n\nm = re.match(\"regex1\");\nif not matched and m:\n #do something\n matched = True;\n\nm = re.match(\"regex2\");\nif not matched and m:\n #do something else\n matched = True;\n\nm = re.match(\"regex3\");\nif not matched and m:\n #do yet something else\n matched = True;\n"
},
{
"answer_id": 4195819,
"author": "Matus",
"author_id": 477800,
"author_profile": "https://Stackoverflow.com/users/477800",
"pm_score": 1,
"selected": false,
"text": "match_objects = {}\n\nif match_objects.setdefault( 'mo_foo', re_foo.search( text ) ):\n # do something with match_objects[ 'mo_foo' ]\n\nelif match_objects.setdefault( 'mo_bar', re_bar.search( text ) ):\n # do something with match_objects[ 'mo_bar' ]\n\nelif match_objects.setdefault( 'mo_baz', re_baz.search( text ) ):\n # do something with match_objects[ 'mo_baz' ]\n\n...\n"
},
{
"answer_id": 30799800,
"author": "Mike Robins",
"author_id": 5002578,
"author_profile": "https://Stackoverflow.com/users/5002578",
"pm_score": 0,
"selected": false,
"text": "import re\n\nclass Found(Exception): pass\n\ntry: \n for m in re.finditer('bar(.+)', var):\n # Do something\n raise Found\n\n for m in re.finditer('foo(.+)', var):\n # Do something else\n raise Found\n\nexcept Found: pass\n"
},
{
"answer_id": 38849153,
"author": "Yirkha",
"author_id": 3543211,
"author_profile": "https://Stackoverflow.com/users/3543211",
"pm_score": 1,
"selected": false,
"text": "re search() check() group() class Re(object):\n def __init__(self):\n self.result = None\n\n def search(self, pattern, text):\n self.result = re.search(pattern, text)\n return self.result\n\n def group(self, index):\n return self.result.group(index)\n m = re.search(r'set ([^ ]+) to ([^ ]+)', line)\nif m:\n vars[m.group(1)] = m.group(2)\nelse:\n m = re.search(r'print ([^ ]+)', line)\n if m:\n print(vars[m.group(1)])\n else:\n m = re.search(r'add ([^ ]+) to ([^ ]+)', line)\n if m:\n vars[m.group(2)] += vars[m.group(1)]\n m = Re()\n...\nif m.search(r'set ([^ ]+) to ([^ ]+)', line):\n vars[m.group(1)] = m.group(2)\nelif m.search(r'print ([^ ]+)', line):\n print(vars[m.group(1)])\nelif m.search(r'add ([^ ]+) to ([^ ]+)', line):\n vars[m.group(2)] += vars[m.group(1)]\n"
},
{
"answer_id": 44837090,
"author": "Mike Robins",
"author_id": 5002578,
"author_profile": "https://Stackoverflow.com/users/5002578",
"pm_score": 1,
"selected": false,
"text": "class Holder(object):\n def __call__(self, *x):\n if x:\n self.x = x[0]\n return self.x\n\ndata = Holder()\n\nif data(re.search('foo (\\d+)', string)):\n print data().group(1)\n def data(*x):\n if x:\n data.x = x[0]\n return data.x\n"
},
{
"answer_id": 45798441,
"author": "Jim Arlow",
"author_id": 8495441,
"author_profile": "https://Stackoverflow.com/users/8495441",
"pm_score": 0,
"selected": false,
"text": "def plus(self, regex: r\"\\+\", **kwargs):\n...\n import inspect\nimport re\n\n\nclass RegexMethod:\n def __init__(self, method, annotation):\n self.method = method\n self.name = self.method.__name__\n self.order = inspect.getsourcelines(self.method)[1] # The line in the source file\n self.regex = self.method.__annotations__[annotation]\n\n def match(self, s):\n return re.match(self.regex, s)\n\n # Make it callable\n def __call__(self, *args, **kwargs):\n return self.method(*args, **kwargs)\n\n def __str__(self):\n return str.format(\"Line: %s, method name: %s, regex: %s\" % (self.order, self.name, self.regex))\n\n\nclass RegexDispatcher:\n def __init__(self, annotation=\"regex\"):\n self.annotation = annotation\n # Collect all the methods that have an annotation that matches self.annotation\n # For example, methods that have the annotation \"regex\", which is the default\n self.dispatchMethods = [RegexMethod(m[1], self.annotation) for m in\n inspect.getmembers(self, predicate=inspect.ismethod) if\n (self.annotation in m[1].__annotations__)]\n # Be sure to process the dispatch methods in the order they appear in the class!\n # This is because the order in which you test regexes is important.\n # The most specific patterns must always be tested BEFORE more general ones\n # otherwise they will never match.\n self.dispatchMethods.sort(key=lambda m: m.order)\n\n # Finds the FIRST match of s against a RegexMethod in dispatchMethods, calls the RegexMethod and returns\n def dispatch(self, s, **kwargs):\n for m in self.dispatchMethods:\n if m.match(s):\n return m(self.annotation, **kwargs)\n return None\n from RegexDispatcher import *\nimport math\n\nclass RPNCalculator(RegexDispatcher):\n def __init__(self):\n RegexDispatcher.__init__(self)\n self.stack = []\n\n def __str__(self):\n return str(self.stack)\n\n # Make RPNCalculator objects callable\n def __call__(self, expression):\n # Calculate the value of expression\n for t in expression.split():\n self.dispatch(t, token=t)\n return self.top() # return the top of the stack\n\n # Stack management\n def top(self):\n return self.stack[-1] if len(self.stack) > 0 else []\n\n def push(self, x):\n return self.stack.append(float(x))\n\n def pop(self, n=1):\n return self.stack.pop() if n == 1 else [self.stack.pop() for n in range(n)]\n\n # Handle numbers\n def number(self, regex: r\"[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?\", **kwargs):\n self.stack.append(float(kwargs['token']))\n\n # Binary operators\n def plus(self, regex: r\"\\+\", **kwargs):\n a, b = self.pop(2)\n self.push(b + a)\n\n def minus(self, regex: r\"\\-\", **kwargs):\n a, b = self.pop(2)\n self.push(b - a)\n\n def multiply(self, regex: r\"\\*\", **kwargs):\n a, b = self.pop(2)\n self.push(b * a)\n\n def divide(self, regex: r\"\\/\", **kwargs):\n a, b = self.pop(2)\n self.push(b / a)\n\n def pow(self, regex: r\"exp\", **kwargs):\n a, b = self.pop(2)\n self.push(a ** b)\n\n def logN(self, regex: r\"logN\", **kwargs):\n a, b = self.pop(2)\n self.push(math.log(a,b))\n\n # Unary operators\n def neg(self, regex: r\"neg\", **kwargs):\n self.push(-self.pop())\n\n def sqrt(self, regex: r\"sqrt\", **kwargs):\n self.push(math.sqrt(self.pop()))\n\n def log2(self, regex: r\"log2\", **kwargs):\n self.push(math.log2(self.pop()))\n\n def log10(self, regex: r\"log10\", **kwargs):\n self.push(math.log10(self.pop()))\n\n def pi(self, regex: r\"pi\", **kwargs):\n self.push(math.pi)\n\n def e(self, regex: r\"e\", **kwargs):\n self.push(math.e)\n\n def deg(self, regex: r\"deg\", **kwargs):\n self.push(math.degrees(self.pop()))\n\n def rad(self, regex: r\"rad\", **kwargs):\n self.push(math.radians(self.pop()))\n\n # Whole stack operators\n def cls(self, regex: r\"c\", **kwargs):\n self.stack=[]\n\n def sum(self, regex: r\"sum\", **kwargs):\n self.stack=[math.fsum(self.stack)]\n\n\nif __name__ == '__main__':\n calc = RPNCalculator()\n\n print(calc('2 2 exp 3 + neg'))\n\n print(calc('c 1 2 3 4 5 sum 2 * 2 / pi'))\n\n print(calc('pi 2 * deg'))\n\n print(calc('2 2 logN'))\n"
},
{
"answer_id": 55887489,
"author": "Xavier Guihot",
"author_id": 9297144,
"author_profile": "https://Stackoverflow.com/users/9297144",
"pm_score": 4,
"selected": true,
"text": "Python 3.8 := re.search(pattern, text) match None if match := re.search(r'foo(.+)', text):\n # do something with match.group(1)\nelif match := re.search(r'bar(.+)', text):\n # do something with match.group(1)\nelif match := re.search(r'baz(.+)', text)\n # do something with match.group(1)\n"
},
{
"answer_id": 59789328,
"author": "joe-purl",
"author_id": 562210,
"author_profile": "https://Stackoverflow.com/users/562210",
"pm_score": 0,
"selected": false,
"text": "import re\n\ns = '1.23 Million equals to 1230000'\n\ns = re.sub(\"([\\d.]+)(\\s*)Million\", lambda m: str(round(float(m.groups()[0]) * 1000_000))+m.groups()[1], s)\n\nprint(s)\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20789/"
] |
122,301
|
<p>Is there an easy way to get a conflict summary after running a <code>cvs update</code>? </p>
<p>I work on a large project and after doing some work I need to do an update. The list of changes coming back from the cvs update command is several pages long and I'd like to see only the list of conflicts (starts with 'C') repeated at the end of the cvs update command output.</p>
<p>The solution needs to work from the command line.</p>
<p>If my normal output is:</p>
<pre><code>M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
</code></pre>
<p>I want my new output to be:</p>
<pre><code>M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
Conflict Summary:
C src/file3.txt
</code></pre>
<p>I want this to be a single command (possibly a short script or alias) that outputs the normal cvs output as it happens followed by a summary of conflicts.</p>
|
[
{
"answer_id": 169551,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": true,
"text": "tmp=${TMPDIR:-/tmp}/cvsupd.$$\ntrap \"rm -f $tmp; exit 1\" 0 1 2 3 13 15\ncvs update \"$@\" | tee $tmp\nif grep -s '^C' $tmp\nthen\n echo\n echo Conflict Summary:\n grep '^C' $tmp\nfi\nrm -f $tmp\ntrap 0\nexit 0\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] |
122,302
|
<p>According to select name from system_privilege_map System has been granted:</p>
<pre><code>SELECT ANY TABLE
</code></pre>
<p>...and lots of other * ANY TABLES.</p>
<p>Plainly running</p>
<pre><code>select * from the_table;
select * from the_table;
</code></pre>
<p>...nets the given response:</p>
<blockquote>
<p>ERROR at line 1:
ORA-00942: table or view does not exist</p>
</blockquote>
<p>I can log in as that user and run the same command just fine.</p>
<p>I'm running under the assumption I should be able to run queries (select in this case) agaisnt a general user's DB table. Is my assumption correct, and if so, how do I do it?</p>
|
[
{
"answer_id": 122309,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": true,
"text": "select * from some_user.the_table;\n"
},
{
"answer_id": 122310,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM schema_name.the_table;\n CREATE SYNONYM the_table FOR schema_name.the_table;\n"
},
{
"answer_id": 233552,
"author": "Gazmo",
"author_id": 31175,
"author_profile": "https://Stackoverflow.com/users/31175",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM schema_name.the_table;\n CREATE (PUBLIC) SYNONYM the_table FOR schema_name.the_table;\n ALTER SESSION SET current_schema=schema_name;\n schema_name SET current_schema"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
122,313
|
<p>I'm getting confused with the include/exclude jargon, and my actual SVN client doesn't seem to have (or I've been unable to find it easily) a simple option to add or remove a certain type of files for version control.</p>
<p>Let's say for example I've added the entire Visual Studio folder, with its solutions, projects, debug files, etc., but I only want to version the actual source files. What would be the simplest way to do that?</p>
|
[
{
"answer_id": 122330,
"author": "Max Cantor",
"author_id": 16034,
"author_profile": "https://Stackoverflow.com/users/16034",
"pm_score": 3,
"selected": false,
"text": "~/.subversion/config svn propset svn propedit ~/.subversion/config [miscellany]"
},
{
"answer_id": 122331,
"author": "Prody",
"author_id": 21240,
"author_profile": "https://Stackoverflow.com/users/21240",
"pm_score": 1,
"selected": false,
"text": "svn:ignore"
},
{
"answer_id": 122335,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": true,
"text": "svn propedit svn:ignore .\n *.user\n*.exe\n*.dll\n global-ignores \"%APPDATA%\\Subversion\\config\" # ### Set global-ignores to a set of whitespace-delimited globs\n### which Subversion will ignore in its 'status' output, and\n### while importing or adding files and directories.\n# global-ignores = *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store\nglobal-ignores = Ankh.Load *.resharper.user\n"
},
{
"answer_id": 70987353,
"author": "mwarren",
"author_id": 1617550,
"author_profile": "https://Stackoverflow.com/users/1617550",
"pm_score": 0,
"selected": false,
"text": "Preferences > Team > Ignored Resources\n Add Pattern"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
122,316
|
<p>In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:</p>
<pre><code>interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main(string[] args)
{
Foo<Bar> a = new Foo<Bar>();
Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
}
}
</code></pre>
<p>Is there a way we can impose constraints for template parameters in C++.</p>
<hr>
<p>C++0x has native support for this but I am talking about current standard C++.</p>
|
[
{
"answer_id": 122386,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 6,
"selected": false,
"text": "template <class T>\nint compute_length(T *value)\n{\n return value->length();\n}\n length() int string s = \"test\";\nvector<int> vec;\nint i = 0;\n\ncompute_length(&s);\ncompute_length(&vec);\n length() compute_length(&i);\n int* length()"
},
{
"answer_id": 122406,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 4,
"selected": false,
"text": "class IFoo\n{\npublic:\n typedef int IsDerivedFromIFoo;\n};\n\ntemplate <typename T>\nclass Foo<T>\n{\n typedef typename T::IsDerivedFromIFoo IFooGuard;\n}\n"
},
{
"answer_id": 152742,
"author": "OldMan",
"author_id": 23415,
"author_profile": "https://Stackoverflow.com/users/23415",
"pm_score": 2,
"selected": false,
"text": "template<class t> class FOO { private: FOO(){}};\n\ntemplate<> class FOO<int>{public: FOO(){}};\n\ntemplate<> class FOO<float>{public: FOO(){}};\n"
},
{
"answer_id": 22934960,
"author": "Venemo",
"author_id": 202919,
"author_profile": "https://Stackoverflow.com/users/202919",
"pm_score": 6,
"selected": false,
"text": "static_assert std::is_base_of #include <type_traits>\n\ntemplate<typename T>\nclass YourClass {\n\n YourClass() {\n // Compile-time check\n static_assert(std::is_base_of<BaseClass, T>::value, \"type parameter of this class must derive from BaseClass\");\n\n // ...\n }\n}\n"
},
{
"answer_id": 71100711,
"author": "Hugo",
"author_id": 7261360,
"author_profile": "https://Stackoverflow.com/users/7261360",
"pm_score": 2,
"selected": false,
"text": "#include <concepts>\n\ntemplate<class T, class U>\nconcept Derived = std::is_base_of<U, T>::value;\n\nclass ABase { };\nclass ADerived : ABase { };\n\ntemplate<Derived<ABase> T>\nclass AClass {\n T aMemberDerivedFromABase;\n};\n int main () {\n AClass<ADerived> aClass;\n return 0;\n}\n class AnotherClass {\n\n};\nint main () {\n AClass<AnotherClass> aClass;\n return 0;\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6508/"
] |
122,327
|
<p>How do I find the location of my <code>site-packages</code> directory?</p>
|
[
{
"answer_id": 122340,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 9,
"selected": false,
"text": "python -c \"from distutils.sysconfig import get_python_lib; print(get_python_lib())\"\n from distutils.sysconfig import get_python_lib\nprint(get_python_lib())\n"
},
{
"answer_id": 122360,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 3,
"selected": false,
"text": "from distutils.sysconfig import get_python_lib\nprint get_python_lib()\n"
},
{
"answer_id": 122377,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 5,
"selected": false,
"text": "distutils.sysconfig import distutils.sysconfig\nprint distutils.sysconfig.get_python_lib()\n site.py import sys, os\nprint os.sep.join([sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages'])\n ${sys.prefix}/lib/site-python sys.exec_prefix site-packages"
},
{
"answer_id": 122387,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": false,
"text": "get_python_lib plat_specific=True"
},
{
"answer_id": 1711808,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "distutils.sysconfig.get_python_lib()"
},
{
"answer_id": 4611382,
"author": "David Hollander",
"author_id": 564833,
"author_profile": "https://Stackoverflow.com/users/564833",
"pm_score": 7,
"selected": false,
"text": "python -c \"from distutils.sysconfig import get_python_lib; print get_python_lib()\"\n /usr/lib/pythonX.X/dist-packages /usr/local/lib/pythonX.X/dist-packages"
},
{
"answer_id": 5095375,
"author": "Sumod",
"author_id": 418832,
"author_profile": "https://Stackoverflow.com/users/418832",
"pm_score": 5,
"selected": false,
"text": ">>> import django\n>>> dir(django)\n['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']\n>>> print django.__path__\n['/Library/Python/2.6/site-packages/django']\n"
},
{
"answer_id": 9155056,
"author": "cheater",
"author_id": 389169,
"author_profile": "https://Stackoverflow.com/users/389169",
"pm_score": 4,
"selected": false,
"text": "from setuptools.command.easy_install import easy_install\nclass easy_install_default(easy_install):\n \"\"\" class easy_install had problems with the fist parameter not being\n an instance of Distribution, even though it was. This is due to\n some import-related mess.\n \"\"\"\n\n def __init__(self):\n from distutils.dist import Distribution\n dist = Distribution()\n self.distribution = dist\n self.initialize_options()\n self._dry_run = None\n self.verbose = dist.verbose\n self.force = None\n self.help = 0\n self.finalized = 0\n\ne = easy_install_default()\nimport distutils.errors\ntry:\n e.finalize_options()\nexcept distutils.errors.DistutilsError:\n pass\n\nprint e.install_dir\n"
},
{
"answer_id": 9946505,
"author": "just_an_old_guy",
"author_id": 1303682,
"author_profile": "https://Stackoverflow.com/users/1303682",
"pm_score": 4,
"selected": false,
"text": "import sys; \nprint [f for f in sys.path if f.endswith('packages')]\n ['/home/username/.local/lib/python2.7/site-packages',\n '/usr/local/lib/python2.7/dist-packages',\n '/usr/lib/python2.7/dist-packages']\n"
},
{
"answer_id": 10694208,
"author": "Ramashri",
"author_id": 1409043,
"author_profile": "https://Stackoverflow.com/users/1409043",
"pm_score": 6,
"selected": false,
"text": "python -m site --user-site\n"
},
{
"answer_id": 12950101,
"author": "eudoxos",
"author_id": 761090,
"author_profile": "https://Stackoverflow.com/users/761090",
"pm_score": 9,
"selected": false,
"text": ">>> import site; site.getsitepackages()\n['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']\n site.getsitepackages()[0]"
},
{
"answer_id": 18130809,
"author": "fnatic_shank",
"author_id": 1062108,
"author_profile": "https://Stackoverflow.com/users/1062108",
"pm_score": 5,
"selected": false,
"text": "/Library/Python/2.7/site-packages from distutils.sysconfig import get_python_lib\nprint get_python_lib()\n pip >>> import site; site.getsitepackages()\n['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']\n >>> import site; site.getsitepackages()\n['/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']\n"
},
{
"answer_id": 29062571,
"author": "Pyramid Newbie",
"author_id": 1258009,
"author_profile": "https://Stackoverflow.com/users/1258009",
"pm_score": 4,
"selected": false,
"text": "import os; print(os.path.dirname(os.__file__) + '/site-packages')\n alias cdsp='cd $(python -c \"import os; print(os.path.dirname(os.__file__))\"); cd site-packages'\n"
},
{
"answer_id": 38432782,
"author": "Sahil Agarwal",
"author_id": 6003362,
"author_profile": "https://Stackoverflow.com/users/6003362",
"pm_score": 3,
"selected": false,
"text": "pip install ipython\nipython \nimport imaplib\nimaplib?\n Type: module\nString form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>\nFile: /usr/lib/python2.7/imaplib.py\nDocstring: \nIMAP4 client.\n\nBased on RFC 2060.\n\nPublic class: IMAP4\nPublic variable: Debug\nPublic functions: Internaldate2tuple\n Int2AP\n ParseFlags\n Time2Internaldate\n"
},
{
"answer_id": 46071447,
"author": "Peterino",
"author_id": 202834,
"author_profile": "https://Stackoverflow.com/users/202834",
"pm_score": 11,
"selected": true,
"text": "sys.path python -m site\n getsitepackages python -c 'import site; print(site.getsitepackages())'\n virtualenv sys.path python3 -c 'import sysconfig; print(sysconfig.get_paths()[\"purelib\"])'\n python -m site --user-site\n python -m site --help pip list --user pip freeze --user <package>.__path__ $ python -c \"import setuptools as _; print(_.__path__)\"\n ['/usr/lib/python2.7/dist-packages/setuptools']\n <module>.__file__ $ python3 -c \"import os as _; print(_.__file__)\"\n /usr/lib/python3.6/os.py\n pip show <package> $ pip show pytest\n Name: pytest\n Version: 3.8.2\n Summary: pytest: simple powerful testing with Python\n Home-page: https://docs.pytest.org/en/latest/\n Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others\n Author-email: None\n License: MIT license\n Location: /home/peter/.local/lib/python3.4/site-packages\n Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy\n"
},
{
"answer_id": 47844391,
"author": "MultipleMonomials",
"author_id": 7083698,
"author_profile": "https://Stackoverflow.com/users/7083698",
"pm_score": 2,
"selected": false,
"text": "/usr/lib/python2.7/site-packages /lib/python2.7/site-packages site-packages /usr/lib64 setup.py import sys\nimport os\nfrom distutils.command.install import INSTALL_SCHEMES\n\nif os.name == 'nt':\n scheme_key = 'nt'\nelse:\n scheme_key = 'unix_prefix'\n\nprint(INSTALL_SCHEMES[scheme_key]['purelib'].replace('$py_version_short', (str.split(sys.version))[0][0:3]).replace('$base', ''))\n /Lib/site-packages /lib/python3.6/site-packages"
},
{
"answer_id": 52638888,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 6,
"selected": false,
"text": "sysconfig sysconfig distutils.sysconfig get_paths distutils pip # Linux\n$ python3 -c \"import sysconfig; print(sysconfig.get_path('purelib'))\"\n/usr/local/lib/python3.8/site-packages\n\n# macOS (brew installed python3.8)\n$ python3 -c \"import sysconfig; print(sysconfig.get_path('purelib'))\"\n/usr/local/Cellar/python@3.8/3.8.3/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages\n\n# Windows\nC:\\> py -c \"import sysconfig; print(sysconfig.get_path('purelib'))\"\nC:\\Users\\wim\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\n # Linux\n/tmp/.venv/lib/python3.8/site-packages\n\n# macOS\n/private/tmp/.venv/lib/python3.8/site-packages\n\n# Windows\nC:\\Users\\wim\\AppData\\Local\\Temp\\.venv\\Lib\\site-packages\n sysconfig.get_paths() >>> import sysconfig\n>>> sysconfig.get_paths()\n{'stdlib': '/usr/local/lib/python3.8',\n 'platstdlib': '/usr/local/lib/python3.8',\n 'purelib': '/usr/local/lib/python3.8/site-packages',\n 'platlib': '/usr/local/lib/python3.8/site-packages',\n 'include': '/usr/local/include/python3.8',\n 'platinclude': '/usr/local/include/python3.8',\n 'scripts': '/usr/local/bin',\n 'data': '/usr/local'}\n sysconfig python -m sysconfig\n root@cb5e85f17c7f:/# python3 -m sysconfig | grep packages\n platlib = \"/usr/lib/python3.8/site-packages\"\n purelib = \"/usr/lib/python3.8/site-packages\"\n\nroot@cb5e85f17c7f:/# python3 -m site | grep packages\n '/usr/local/lib/python3.8/dist-packages',\n '/usr/lib/python3/dist-packages',\nUSER_SITE: '/root/.local/lib/python3.8/site-packages' (doesn't exist)\n"
},
{
"answer_id": 54019959,
"author": "Sourabh Potnis",
"author_id": 3322308,
"author_profile": "https://Stackoverflow.com/users/3322308",
"pm_score": 5,
"selected": false,
"text": "pip show <package_name>| grep Location\n cd $(python -c \"import site; print(site.getsitepackages()[0])\")\n"
},
{
"answer_id": 56011087,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "pip show six | grep \"Location:\" | cut -d \" \" -f2\n pip3 show six | grep \"Location:\" | cut -d \" \" -f2\n"
},
{
"answer_id": 63923577,
"author": "Stamatis Tiniakos",
"author_id": 11536058,
"author_profile": "https://Stackoverflow.com/users/11536058",
"pm_score": 2,
"selected": false,
"text": "py -3.5 -c \"import site; print(site.getsitepackages()[1])\n"
},
{
"answer_id": 64917912,
"author": "cglacet",
"author_id": 1720199,
"author_profile": "https://Stackoverflow.com/users/1720199",
"pm_score": 2,
"selected": false,
"text": "poetry debug $ poetry debug\n\nPoetry\nVersion: 1.1.4\nPython: 3.8.2\n\nVirtualenv\nPython: 3.8.2\nImplementation: CPython\nPath: /Users/cglacet/.pyenv/versions/3.8.2/envs/my-virtualenv\nValid: True\n\nSystem\nPlatform: darwin\nOS: posix\nPython: /Users/cglacet/.pyenv/versions/3.8.2\n ls /Users/cglacet/.pyenv/versions/3.8.2/envs/my-virtualenv/lib/python3.8/site-packages/\n"
},
{
"answer_id": 68426881,
"author": "Angel",
"author_id": 12234006,
"author_profile": "https://Stackoverflow.com/users/12234006",
"pm_score": 2,
"selected": false,
"text": "import site\n\n\ndef get_site_packages_dir():\n return [p for p in site.getsitepackages()\n if p.endswith((\"site-packages\", \"dist-packages\"))][0]\n\nget_site_packages_dir()\n# '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages'\n python3 -c \"import site;print([p for p in site.getsitepackages() if p.endswith(('site-packages', 'dist-packages')) ][0])\"\n\n/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages\n\n\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
122,348
|
<p>I have a command which includes an includegraphics command - I can pass an image to my command, and it will do some standard formatting for me before actually including the image. Some of the images that I'm including via this command are smaller than \textwidth, while some are larger. I'd like to scale the larger images down to \textwidth, while not scaling the smaller images up - this means I can't just do </p>
<pre><code>\includegraphics[width=\textwidth]{img}
</code></pre>
<p>Is there a way to specify a maxwidth? Or, can I get the width of the image somehow so I can do something like </p>
<pre><code>\ifthenelse{\imagewidth > \textwidth}{%
\includegraphics[width=\textwidth]{img}}{%
\includegraphics{img}}
</code></pre>
|
[
{
"answer_id": 123184,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 6,
"selected": true,
"text": "\\newlength{\\imgwidth}\n\\settowidth{\\imgwidth}{\\includegraphics{img}}\n \\usepackage{graphicx}\n\\usepackage{calc}\n\n\\newlength{\\imgwidth}\n\n\\newcommand\\scalegraphics[1]{% \n \\settowidth{\\imgwidth}{\\includegraphics{#1}}%\n \\setlength{\\imgwidth}{\\minof{\\imgwidth}{\\textwidth}}%\n \\includegraphics[width=\\imgwidth]{#1}%\n}\n \\scalegraphics{img}\n"
},
{
"answer_id": 5732912,
"author": "TauPan",
"author_id": 565224,
"author_profile": "https://Stackoverflow.com/users/565224",
"pm_score": 1,
"selected": false,
"text": "\\newcommand\\scalegraphics[2][]{%\n \\settowidth{\\imgwidth}{\\includegraphics{#2}}%\n \\setlength{\\imgwidth}{\\minof{#1\\imgwidth}{\\textwidth}}%\n \\includegraphics[width=\\imgwidth]{#2}%\n}\n"
},
{
"answer_id": 17909454,
"author": "ted",
"author_id": 258418,
"author_profile": "https://Stackoverflow.com/users/258418",
"pm_score": 0,
"selected": false,
"text": "adjustbox \\documentclass[a4paper]{article}\n\n\n\\usepackage[demo]{graphicx}\n\\usepackage[export]{adjustbox}\n\n\\begin{document}\n\n\\adjustbox{max width=\\linewidth}{\\includegraphics[width=.5\\linewidth,height=3cm]{}}\n\n\\adjustbox{max width=\\linewidth}{\\includegraphics[width=2\\linewidth,height=3cm]{}}\n\n\\includegraphics[width=2\\linewidth,height=3cm,max width=\\linewidth]{}\n\\end{document}\n export \\includegraphics max width"
},
{
"answer_id": 54532404,
"author": "Casimir",
"author_id": 4034025,
"author_profile": "https://Stackoverflow.com/users/4034025",
"pm_score": 0,
"selected": false,
"text": ".tex \\scalegraphics \\newlength{\\inputwidth}\n\\newcommand\\maxwidthinput[2][\\linewidth]{% \n \\settowidth{\\inputwidth}{#2}%\n \\setlength{\\inputwidth}{\\minof{\\inputwidth}{#1}}%\n \\resizebox{\\inputwidth}{!}{#2}\n}\n \\maxwidthinput{\\input{standalone}}\n\\maxwidthinput[0.5\\textwidth]{\\input{standalone}}\n adjustbox \\usepackage{adjustbox}\n...\n\\adjustbox{max width=\\linewidth}{\\input{standalone}}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1322/"
] |
122,362
|
<p>If I am trying to determine the read speed of a drive, I can code a routine to write files to a filesystem and then read those files back. Unfortunately, this doesn't give an accurate read speed because Windows does disk read caching. </p>
<p>Is there a way to flush the disk read cache of a drive in C# / .Net (or perhaps with Win32 API calls) so that I can read the files directly from the drive without them being cached?</p>
|
[
{
"answer_id": 128523,
"author": "Pretzel",
"author_id": 21244,
"author_profile": "https://Stackoverflow.com/users/21244",
"pm_score": 4,
"selected": false,
"text": " [DllImport(\"kernel32\", SetLastError=true)]\n static extern unsafe SafeFileHandle CreateFile(\n string FileName, // file name\n uint DesiredAccess, // access mode\n uint ShareMode, // share mode\n IntPtr SecurityAttributes, // Security Attr\n uint CreationDisposition, // how to create\n uint FlagsAndAttributes, // file attributes\n SafeFileHandle hTemplate // template file \n );\n\n SafeFileHandle handle = CreateFile(FileName,\n FileAccess.Read,\n FileShare.None,\n IntPtr.Zero,\n FileMode.Open,\n FILE_FLAG_NO_BUFFERING,\n null);\n\n FileStream stream = new FileStream(handle, \n FileAccess.Read, \n true, \n 4096);\n"
},
{
"answer_id": 384850,
"author": "Fix",
"author_id": 48173,
"author_profile": "https://Stackoverflow.com/users/48173",
"pm_score": 2,
"selected": false,
"text": "const int FILE_FLAG_NO_BUFFERING = 0x20000000;\nreturn new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,64 * 1024,\n(FileOptions)FILE_FLAG_NO_BUFFERING | FileOptions.Asynchronous\n& FileOptions.SequentialScan);\n"
},
{
"answer_id": 1374156,
"author": "Mash",
"author_id": 167951,
"author_profile": "https://Stackoverflow.com/users/167951",
"pm_score": 4,
"selected": false,
"text": "const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000;\n\nFileStream file = new FileStream(fileName, fileMode, fileAccess, fileShare, blockSize,\n FileFlagNoBuffering | FileOptions.WriteThrough | fileOptions);\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21244/"
] |
122,367
|
<p>Can I simulate in C#/C++ code <kbd>Control</kbd>+<kbd>Alt</kbd>+<kbd>Delete</kbd> sequence in Vista?
When UAC enabled/disabled?
How it is done in XP?</p>
<p>Can you provide a code sample that works in Vista?</p>
|
[
{
"answer_id": 47656659,
"author": "fdioff",
"author_id": 2027913,
"author_profile": "https://Stackoverflow.com/users/2027913",
"pm_score": 0,
"selected": false,
"text": "HDESK desktop = OpenDesktopW(L\"Winlogon\", 0, TRUE,\n DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | \n DESKTOP_HOOKCONTROL | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |\n DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);\nint result = SetThreadDesktop(desktop);\nif (result)\n{\n HMODULE sasdll = LoadLibraryA(\"sas.dll\");\n if (sasdll)\n {\n typedef void(__stdcall * SendSAS_t)(BOOL);\n SendSAS_t sendSAS = (SendSAS_t)GetProcAddress(sasdll, \"SendSAS\");\n if (sendSAS)\n sendSAS(FALSE);\n }\n}\nCloseDesktop(desktop);\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20257/"
] |
122,400
|
<p>I'm not asking about general syntactic rules for file names. I mean gotchas that jump out of nowhere and bite you. For example, trying to name a file "COM<n>" on Windows?</p>
|
[
{
"answer_id": 122427,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "gzip -9vf -- -mydashedfilename\n"
},
{
"answer_id": 122429,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": 1,
"selected": false,
"text": ". .. - --"
},
{
"answer_id": 122431,
"author": "Jacob T. Nielsen",
"author_id": 20032,
"author_profile": "https://Stackoverflow.com/users/20032",
"pm_score": 5,
"selected": true,
"text": "/ ? < > \\ : * | \" ^ aux com1 com2 com9 lpt1 lpt2 lpt9 con nul prn"
},
{
"answer_id": 27912606,
"author": "Malvineous",
"author_id": 308237,
"author_profile": "https://Stackoverflow.com/users/308237",
"pm_score": 3,
"selected": false,
"text": "ver ver > \"\\\\?\\C:\\Users\\username\\COM1\"\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3474/"
] |
122,404
|
<p>I used to often find myself coping a piece of code from a website/Word document etc only to discover that when doing Paste I would end up with the desired code plus some extra HTML tags/text, basically extra formatting information.</p>
<p>To get rid of that extra ballast I would paste the text to the Notepad and then copy it again and then paste to the desired destination. </p>
<p>Pretty recently I discovered a simple and free tool for Windows called <a href="http://www.stevemiller.net/puretext/" rel="noreferrer">PureText</a> that allows me to cut the Notepad step. It basically adds an extra keyboard shortcut e.g WinKey + V that will do the Paste action without formatting; just pure text.
I find it very handy.</p>
<p>I was wondering what approach would you use yourselves? Are they any better/easier to use tools around?</p>
|
[
{
"answer_id": 132761,
"author": "eugensk",
"author_id": 17495,
"author_profile": "https://Stackoverflow.com/users/17495",
"pm_score": 2,
"selected": false,
"text": "ctrl-escape,arrdown,enter,shift-f4,$,enter\nshift-insert,ctrl-insert,alt-backspace,\nf10,enter\n"
},
{
"answer_id": 132826,
"author": "Dean Hill",
"author_id": 3106,
"author_profile": "https://Stackoverflow.com/users/3106",
"pm_score": 5,
"selected": false,
"text": "^+v::\n ; Convert any copied files, HTML, or other formatted text to plain text\n Clipboard = %Clipboard%\n\n ; Paste by pressing Ctrl+V\n SendInput, ^v\nreturn\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3241/"
] |
122,407
|
<p>I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?</p>
|
[
{
"answer_id": 122414,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 9,
"selected": true,
"text": "String int interface StringFunction {\n int func(String param);\n}\n StringFunction public void takingMethod(StringFunction sf) {\n int i = sf.func(\"my string\");\n // do whatever ...\n}\n ref.takingMethod(new StringFunction() {\n public int func(String param) {\n // body\n }\n});\n ref.takingMethod(param -> bodyExpression);\n"
},
{
"answer_id": 122470,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 5,
"selected": false,
"text": "/**\n * A simple interface to wrap up a function of one argument.\n * \n * @author rcreswick\n *\n */\npublic interface Function1<S, T> {\n\n /**\n * Evaluates this function on it's arguments.\n * \n * @param a The first argument.\n * @return The result.\n */\n public S eval(T a);\n\n}\n List<Integer> result = CollectionUtilities.map(list,\n new Function1<Integer, Integer>() {\n @Override\n public Integer eval(Integer a) {\n return a * a;\n }\n });\n public static <K,R,S,T> Map<K, R> zipWith(Function2<R,S,T> fn, \n Map<K, S> m1, Map<K, T> m2, Map<K, R> results){\n Set<K> keySet = new HashSet<K>();\n keySet.addAll(m1.keySet());\n keySet.addAll(m2.keySet());\n\n results.clear();\n\n for (K key : keySet) {\n results.put(key, fn.eval(m1.get(key), m2.get(key)));\n }\n return results;\n }\n"
},
{
"answer_id": 687655,
"author": "TofuBeer",
"author_id": 65868,
"author_profile": "https://Stackoverflow.com/users/65868",
"pm_score": 4,
"selected": false,
"text": "import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n\nclass Main\n{\n public static void main(final String[] argv)\n throws NoSuchMethodException,\n IllegalAccessException,\n IllegalArgumentException,\n InvocationTargetException\n {\n final String methodName;\n final Method method;\n final Main main;\n\n main = new Main();\n\n if(argv.length == 0)\n {\n methodName = \"foo\";\n }\n else\n {\n methodName = \"bar\";\n }\n\n method = Main.class.getDeclaredMethod(methodName, int.class);\n\n main.car(method, 42);\n }\n\n private void foo(final int x)\n {\n System.out.println(\"foo: \" + x);\n }\n\n private void bar(final int x)\n {\n System.out.println(\"bar: \" + x);\n }\n\n private void car(final Method method,\n final int val)\n throws IllegalAccessException,\n IllegalArgumentException,\n InvocationTargetException\n {\n method.invoke(this, val);\n }\n}\n"
},
{
"answer_id": 688035,
"author": "javashlook",
"author_id": 24815,
"author_profile": "https://Stackoverflow.com/users/24815",
"pm_score": 5,
"selected": false,
"text": "public enum Operation {\n PLUS {\n public double calc(double a, double b) {\n return a + b;\n }\n },\n TIMES {\n public double calc(double a, double b) {\n return a * b;\n }\n }\n ...\n\n public abstract double calc(double a, double b);\n}\n"
},
{
"answer_id": 2768052,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 3,
"selected": false,
"text": "f(x,y)=x*y\n f(x,y)=x*y*2\n f(x,y)=x*y/2\n InnerFunc f=new InnerFunc(1.0);// for the first\ncalculateUsing(f);\nf=new InnerFunc(2.0);// for the second\ncalculateUsing(f);\nf=new InnerFunc(0.5);// for the third\ncalculateUsing(f);\n InnerFunc f=new InnerFunc(1.0);// for the first\ncalculateUsing(f);\nf.setConstant(2.0);\ncalculateUsing(f);\nf.setConstant(0.5);\ncalculateUsing(f);\n"
},
{
"answer_id": 5347558,
"author": "vwvan",
"author_id": 591223,
"author_profile": "https://Stackoverflow.com/users/591223",
"pm_score": 2,
"selected": false,
"text": "class NameFuncPair\n{\n public String name; // name each func\n void f(String x) {} // stub gets overridden\n public NameFuncPair(String myName) { this.name = myName; }\n}\n\npublic class ArrayOfFunctions\n{\n public static void main(String[] args)\n {\n final A a = new A();\n final B b = new B();\n\n NameFuncPair[] fArray = new NameFuncPair[]\n {\n new NameFuncPair(\"A\") { @Override void f(String x) { a.g(x); } },\n new NameFuncPair(\"B\") { @Override void f(String x) { b.h(x); } },\n };\n\n // Go through the whole func list and run the func named \"B\"\n for (NameFuncPair fInstance : fArray)\n {\n if (fInstance.name.equals(\"B\"))\n {\n fInstance.f(fInstance.name + \"(some args)\");\n }\n }\n }\n}\n\nclass A { void g(String args) { System.out.println(args); } }\nclass B { void h(String args) { System.out.println(args); } }\n"
},
{
"answer_id": 8066845,
"author": "yogibimbi",
"author_id": 1037921,
"author_profile": "https://Stackoverflow.com/users/1037921",
"pm_score": 2,
"selected": false,
"text": "java.lang.reflect.Method Function = Class.forName(String classPath).getMethod(String method, Class[] params);\n java.lang.reflect.Method Function = Class.forName(\"be.qan.NN.ActivationFunctions\").getMethod(\"sigmoid\", double.class);\n return (java.lang.Double)this.Function.invoke(null, args);\n\njava.lang.Object[] args = new java.lang.Object[] {activity};\nsomeOtherFunction() + 234 + (java.lang.Double)Function.invoke(null, args);\n"
},
{
"answer_id": 21974187,
"author": "The Guy with The Hat",
"author_id": 2846923,
"author_profile": "https://Stackoverflow.com/users/2846923",
"pm_score": 4,
"selected": false,
"text": ":: IntBinaryOperator applyAsInt int int Math.max int int A.method(Math::max); parameter.applyAsInt Math.max Math.max import java.util.function.IntBinaryOperator;\n\nclass A {\n static void method(IntBinaryOperator parameter) {\n int i = parameter.applyAsInt(7315, 89163);\n System.out.println(i);\n }\n}\n import java.lang.Math;\n\nclass B {\n public static void main(String[] args) {\n A.method(Math::max);\n }\n}\n method1(Class1::method2);\n method1((arg1, arg2) -> Class1.method2(arg1, arg2));\n method1(new Interface1() {\n int method1(int arg1, int arg2) {\n return Class1.method2(arg1, agr2);\n }\n});\n"
},
{
"answer_id": 24152239,
"author": "Scott Emmons",
"author_id": 3025865,
"author_profile": "https://Stackoverflow.com/users/3025865",
"pm_score": 1,
"selected": false,
"text": "(define (function scalar1 scalar2)\n (lambda (x) (* x scalar1 scalar2)))\n"
},
{
"answer_id": 25381389,
"author": "user3002379",
"author_id": 3002379,
"author_profile": "https://Stackoverflow.com/users/3002379",
"pm_score": 4,
"selected": false,
"text": ":: @FunctionalInterface\ninterface CallbackHandler{\n public void onClick();\n}\n\npublic class MyClass{\n public void doClick1(){System.out.println(\"doClick1\");;}\n public void doClick2(){System.out.println(\"doClick2\");}\n public CallbackHandler mClickListener = this::doClick;\n\n public static void main(String[] args) {\n MyClass myObjectInstance = new MyClass();\n CallbackHandler pointer = myObjectInstance::doClick1;\n Runnable pointer2 = myObjectInstance::doClick2;\n pointer.onClick();\n pointer2.run();\n }\n}\n Runnable -> void run( );\nSupplier<T> -> T get( );\nConsumer<T> -> void accept(T);\nPredicate<T> -> boolean test(T);\nUnaryOperator<T> -> T apply(T);\nBinaryOperator<T,U,R> -> R apply(T, U);\nFunction<T,R> -> R apply(T);\nBiFunction<T,U,R> -> R apply(T, U);\n//... and some more of it ...\nCallable<V> -> V call() throws Exception;\nReadable -> int read(CharBuffer) throws IOException;\nAutoCloseable -> void close() throws Exception;\nIterable<T> -> Iterator<T> iterator();\nComparable<T> -> int compareTo(T);\nComparator<T> -> int compare(T,T);\n"
},
{
"answer_id": 30151628,
"author": "Alex",
"author_id": 4884360,
"author_profile": "https://Stackoverflow.com/users/4884360",
"pm_score": 1,
"selected": false,
"text": "Function<InputType, OutputType> functionname = (inputvariablename) {\n... \nreturn outputinstance;\n}\n"
},
{
"answer_id": 31001089,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 1,
"selected": false,
"text": "Collections.sort(list, new Comparator<CustomClass>(){\n public int compare(CustomClass a, CustomClass b)\n {\n // Logic to compare objects of class CustomClass which returns int as per contract.\n }\n});\n list.sort((a, b) -> { a.isBiggerThan(b) } );\n CustomClass list.sort(MyClass::isBiggerThan);\n"
},
{
"answer_id": 39922622,
"author": "mrts",
"author_id": 258772,
"author_profile": "https://Stackoverflow.com/users/258772",
"pm_score": 2,
"selected": false,
"text": "void doCalculation(Function<Integer, String> calculation, int parameter) {\n final String result = calculation.apply(parameter);\n}\n doCalculation((i) -> i.toString(), 2);\n"
},
{
"answer_id": 63776249,
"author": "Hervian",
"author_id": 6095334,
"author_profile": "https://Stackoverflow.com/users/6095334",
"pm_score": 0,
"selected": false,
"text": "Fun.With0Params<String> myFunctionField = \" hello world \"::trim;` \nFun.With2Params<Boolean, Object, Object> equals = Objects::equals;` \n \npublic void foo(Fun.With1ParamAndVoid<String> printer) throws Exception {\n printer.invoke(\"hello world);\n} \n\npublic void test(){\n foo(System.out::println);\n} \n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
122,422
|
<p>Is there any way to change the default datatype when importing an Excel file into Access? (I'm using Access 2003, by the way).</p>
<p>I know that I sometimes have the freedom to assign any datatype to each column that is being imported, but that could only be when I'm importing non-Excel files. </p>
<p><strong>EDIT:</strong> To be clear, I understand that there is a step in the import process where you are allowed to change the datatype of the imported column. </p>
<p>In fact, that's what I'm asking about. For some reason - maybe it's always Excel files, maybe there's something else - I am sometimes not allowed to change the datatype: the dropdown box is grayed out and I just have to live with whatever datatype Access assumes is correct.</p>
<p>For example, I just tried importing a large-ish Excel file (<strong>12000+ rows, ~200 columns</strong>) in Access where column #105 (or something similar) was filled with mostly numbers (codes: <code>1=foo, 2=bar</code>, etc), though there are a handful of alpha codes in there too (A=boo, B=far, etc). Access assumed it was a <code>Number</code> datatype (even after I changed the <code>Format</code> value in the Excel file itself) and so gave me errors on those alpha codes. If I had been allowed to change the datatype on import, it would have saved me some trouble.</p>
<p>Am I asking for something that Access just won't do, or am I missing something? Thanks.</p>
<p><strong>EDIT:</strong> There are two answers below that give useful advice. Saving the Excel file as a CSV and then importing that works well and is straightforward like <a href="https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122588">Chris OC</a> says. The advice for saving an import specification is very helpful too. However, I chose the registry setting answer by <a href="https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122504">DK</a> as the "Accepted Answer". I liked it as an answer because it's a <em>one-time-only step</em> that can be used to solve my major problem (having Access incorrectly assign a datatype). In short, this solution doesn't allow me to change the datatype myself, but it makes Access accurately guess the datatype so that there are fewer issues.</p>
|
[
{
"answer_id": 122504,
"author": "DK.",
"author_id": 16886,
"author_profile": "https://Stackoverflow.com/users/16886",
"pm_score": 3,
"selected": true,
"text": "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Jet\\4.0\\Engines\\Excel]\n\"TypeGuessRows\"=dword:00000000\n"
},
{
"answer_id": 68834334,
"author": "Christo",
"author_id": 13048688,
"author_profile": "https://Stackoverflow.com/users/13048688",
"pm_score": 0,
"selected": false,
"text": "Public Function fcn_ChangeExcelFormat()\nOn Error GoTo ErrorExit\n\nDim strExcelFile As String\nDim XL_App As Excel.Application\nDim XL_WB As Excel.Workbook\nDim XL_WS As Excel.Worksheet\n\nstrExcelFile = \"C:\\My Files\\MyExcelFile.xlsx\"\n\nSet XL_App = New Excel.Application\n\nSet XL_WB = XL_App.Workbooks.Open(strExcelFile, , False)\nSet XL_WS = XL_WB.Sheets(1) ' 1 can be changed to \"Your Worksheet Name\"\n\nWith XL_WS\n .Cells.NumberFormat = \"@\" 'Equiv to Right Click...Format Cells...Text\nEnd With\n\nXL_WB.Close True\nXL_App.Quit\n\nNormalExit:\nSet XL_WB = Nothing\nSet XL_App = Nothing\nExit Function\n \nErrorExit:\nstrMsg = \"There was an error updating the Excel file! \" & vbCr & vbCr & _\n \"Error \" & Err.Number & \": \" & Err.Description\nMsgBox strMsg, vbExclamation, \"Error\"\nResume NormalExit\nEnd Function\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3930756/"
] |
122,424
|
<p>Right now, we are using Perforce for version control. It has the handy feature of a strictly increasing change number that we can use to refer to builds, eg "you'll get the bugfix if your build is at least 44902".</p>
<p>I'd like to switch over to using a distributed system (probably git) to make it easier to branch and to work from home. (Both of which are perfectly possible with Perforce, but the git workflow has some advantages.) So although "tributary development" would be distributed and not refer to a common revision sequencing, we'd still maintain a master git repo that all changes would need to feed into before a build was created.</p>
<p>What's the best way to preserve strictly increasing build ids? The most straightforward way I can think of is to have some sort of post-commit hook that fires off whenever the master repo gets updated, and it registers (the hash of) the new tree object (or commit object? I'm new to git) with a centralized database that hands out ids. (I say "database", but I'd probably do it with git tags, and just look for the next available tag number or something. So the "database" would really be .git/refs/tags/build-id/.)</p>
<p>This is workable, but I'm wondering if there is an easier, or already-implemented, or standard/"best practice" way of accomplishing this.</p>
|
[
{
"answer_id": 122673,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 2,
"selected": false,
"text": "git tag git push git push --tags"
},
{
"answer_id": 123594,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 2,
"selected": false,
"text": "git describe # make an annotated tag to an early build in the repository:\ngit tag -a build-origin \"$some_old_commitid\"\n\n# describe the current HEAD against this tag and pull out a build number\nexpr \"$(git describe --match build-origin)\" : 'build-origin-\\([0-9]*\\)-g'\n"
},
{
"answer_id": 124747,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 6,
"selected": true,
"text": "git describe git describe git init\ngit commit --allow-empty -m'Commit One.'\ngit tag -a -m'Tag One.' 1.2.3\ngit describe # => 1.2.3\ngit commit --allow-empty -m'Commit Two.'\ngit describe # => 1.2.3-1-gaac161d\ngit commit --allow-empty -m'Commit Three.'\ngit describe # => 1.2.3-2-g462715d\ngit tag -a -m'Tag Two.' 2.0.0\ngit describe # => 2.0.0\n git describe git describe"
},
{
"answer_id": 1048950,
"author": "yanjost",
"author_id": 16718,
"author_profile": "https://Stackoverflow.com/users/16718",
"pm_score": 0,
"selected": false,
"text": "# get the parents id, the local revision number and the tags\n[yjost@myhost:~/my-repo]$ hg id -nibt\n03b6399bc32b+ 23716+ default tip\n"
},
{
"answer_id": 14997849,
"author": "squadette",
"author_id": 7754,
"author_profile": "https://Stackoverflow.com/users/7754",
"pm_score": 5,
"selected": false,
"text": "git log --pretty=oneline | wc -l\n git describe"
},
{
"answer_id": 22082992,
"author": "joegiralt",
"author_id": 2340298,
"author_profile": "https://Stackoverflow.com/users/2340298",
"pm_score": 3,
"selected": false,
"text": " git rev-list BRANCHNAME --count\n git log --pretty=oneline | wc -l\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14528/"
] |
122,445
|
<p>I'm implementing charts using <a href="http://www.ziya.liquidrail.com/" rel="nofollow noreferrer">The Ziya Charts Gem</a>. Unfortunately, the documentation isn't really helpful or I haven't had enough coffee to figure out theming. I know I can set a theme using</p>
<pre><code>chart.add(:theme, 'whatever')
</code></pre>
<p>Problem: I haven't found any predefined themes, nor have I found a reference to the required format. </p>
|
[
{
"answer_id": 122491,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 0,
"selected": false,
"text": "svn co svn://rubyforge.org/var/svn/liquidrail/samples/charting \n"
},
{
"answer_id": 122795,
"author": "PJ.",
"author_id": 3230,
"author_profile": "https://Stackoverflow.com/users/3230",
"pm_score": 2,
"selected": true,
"text": "Ziya.initialize(:themes_dir => File.join( File.dirname(__FILE__), %w[.. .. public charts themes]) )\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4494/"
] |
122,451
|
<p>My ClickOnce application uses a third party tool that requires the Visual C++ 2005 redistributable. The third party tool will not work if only the VC++ 2008 redistributable is installed. However, in Visual Studio 2008, the ClickOnce prerequisites do not allow a version to be specified for the VC++ redistributable; it will add a VC++ 2008 prerequisite, which makes sense most of the time. However, in this situation, an earlier version is required. ClickOnce is required, so merge modules are out of the question. Any ideas of how to specify the version?</p>
|
[
{
"answer_id": 154033,
"author": "codeConcussion",
"author_id": 1321,
"author_profile": "https://Stackoverflow.com/users/1321",
"pm_score": 4,
"selected": true,
"text": "_ _ <String Name=\"DisplayName\">"
},
{
"answer_id": 25278441,
"author": "Der_Meister",
"author_id": 991267,
"author_profile": "https://Stackoverflow.com/users/991267",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n\n<Package\n xmlns=\"http://schemas.microsoft.com/developer/2004/01/bootstrapper\"\n Name=\"DisplayName\"\n Culture=\"Culture\"\n>\n\n <!-- Defines a localizable string table for error messages-->\n <Strings>\n <String Name=\"DisplayName\">Visual C++ Runtime Libraries (x86)</String>\n <String Name=\"Culture\">en</String>\n <String Name=\"AdminRequired\">You do not have the permissions required to install Visual C++ Runtime Libraries (x86). Please contact your administrator.</String>\n <String Name=\"InvalidPlatformWin9x\">Installation of Visual C++ Runtime Libraries (x86) is not supported on Windows 95. Contact your application vendor.</String>\n <String Name=\"InvalidPlatformWinNT\">Installation of Visual C++ Runtime Libraries (x86) is not supported on Windows NT 4.0. Contact your application vendor.</String>\n <String Name=\"GeneralFailure\">A failure occurred attempting to install Visual C++ Runtime Libraries (x86).</String>\n </Strings>\n\n</Package>\n <?xml version=\"1.0\" encoding=\"utf-8\" ?> \n\n<Product\n xmlns=\"http://schemas.microsoft.com/developer/2004/01/bootstrapper\"\n ProductCode=\"Microsoft.Visual.C++.8.0.x86\"\n>\n\n <!-- Defines list of files to be copied on build -->\n <PackageFiles>\n <PackageFile Name=\"vcredist_x86.exe\"/>\n </PackageFiles>\n\n <InstallChecks>\n <MsiProductCheck Property=\"VCRedistInstalled\" Product=\"{A49F249F-0C91-497F-86DF-B2585E8E76B7}\"/>\n </InstallChecks>\n\n <!-- Defines how to invoke the setup for the Visual C++ 8.0 redist -->\n <!-- TODO: Needs EstrimatedTempSpace, LogFile, and an update of EstimatedDiskSpace -->\n <Commands Reboot=\"Defer\">\n <Command PackageFile=\"vcredist_x86.exe\" \n Arguments=' /q:a ' \n >\n\n <!-- These checks determine whether the package is to be installed -->\n <InstallConditions>\n <BypassIf Property=\"VCRedistInstalled\" Compare=\"ValueGreaterThanOrEqualTo\" Value=\"3\"/>\n <!-- Block install if user does not have admin privileges -->\n <FailIf Property=\"AdminUser\" Compare=\"ValueEqualTo\" Value=\"false\" String=\"AdminRequired\"/>\n\n <!-- Block install on Win95 -->\n <FailIf Property=\"Version9X\" Compare=\"VersionLessThan\" Value=\"4.10\" String=\"InvalidPlatformWin9x\"/>\n\n <!-- Block install on NT 4 or less -->\n <FailIf Property=\"VersionNT\" Compare=\"VersionLessThan\" Value=\"5.00\" String=\"InvalidPlatformWinNT\"/>\n\n </InstallConditions>\n\n <ExitCodes>\n <ExitCode Value=\"0\" Result=\"Success\"/>\n <ExitCode Value=\"3010\" Result=\"SuccessReboot\"/>\n <DefaultExitCode Result=\"Fail\" FormatMessageFromSystem=\"true\" String=\"GeneralFailure\" />\n </ExitCodes>\n\n </Command>\n </Commands>\n</Product>\n SHA1: 95040f80b0d203e1abaec4e06e0ec0e01c507d03\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19357/"
] |
122,463
|
<p>I have an XML file that starts like this:</p>
<pre><code><Elements name="Entities" xmlns="XS-GenerationToolElements">
</code></pre>
<p>I'll have to open a lot of these files. Each of these have a different namespace but will only have one namespace at a time (I'll never find two namespaces defined in one xml file).</p>
<p>Using XPath I'd like to have an automatic way to add the given namespace to the namespace manager.
So far, i could only get the namespace by parsing the xml file but I have a XPathNavigator instance and it should have a nice and clean way to get the namespaces, right?</p>
<p>-- OR --</p>
<p>Given that I only have one namespace, somehow make XPath use the only one that is present in the xml, thus avoiding cluttering the code by always appending the namespace.</p>
|
[
{
"answer_id": 123005,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 8,
"selected": true,
"text": "namespace:: /*/namespace::*[name()='']\n namespace:: namespace-uri() namespace-uri(/*)\n local-name() //*[local-name() = 'Element']\n //*[local-name() = 'Element' and namespace-uri() = namespace-uri(/*)]\n xmlns"
},
{
"answer_id": 289120,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 4,
"selected": false,
"text": " <xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:ext=\"http://exslt.org/common\"\n exclude-result-prefixes=\"ext\"\n >\n\n <xsl:output omit-xml-declaration=\"yes\" indent=\"yes\"/>\n\n <xsl:strip-space elements=\"*\"/>\n\n <xsl:key name=\"kNsByNsUri\" match=\"ns\" use=\"@uri\"/>\n\n <xsl:variable name=\"vXmlNS\" \n select=\"'http://www.w3.org/XML/1998/namespace'\"/>\n\n <xsl:template match=\"/\">\n <xsl:variable name=\"vrtfNamespaces\">\n <xsl:for-each select=\n \"//namespace::*\n [not(. = $vXmlNS)\n and\n . = namespace-uri(..)\n ]\">\n <ns element=\"{name(..)}\"\n prefix=\"{name()}\" uri=\"{.}\"/>\n </xsl:for-each>\n </xsl:variable>\n\n <xsl:variable name=\"vNamespaces\"\n select=\"ext:node-set($vrtfNamespaces)/*\"/>\n\n <namespaces>\n <xsl:for-each select=\n \"$vNamespaces[generate-id()\n =\n generate-id(key('kNsByNsUri',@uri)[1])\n ]\">\n <namespace uri=\"{@uri}\">\n <xsl:for-each select=\"key('kNsByNsUri',@uri)/@element\">\n <element name=\"{.}\" prefix=\"{../@prefix}\"/>\n </xsl:for-each>\n </namespace>\n </xsl:for-each>\n </namespaces>\n </xsl:template>\n </xsl:stylesheet>\n <a xmlns=\"my:def1\" xmlns:n1=\"my:n1\"\n xmlns:n2=\"my:n2\" xmlns:n3=\"my:n3\">\n <b>\n <n1:d/>\n </b>\n <n1:c>\n <n2:e>\n <f/>\n </n2:e>\n </n1:c>\n <n2:g/>\n</a>\n <namespaces>\n <namespace uri=\"my:def1\">\n <element name=\"a\" prefix=\"\"/>\n <element name=\"b\" prefix=\"\"/>\n <element name=\"f\" prefix=\"\"/>\n </namespace>\n <namespace uri=\"my:n1\">\n <element name=\"n1:d\" prefix=\"n1\"/>\n <element name=\"n1:c\" prefix=\"n1\"/>\n </namespace>\n <namespace uri=\"my:n2\">\n <element name=\"n2:e\" prefix=\"n2\"/>\n <element name=\"n2:g\" prefix=\"n2\"/>\n </namespace>\n</namespaces>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20335/"
] |
122,483
|
<p>In crontab, I can use an asterisk to mean every value, or "*/2" to mean every even value.</p>
<p>Is there a way to specify every <strong>odd</strong> value? (Would something like "1+*/2" work?)</p>
|
[
{
"answer_id": 122496,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "1-23/2\n"
},
{
"answer_id": 122499,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 8,
"selected": true,
"text": " 1-23/2\n Ranges can include \"steps\", so \"1-9/2\" is the same as \"1,3,5,7,9\".\n 1,3,5,7,9,11,13,15,17,19,21,23\n"
},
{
"answer_id": 5071478,
"author": "grigb",
"author_id": 627013,
"author_profile": "https://Stackoverflow.com/users/627013",
"pm_score": 6,
"selected": false,
"text": "1-59/2 * * * * \n 0-58/2 * * * * \n"
},
{
"answer_id": 10427443,
"author": "Tomas Jensen",
"author_id": 1371897,
"author_profile": "https://Stackoverflow.com/users/1371897",
"pm_score": 0,
"selected": false,
"text": "3-58/5 * * * * /home/test/bin/do_some_thing_every_five_minute\n"
},
{
"answer_id": 56839339,
"author": "pbjolsby",
"author_id": 11330991,
"author_profile": "https://Stackoverflow.com/users/11330991",
"pm_score": 3,
"selected": false,
"text": "59 */2 * * *\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4465/"
] |
122,514
|
<p>I have already posted something similar <a href="https://stackoverflow.com/questions/118051/c-grid-binding-not-update">here</a> but I would like to ask the question more general over here.</p>
<p>Have you try to serialize an object that implement INotifyPropertyChanged and to get it back from serialization and to bind it to a DataGridView? When I do it, I have no refresh from the value that change (I need to minimize the windows and open it back).</p>
<p>Do you have any trick? </p>
|
[
{
"answer_id": 179462,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 3,
"selected": true,
"text": "DataContractSerializer [OnDeserialized]\nprivate void OnDeserialized(StreamingContext c) {}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
122,523
|
<p>Howdy, I have a DataRow pulled out of a DataTable from a DataSet. I am accessing a column that is defined in SQL as a float datatype. I am trying to assign that value to a local variable (c# float datatype) but am getting an InvalidCastExecption </p>
<pre><code>DataRow exercise = _exerciseDataSet.Exercise.FindByExerciseID(65);
_AccelLimit = (float)exercise["DefaultAccelLimit"];
</code></pre>
<p>Now, playing around with this I did make it work but it did not make any sense and it didn't feel right. </p>
<pre><code>_AccelLimit = (float)(double)exercise["DefaultAccelLimit"];
</code></pre>
<p>Can anyone explain what I am missing here?</p>
|
[
{
"answer_id": 33133446,
"author": "dubrowgn",
"author_id": 4704196,
"author_profile": "https://Stackoverflow.com/users/4704196",
"pm_score": 0,
"selected": false,
"text": "exercise[\"DefaultAccelLimit\"] (double) (float) (double)(float)object_var"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] |
122,571
|
<p>Right now I'm making an extremely simple website- about 5 pages. Question is if it's overkill and worth the time to integrate some sort of database mapping solution or if it would be better to just use plain old JNDI. I'll have maybe a dozen things I need to read/write from the database. I guess I have a basic understanding of these technologies but it would still take a lot of referring to the documentation. Anyone else faced with the decision before?</p>
<p>EDIT: Sorry, I should've specified JNDI to lookup the DB connection and JDBC to perform the operations.</p>
|
[
{
"answer_id": 122888,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": true,
"text": "+findById( id ): Employee\n+insert( Employee ) \n+update( Employee )\n+delete( Employee ) \n+findAll():List<Employee>\n select * from employee where id = ?\ninsert into employee ( bla, bla, bla ) values ( ? , ? , ? )\nupdate etc. etc \n public Employee selectById( int id ) {\n // Commenting out the previous implementation...\n // String query = select * from employee where id = ? \n // execute( query ) \n\n // Using the ORM solution\n\n Session session = getSession();\n Employee e = ( Employee ) session.get( Employee.clas, id );\n return e;\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17614/"
] |
122,582
|
<p>I'm using a lat/long SRID in my PostGIS database (-4326). I would like to find the nearest points to a given point in an efficient manner. I tried doing an</p>
<pre><code>ORDER BY ST_Distance(point, ST_GeomFromText(?,-4326))
</code></pre>
<p>which gives me ok results in the lower 48 states, but up in Alaska it gives me garbage. Is there a way to do real distance calculations in PostGIS, or am I going to have to give a reasonable sized buffer and then calculate the great circle distances and sort the results in the code afterwards?</p>
|
[
{
"answer_id": 123166,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 2,
"selected": false,
"text": "ALTER function [dbo].[getCoordinateDistance]\n (\n @Latitude1 decimal(16,12),\n @Longitude1 decimal(16,12),\n @Latitude2 decimal(16,12),\n @Longitude2 decimal(16,12)\n )\nreturns decimal(16,12)\nas\n/*\nfUNCTION: getCoordinateDistance\n\n Computes the Great Circle distance in kilometers\n between two points on the Earth using the\n Haversine formula distance calculation.\n\nInput Parameters:\n @Longitude1 - Longitude in degrees of point 1\n @Latitude1 - Latitude in degrees of point 1\n @Longitude2 - Longitude in degrees of point 2\n @Latitude2 - Latitude in degrees of point 2\n\n*/\nbegin\ndeclare @radius decimal(16,12)\n\ndeclare @lon1 decimal(16,12)\ndeclare @lon2 decimal(16,12)\ndeclare @lat1 decimal(16,12)\ndeclare @lat2 decimal(16,12)\n\ndeclare @a decimal(16,12)\ndeclare @distance decimal(16,12)\n\n-- Sets average radius of Earth in Kilometers\nset @radius = 6366.70701949371\n\n-- Convert degrees to radians\nset @lon1 = radians( @Longitude1 )\nset @lon2 = radians( @Longitude2 )\nset @lat1 = radians( @Latitude1 )\nset @lat2 = radians( @Latitude2 )\n\nset @a = sqrt(square(sin((@lat2-@lat1)/2.0E)) + \n (cos(@lat1) * cos(@lat2) * square(sin((@lon2-@lon1)/2.0E))) )\n\nset @distance =\n @radius * ( 2.0E *asin(case when 1.0E < @a then 1.0E else @a end ) )\n\nreturn @distance\n\nend\n /*\n * Calculate geodesic distance (in m) between two points specified by latitude/longitude (in numeric degrees)\n * using Vincenty inverse formula for ellipsoids\n */\nfunction distVincenty(lat1, lon1, lat2, lon2) {\n var a = 6378137, b = 6356752.3142, f = 1/298.257223563; // WGS-84 ellipsiod\n var L = (lon2-lon1).toRad();\n var U1 = Math.atan((1-f) * Math.tan(lat1.toRad()));\n var U2 = Math.atan((1-f) * Math.tan(lat2.toRad()));\n var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);\n var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);\n\n var lambda = L, lambdaP = 2*Math.PI;\n var iterLimit = 20;\n while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0) {\n var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);\n var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) + \n (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));\n if (sinSigma==0) return 0; // co-incident points\n var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;\n var sigma = Math.atan2(sinSigma, cosSigma);\n var sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;\n var cosSqAlpha = 1 - sinAlpha*sinAlpha;\n var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;\n if (isNaN(cos2SigmaM)) cos2SigmaM = 0; // equatorial line: cosSqAlpha=0 (§6)\n var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));\n lambdaP = lambda;\n lambda = L + (1-C) * f * sinAlpha *\n (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));\n }\n if (iterLimit==0) return NaN // formula failed to converge\n\n var uSq = cosSqAlpha * (a*a - b*b) / (b*b);\n var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));\n var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));\n var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-\n B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));\n var s = b*A*(sigma-deltaSigma);\n\n s = s.toFixed(3); // round to 1mm precision\n return s;\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] |
122,593
|
<p>Is it possible to throw an exception in a JSP without using scriptlet code?</p>
|
[
{
"answer_id": 122608,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 0,
"selected": false,
"text": "<c:out value=\"${1/0}\" />\n <c:catch>"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
122,607
|
<p>I need to consume an external web service from my VB6 program. I want to be able to deploy my program without the SOAP toolkit, if possible, but that's not a requirement. I do not have the web service source and I didn't create it. It is a vendor-provided service.</p>
<p>So outside of the SOAP toolkit, what is the best way to consume a web service from VB6?</p>
|
[
{
"answer_id": 122645,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 2,
"selected": false,
"text": " set SoapObj = GetObject\n (\"soap:wsdl=http://www.xmethods.net/sd/TemperatureService.wsdl\")\n WScript.Echo \"Fairbanks Temperature = \" & SoapObj.getTemp(\"99707\")\n"
},
{
"answer_id": 123285,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 5,
"selected": true,
"text": "Private Function HttpGetRequest(url As String) As DOMDocument\n Dim req As XMLHTTP60\n Set req = New XMLHTTP60\n req.Open \"GET\", url, False\n req.send \"\"\n\n Dim resp As DOMDocument\n If req.responseText <> vbNullString Then\n Set resp = New DOMDocument60\n resp.loadXML req.responseText\n Else\n Set resp = req.responseXML\n End If\n Set HttpGetRequest = resp\nEnd Function\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
] |
122,616
|
<p>Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution.</p>
|
[
{
"answer_id": 122721,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 9,
"selected": true,
"text": "// Note: This function returns a pointer to a substring of the original string.\n// If the given string was allocated dynamically, the caller must not overwrite\n// that pointer with the returned value, since the original pointer must be\n// deallocated using the same allocator with which it was allocated. The return\n// value must NOT be deallocated using free() etc.\nchar *trimwhitespace(char *str)\n{\n char *end;\n\n // Trim leading space\n while(isspace((unsigned char)*str)) str++;\n\n if(*str == 0) // All spaces?\n return str;\n\n // Trim trailing space\n end = str + strlen(str) - 1;\n while(end > str && isspace((unsigned char)*end)) end--;\n\n // Write new null terminator character\n end[1] = '\\0';\n\n return str;\n}\n // Stores the trimmed input string into the given output buffer, which must be\n// large enough to store the result. If it is too small, the output is\n// truncated.\nsize_t trimwhitespace(char *out, size_t len, const char *str)\n{\n if(len == 0)\n return 0;\n\n const char *end;\n size_t out_size;\n\n // Trim leading space\n while(isspace((unsigned char)*str)) str++;\n\n if(*str == 0) // All spaces?\n {\n *out = 0;\n return 1;\n }\n\n // Trim trailing space\n end = str + strlen(str) - 1;\n while(end > str && isspace((unsigned char)*end)) end--;\n end++;\n\n // Set output size to minimum of trimmed string length and buffer size minus 1\n out_size = (end - str) < len-1 ? (end - str) : len-1;\n\n // Copy trimmed string and add null terminator\n memcpy(out, str, out_size);\n out[out_size] = 0;\n\n return out_size;\n}\n"
},
{
"answer_id": 122793,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": -1,
"selected": false,
"text": "void str_trim(char *output, const char *text, int32 max_len)\n{\n int32 i, j, length;\n length = strlen(text);\n\n if (max_len < 0) {\n max_len = length + 1;\n }\n\n for (i=0; i<length; i++) {\n if ( (text[i] != ' ') && (text[i] != '\\t') && (text[i] != '\\n') && (text[i] != '\\r')) {\n break;\n }\n }\n\n if (i == length) {\n // handle lines that are all whitespace\n output[0] = 0;\n return;\n }\n\n for (j=length-1; j>=0; j--) {\n if ( (text[j] != ' ') && (text[j] != '\\t') && (text[j] != '\\n') && (text[j] != '\\r')) {\n break;\n }\n }\n\n length = j + 1 - i;\n strncpy(output, text + i, length);\n output[length] = 0;\n}\n"
},
{
"answer_id": 122912,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 2,
"selected": false,
"text": "* ++ String chomp"
},
{
"answer_id": 122974,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 5,
"selected": false,
"text": "char *trim(char *str)\n{\n size_t len = 0;\n char *frontp = str;\n char *endp = NULL;\n\n if( str == NULL ) { return NULL; }\n if( str[0] == '\\0' ) { return str; }\n\n len = strlen(str);\n endp = str + len;\n\n /* Move the front and back pointers to address the first non-whitespace\n * characters from each end.\n */\n while( isspace((unsigned char) *frontp) ) { ++frontp; }\n if( endp != frontp )\n {\n while( isspace((unsigned char) *(--endp)) && endp != frontp ) {}\n }\n\n if( frontp != str && endp == frontp )\n *str = '\\0';\n else if( str + len - 1 != endp )\n *(endp + 1) = '\\0';\n\n /* Shift the string so that it starts at str so that if it's dynamically\n * allocated, we can still free it on the returned pointer. Note the reuse\n * of endp to mean the front of the string buffer now.\n */\n endp = str;\n if( frontp != str )\n {\n while( *frontp ) { *endp++ = *frontp++; }\n *endp = '\\0';\n }\n\n return str;\n}\n #include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n\n/* Paste function from above here. */\n\nint main()\n{\n /* The test prints the following:\n [nothing to trim] -> [nothing to trim]\n [ trim the front] -> [trim the front]\n [trim the back ] -> [trim the back]\n [ trim front and back ] -> [trim front and back]\n [ trim one char front and back ] -> [trim one char front and back]\n [ trim one char front] -> [trim one char front]\n [trim one char back ] -> [trim one char back]\n [ ] -> []\n [ ] -> []\n [a] -> [a]\n [] -> []\n */\n\n char *sample_strings[] =\n {\n \"nothing to trim\",\n \" trim the front\",\n \"trim the back \",\n \" trim front and back \",\n \" trim one char front and back \",\n \" trim one char front\",\n \"trim one char back \",\n \" \",\n \" \",\n \"a\",\n \"\",\n NULL\n };\n char test_buffer[64];\n char comparison_buffer[64];\n size_t index, compare_pos;\n\n for( index = 0; sample_strings[index] != NULL; ++index )\n {\n // Fill buffer with known value to verify we do not write past the end of the string.\n memset( test_buffer, 0xCC, sizeof(test_buffer) );\n strcpy( test_buffer, sample_strings[index] );\n memcpy( comparison_buffer, test_buffer, sizeof(comparison_buffer));\n\n printf(\"[%s] -> [%s]\\n\", sample_strings[index],\n trim(test_buffer));\n\n for( compare_pos = strlen(comparison_buffer);\n compare_pos < sizeof(comparison_buffer);\n ++compare_pos )\n {\n if( test_buffer[compare_pos] != comparison_buffer[compare_pos] )\n {\n printf(\"Unexpected change to buffer @ index %u: %02x (expected %02x)\\n\",\n compare_pos, (unsigned char) test_buffer[compare_pos], (unsigned char) comparison_buffer[compare_pos]);\n }\n }\n }\n\n return 0;\n}\n"
},
{
"answer_id": 122986,
"author": "sfink",
"author_id": 14528,
"author_profile": "https://Stackoverflow.com/users/14528",
"pm_score": 0,
"selected": false,
"text": "void inplace_trim(char* s)\n{\n int start, end = strlen(s);\n for (start = 0; isspace(s[start]); ++start) {}\n if (s[start]) {\n while (end > 0 && isspace(s[end-1]))\n --end;\n memmove(s, &s[start], end - start);\n }\n s[end - start] = '\\0';\n}\n\nchar* copy_trim(const char* s)\n{\n int start, end;\n for (start = 0; isspace(s[start]); ++start) {}\n for (end = strlen(s); end > 0 && isspace(s[end-1]); --end) {}\n return strndup(s + start, end - start);\n}\n strndup() r = strdup(s + start);\nr[end-start] = '\\0';\n"
},
{
"answer_id": 123724,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 5,
"selected": false,
"text": "void trim(char * s) {\n char * p = s;\n int l = strlen(p);\n\n while(isspace(p[l - 1])) p[--l] = 0;\n while(* p && isspace(* p)) ++p, --l;\n\n memmove(s, p, l + 1);\n} \n char * trim(char * s) {\n int l = strlen(s);\n\n while(isspace(s[l - 1])) --l;\n while(* s && isspace(* s)) ++s, --l;\n\n return strndup(s, l);\n}\n"
},
{
"answer_id": 125378,
"author": "James Antill",
"author_id": 10314,
"author_profile": "https://Stackoverflow.com/users/10314",
"pm_score": 2,
"selected": false,
"text": "Ustr *s1 = USTR1(\\7, \" 12345 \");\n\nustr_sc_trim_cstr(&s1, \" \");\nassert(ustr_cmp_cstr_eq(s1, \"12345\"));"
},
{
"answer_id": 1845096,
"author": "Balkrishna Talele",
"author_id": 175374,
"author_profile": "https://Stackoverflow.com/users/175374",
"pm_score": 0,
"selected": false,
"text": "#include \"stdafx.h\"\n#include \"malloc.h\"\n#include \"string.h\"\n\nint main(int argc, char* argv[])\n{\n\n char *ptr = (char*)malloc(sizeof(char)*30);\n strcpy(ptr,\" Hel lo wo rl d G eo rocks!!! by shahil sucks b i g tim e\");\n\n int i = 0, j = 0;\n\n while(ptr[j]!='\\0')\n {\n\n if(ptr[j] == ' ' )\n {\n j++;\n ptr[i] = ptr[j];\n }\n else\n {\n i++;\n j++;\n ptr[i] = ptr[j];\n }\n }\n\n\n printf(\"\\noutput-%s\\n\",ptr);\n return 0;\n}"
},
{
"answer_id": 2452438,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "rtrim() #include <ctype.h>\n#include <string.h>\n\n/*\n Public domain implementations of in-place string trim functions\n\n Michael Burr\n michael.burr@nth-element.com\n 2010\n*/\n\nchar* ltrim(char* s) \n{\n char* newstart = s;\n\n while (isspace( *newstart)) {\n ++newstart;\n }\n\n // newstart points to first non-whitespace char (which might be '\\0')\n memmove( s, newstart, strlen( newstart) + 1); // don't forget to move the '\\0' terminator\n\n return s;\n}\n\n\nchar* rtrim( char* s)\n{\n char* end = s + strlen( s);\n\n // find the last non-whitespace character\n while ((end != s) && isspace( *(end-1))) {\n --end;\n }\n\n // at this point either (end == s) and s is either empty or all whitespace\n // so it needs to be made empty, or\n // end points just past the last non-whitespace character (it might point\n // at the '\\0' terminator, in which case there's no problem writing\n // another there). \n *end = '\\0';\n\n return s;\n}\n\nchar* trim( char* s)\n{\n return rtrim( ltrim( s));\n}\n"
},
{
"answer_id": 3042515,
"author": "Shoots the Moon",
"author_id": 366892,
"author_profile": "https://Stackoverflow.com/users/366892",
"pm_score": 4,
"selected": false,
"text": "#ifndef STRLIB_H_\n#define STRLIB_H_ 1\nenum strtrim_mode_t {\n STRLIB_MODE_ALL = 0, \n STRLIB_MODE_RIGHT = 0x01, \n STRLIB_MODE_LEFT = 0x02, \n STRLIB_MODE_BOTH = 0x03\n};\n\nchar *strcpytrim(char *d, // destination\n char *s, // source\n int mode,\n char *delim\n );\n\nchar *strtriml(char *d, char *s);\nchar *strtrimr(char *d, char *s);\nchar *strtrim(char *d, char *s); \nchar *strkill(char *d, char *s);\n\nchar *triml(char *s);\nchar *trimr(char *s);\nchar *trim(char *s);\nchar *kill(char *s);\n#endif\n #include <strlib.h>\n\nchar *strcpytrim(char *d, // destination\n char *s, // source\n int mode,\n char *delim\n ) {\n char *o = d; // save orig\n char *e = 0; // end space ptr.\n char dtab[256] = {0};\n if (!s || !d) return 0;\n\n if (!delim) delim = \" \\t\\n\\f\";\n while (*delim) \n dtab[*delim++] = 1;\n\n while ( (*d = *s++) != 0 ) { \n if (!dtab[0xFF & (unsigned int)*d]) { // Not a match char\n e = 0; // Reset end pointer\n } else {\n if (!e) e = d; // Found first match.\n\n if ( mode == STRLIB_MODE_ALL || ((mode != STRLIB_MODE_RIGHT) && (d == o)) ) \n continue;\n }\n d++;\n }\n if (mode != STRLIB_MODE_LEFT && e) { // for everything but trim_left, delete trailing matches.\n *e = 0;\n }\n return o;\n}\n\n// perhaps these could be inlined in strlib.h\nchar *strtriml(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_LEFT, 0); }\nchar *strtrimr(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_RIGHT, 0); }\nchar *strtrim(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_BOTH, 0); }\nchar *strkill(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_ALL, 0); }\n\nchar *triml(char *s) { return strcpytrim(s, s, STRLIB_MODE_LEFT, 0); }\nchar *trimr(char *s) { return strcpytrim(s, s, STRLIB_MODE_RIGHT, 0); }\nchar *trim(char *s) { return strcpytrim(s, s, STRLIB_MODE_BOTH, 0); }\nchar *kill(char *s) { return strcpytrim(s, s, STRLIB_MODE_ALL, 0); }\n strcpy"
},
{
"answer_id": 3975465,
"author": "Swiss",
"author_id": 84955,
"author_profile": "https://Stackoverflow.com/users/84955",
"pm_score": 3,
"selected": false,
"text": "void trim(char *str)\n{\n int i;\n int begin = 0;\n int end = strlen(str) - 1;\n\n while (isspace((unsigned char) str[begin]))\n begin++;\n\n while ((end >= begin) && isspace((unsigned char) str[end]))\n end--;\n\n // Shift all characters back to the start of the string array.\n for (i = begin; i <= end; i++)\n str[i - begin] = str[i];\n\n str[i - begin] = '\\0'; // Null terminate string.\n}\n"
},
{
"answer_id": 4505533,
"author": "Rhys Ulerich",
"author_id": 103640,
"author_profile": "https://Stackoverflow.com/users/103640",
"pm_score": 2,
"selected": false,
"text": "#include <ctype.h>\n\nvoid trim(char * const a)\n{\n char *p = a, *q = a;\n while (isspace(*q)) ++q;\n while (*q) *p++ = *q++;\n *p = '\\0';\n while (p > a && isspace(*--p)) *p = '\\0';\n}\n\n/* See http://fctx.wildbearsoftware.com/ */\n#include \"fct.h\"\n\nFCT_BGN()\n{\n FCT_QTEST_BGN(trim)\n {\n { char s[] = \"\"; trim(s); fct_chk_eq_str(\"\", s); } // Trivial\n { char s[] = \" \"; trim(s); fct_chk_eq_str(\"\", s); } // Trivial\n { char s[] = \"\\t\"; trim(s); fct_chk_eq_str(\"\", s); } // Trivial\n { char s[] = \"a\"; trim(s); fct_chk_eq_str(\"a\", s); } // NOP\n { char s[] = \"abc\"; trim(s); fct_chk_eq_str(\"abc\", s); } // NOP\n { char s[] = \" a\"; trim(s); fct_chk_eq_str(\"a\", s); } // Leading\n { char s[] = \" a c\"; trim(s); fct_chk_eq_str(\"a c\", s); } // Leading\n { char s[] = \"a \"; trim(s); fct_chk_eq_str(\"a\", s); } // Trailing\n { char s[] = \"a c \"; trim(s); fct_chk_eq_str(\"a c\", s); } // Trailing\n { char s[] = \" a \"; trim(s); fct_chk_eq_str(\"a\", s); } // Both\n { char s[] = \" a c \"; trim(s); fct_chk_eq_str(\"a c\", s); } // Both\n\n // Villemoes pointed out an edge case that corrupted memory. Thank you.\n // http://stackoverflow.com/questions/122616/#comment23332594_4505533\n {\n char s[] = \"a \"; // Buffer with whitespace before s + 2\n trim(s + 2); // Trim \" \" containing only whitespace\n fct_chk_eq_str(\"\", s + 2); // Ensure correct result from the trim\n fct_chk_eq_str(\"a \", s); // Ensure preceding buffer not mutated\n }\n\n // doukremt suggested I investigate this test case but\n // did not indicate the specific behavior that was objectionable.\n // http://stackoverflow.com/posts/comments/33571430\n {\n char s[] = \" foobar\"; // Shifted across whitespace\n trim(s); // Trim\n fct_chk_eq_str(\"foobar\", s); // Leading string is correct\n\n // Here is what the algorithm produces:\n char r[16] = { 'f', 'o', 'o', 'b', 'a', 'r', '\\0', ' ', \n ' ', 'f', 'o', 'o', 'b', 'a', 'r', '\\0'};\n fct_chk_eq_int(0, memcmp(s, r, sizeof(s)));\n }\n }\n FCT_QTEST_END();\n}\nFCT_END();\n"
},
{
"answer_id": 5916192,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 0,
"selected": false,
"text": "strlen() static char const WHITESPACE[] = \" \\t\\n\\r\";\n\nstatic void get_trim_bounds(char const *s,\n char const **firstWord,\n char const **trailingSpace)\n{\n char const *lastWord;\n *firstWord = lastWord = s + strspn(s, WHITESPACE);\n do\n {\n *trailingSpace = lastWord + strcspn(lastWord, WHITESPACE);\n lastWord = *trailingSpace + strspn(*trailingSpace, WHITESPACE);\n }\n while (*lastWord != '\\0');\n}\n\nchar *copy_trim(char const *s)\n{\n char const *firstWord, *trailingSpace;\n char *result;\n size_t newLength;\n\n get_trim_bounds(s, &firstWord, &trailingSpace);\n newLength = trailingSpace - firstWord;\n\n result = malloc(newLength + 1);\n memcpy(result, firstWord, newLength);\n result[newLength] = '\\0';\n return result;\n}\n\nvoid inplace_trim(char *s)\n{\n char const *firstWord, *trailingSpace;\n size_t newLength;\n\n get_trim_bounds(s, &firstWord, &trailingSpace);\n newLength = trailingSpace - firstWord;\n\n memmove(s, firstWord, newLength);\n s[newLength] = '\\0';\n}\n"
},
{
"answer_id": 11539150,
"author": "stars",
"author_id": 1534429,
"author_profile": "https://Stackoverflow.com/users/1534429",
"pm_score": -1,
"selected": false,
"text": "#include<stdio.h>\n#include<ctype.h>\n\nmain()\n{\n char sent[10]={' ',' ',' ','s','t','a','r','s',' ',' '};\n int i,j=0;\n char rec[10];\n\n for(i=0;i<=10;i++)\n {\n if(!isspace(sent[i]))\n {\n\n rec[j]=sent[i];\n j++;\n }\n }\n\nprintf(\"\\n%s\\n\",rec);\n\n}\n"
},
{
"answer_id": 14978802,
"author": "Michał Gawlas",
"author_id": 1678108,
"author_profile": "https://Stackoverflow.com/users/1678108",
"pm_score": 0,
"selected": false,
"text": "static const char *WhiteSpace=\" \\n\\r\\t\";\nchar* trim(char *t)\n{\n char *e=t+(t!=NULL?strlen(t):0); // *e initially points to end of string\n if (t==NULL) return;\n do --e; while (strchr(WhiteSpace, *e) && e>=t); // Find last char that is not \\r\\n\\t\n *(++e)=0; // Null-terminate\n e=t+strspn (t,WhiteSpace); // Find first char that is not \\t\n return e>t?memmove(t,e,strlen(e)+1):t; // memmove string contents and terminator\n}\n"
},
{
"answer_id": 16693536,
"author": "Telc",
"author_id": 869113,
"author_profile": "https://Stackoverflow.com/users/869113",
"pm_score": 0,
"selected": false,
"text": "#include <string.h>\n\nvoid rstrip(char *string)\n{\n int l;\n if (!string)\n return;\n l = strlen(string) - 1;\n while (isspace(string[l]) && l >= 0)\n string[l--] = 0;\n}\n\nvoid lstrip(char *string)\n{\n int i, l;\n if (!string)\n return;\n l = strlen(string);\n while (isspace(string[(i = 0)]))\n while(i++ < l)\n string[i-1] = string[i];\n}\n\nvoid strip(char *string)\n{\n lstrip(string);\n rstrip(string);\n}\n"
},
{
"answer_id": 19441143,
"author": "Carthi",
"author_id": 1992435,
"author_profile": "https://Stackoverflow.com/users/1992435",
"pm_score": 0,
"selected": false,
"text": "char ausCaptain[]=\"GeorgeBailey \"; StrTrim(ausCaptain,\" \"); ausCaptain \"GeorgeBailey\" \"GeorgeBailey \""
},
{
"answer_id": 24168813,
"author": "Daniel",
"author_id": 1531346,
"author_profile": "https://Stackoverflow.com/users/1531346",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n\nint main()\n{\n const char *target = \" haha \";\n char buf[256];\n sscanf(target, \"%s\", buf); // Trimming on both sides occurs here\n printf(\"<%s>\\n\", buf);\n}\n"
},
{
"answer_id": 26063378,
"author": "Oleksiy",
"author_id": 1214101,
"author_profile": "https://Stackoverflow.com/users/1214101",
"pm_score": -1,
"selected": false,
"text": "/**\n * skip_spaces - Removes leading whitespace from @s.\n * @s: The string to be stripped.\n *\n * Returns a pointer to the first non-whitespace character in @s.\n */\nchar *skip_spaces(const char *str)\n{\n while (isspace(*str))\n ++str;\n return (char *)str;\n}\n\n/**\n * strim - Removes leading and trailing whitespace from @s.\n * @s: The string to be stripped.\n *\n * Note that the first trailing whitespace is replaced with a %NUL-terminator\n * in the given string @s. Returns a pointer to the first non-whitespace\n * character in @s.\n */\nchar *strim(char *s)\n{\n size_t size;\n char *end;\n\n size = strlen(s);\n\n if (!size)\n return s;\n\n end = s + size - 1;\n while (end >= s && isspace(*end))\n end--;\n *(end + 1) = '\\0';\n\n return skip_spaces(s);\n}\n /**\n * trim spaces\n **/\nchar * trim_inplace(char * s, int len)\n{\n // trim leading\n while (len && isspace(s[0]))\n {\n s++; len--;\n }\n\n // trim trailing\n while (len && isspace(s[len - 1]))\n {\n s[len - 1] = 0; len--;\n }\n\n return s;\n}\n"
},
{
"answer_id": 26984026,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 3,
"selected": false,
"text": "char char *s unsigned char int unsigned char EOF #include <ctype.h>\n\n// Return a pointer to the trimmed string\nchar *string_trim_inplace(char *s) {\n while (isspace((unsigned char) *s)) s++;\n if (*s) {\n char *p = s;\n while (*p) p++;\n while (isspace((unsigned char) *(--p)));\n p[1] = '\\0';\n }\n\n // If desired, shift the trimmed string\n\n return s;\n}\n // Return a pointer to the (shifted) trimmed string\nchar *string_trim_inplace(char *s) {\n char *original = s;\n size_t len = 0;\n\n while (isspace((unsigned char) *s)) {\n s++;\n } \n if (*s) {\n char *p = s;\n while (*p) p++;\n while (isspace((unsigned char) *(--p)));\n p[1] = '\\0';\n // len = (size_t) (p - s); // older errant code\n len = (size_t) (p - s + 1); // Thanks to @theriver\n }\n\n return (s == original) ? s : memmove(original, s, len + 1);\n}\n"
},
{
"answer_id": 33599020,
"author": "wallek876",
"author_id": 4394382,
"author_profile": "https://Stackoverflow.com/users/4394382",
"pm_score": 1,
"selected": false,
"text": "void trimString(char *string)\n{\n size_t i = 0, j = strlen(string);\n while (j > 0 && isspace((unsigned char)string[j - 1])) string[--j] = '\\0';\n while (isspace((unsigned char)string[i])) i++;\n if (i > 0) memmove(string, string + i, j - i + 1);\n}\n"
},
{
"answer_id": 33757317,
"author": "Jason Stewart",
"author_id": 3277205,
"author_profile": "https://Stackoverflow.com/users/3277205",
"pm_score": 2,
"selected": false,
"text": "void fnStrTrimInPlace(char *szWrite) {\n\n const char *szWriteOrig = szWrite;\n char *szLastSpace = szWrite, *szRead = szWrite;\n int bNotSpace;\n\n // SHIFT STRING, STARTING AT FIRST NON-SPACE CHAR, LEFTMOST\n while( *szRead != '\\0' ) {\n\n bNotSpace = !isspace((unsigned char)(*szRead));\n\n if( (szWrite != szWriteOrig) || bNotSpace ) {\n\n *szWrite = *szRead;\n szWrite++;\n\n // TRACK POINTER TO LAST NON-SPACE\n if( bNotSpace )\n szLastSpace = szWrite;\n }\n\n szRead++;\n }\n\n // TERMINATE AFTER LAST NON-SPACE (OR BEGINNING IF THERE WAS NO NON-SPACE)\n *szLastSpace = '\\0';\n}\n"
},
{
"answer_id": 34766453,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": -1,
"selected": false,
"text": "std::string Trimed(const std::string& s)\n{\n std::string::const_iterator begin = std::find_if(s.begin(),\n s.end(),\n [](char ch) { return !std::isspace(ch); });\n\n std::string::const_iterator end = std::find_if(s.rbegin(),\n s.rend(),\n [](char ch) { return !std::isspace(ch); }).base();\n return std::string(begin, end);\n}\n"
},
{
"answer_id": 35305045,
"author": "Mitch",
"author_id": 329999,
"author_profile": "https://Stackoverflow.com/users/329999",
"pm_score": -1,
"selected": false,
"text": "void trim(char* const str)\n{\n char* begin = str;\n char* end = str;\n while (isspace(*begin))\n {\n ++begin;\n }\n char* s = begin;\n while (*s != '\\0')\n {\n if (!isspace(*s++))\n {\n end = s;\n }\n }\n *end = '\\0';\n const int dist = end - begin;\n if (begin > str && dist > 0)\n {\n memmove(str, begin, dist + 1);\n }\n}\n"
},
{
"answer_id": 35574577,
"author": "Деян Добромиров",
"author_id": 4170264,
"author_profile": "https://Stackoverflow.com/users/4170264",
"pm_score": 0,
"selected": false,
"text": "char *trimAll(char *strData)\n{\n unsigned int L = strlen(strData);\n if(L > 0){ L--; }else{ return strData; }\n size_t S = 0, E = L;\n while((!(strData[S] > ' ') || !(strData[E] > ' ')) && (S >= 0) && (S <= L) && (E >= 0) && (E <= L))\n {\n if(strData[S] <= ' '){ S++; }\n if(strData[E] <= ' '){ E--; }\n }\n if(S == 0 && E == L){ return strData; } // Nothing to be done\n if((S >= 0) && (S <= L) && (E >= 0) && (E <= L)){\n L = E - S + 1;\n memmove(strData,&strData[S],L); strData[L] = '\\0';\n }else{ strData[0] = '\\0'; }\n return strData;\n}\n"
},
{
"answer_id": 35899634,
"author": "Vaner Magalhaes",
"author_id": 5731423,
"author_profile": "https://Stackoverflow.com/users/5731423",
"pm_score": -1,
"selected": false,
"text": "void trim(char* string) {\n int lenght = strlen(string);\n int i=0;\n\n while(string[0] ==' ') {\n for(i=0; i<lenght; i++) {\n string[i] = string[i+1];\n }\n lenght--;\n }\n\n\n for(i=lenght-1; i>0; i--) {\n if(string[i] == ' ') {\n string[i] = '\\0';\n } else {\n break;\n }\n }\n}\n"
},
{
"answer_id": 39931573,
"author": "sleepycal",
"author_id": 1267398,
"author_profile": "https://Stackoverflow.com/users/1267398",
"pm_score": 2,
"selected": false,
"text": "glib"
},
{
"answer_id": 45582189,
"author": "Ekeyme Mo",
"author_id": 4988506,
"author_profile": "https://Stackoverflow.com/users/4988506",
"pm_score": 1,
"selected": false,
"text": "// Trims leading whitespace chars in left `str`, then copy at almost `n - 1` chars\n// into the `out` buffer in which copying might stop when the first '\\0' occurs, \n// and finally append '\\0' to the position of the last non-trailing whitespace char.\n// Reture the length the trimed string which '\\0' is not count in like strlen().\nsize_t trim(char *out, size_t n, const char *str)\n{\n // do nothing\n if(n == 0) return 0; \n\n // ptr stop at the first non-leading space char\n while(isspace(*str)) str++; \n\n if(*str == '\\0') {\n out[0] = '\\0';\n return 0;\n } \n\n size_t i = 0; \n\n // copy char to out until '\\0' or i == n - 1\n for(i = 0; i < n - 1 && *str != '\\0'; i++){\n out[i] = *str++;\n } \n\n // deal with the trailing space\n while(isspace(out[--i])); \n\n out[++i] = '\\0';\n return i;\n}\n"
},
{
"answer_id": 48563040,
"author": "saeed_falahat",
"author_id": 5958242,
"author_profile": "https://Stackoverflow.com/users/5958242",
"pm_score": 0,
"selected": false,
"text": "#include<stdio.h>\n#include<stdlib.h>\n\nchar *trimStr(char *str){\nchar *tmp = str;\nprintf(\"input string %s\\n\",str);\nint nc = 0;\n\nwhile(*tmp!='\\0'){\n if (*tmp != ' '){\n nc++;\n }\n tmp++;\n}\nprintf(\"total nonempty characters are %d\\n\",nc);\nchar *trim = NULL;\n\ntrim = malloc(sizeof(char)*(nc+1));\nif (trim == NULL) return NULL;\ntmp = str;\nint ne = 0;\n\nwhile(*tmp!='\\0'){\n if (*tmp != ' '){\n trim[ne] = *tmp;\n ne++;\n }\n tmp++;\n}\ntrim[nc] = '\\0';\n\nprintf(\"trimmed string is %s\\n\",trim);\n\nreturn trim; \n }\n\n\nint main(void){\n\nchar str[] = \" s ta ck ove r fl o w \";\n\nchar *trim = trimStr(str);\n\nif (trim != NULL )free(trim);\n\nreturn 0;\n}\n"
},
{
"answer_id": 50087045,
"author": "Zibri",
"author_id": 236062,
"author_profile": "https://Stackoverflow.com/users/236062",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n\nint main()\n{\nchar *foo=\" teststring \";\nchar *bar;\nsscanf(foo,\"%s\",bar);\nprintf(\"String is >%s<\\n\",bar);\n return 0;\n}\n"
},
{
"answer_id": 50881315,
"author": "Isaac To",
"author_id": 4635580,
"author_profile": "https://Stackoverflow.com/users/4635580",
"pm_score": 0,
"selected": false,
"text": "#include <ctype.h>\n#include <string.h>\nvoid trim_str(char *s)\n{\n const size_t s_len = strlen(s);\n\n int i;\n for (i = 0; i < s_len; i++)\n {\n if (!isspace( (unsigned char) s[i] )) break;\n }\n\n if (i == s_len)\n {\n // s is an empty string or contains only space characters\n\n s[0] = '\\0';\n }\n else\n {\n // s contains non-space characters\n\n const char *non_space_beginning = s + i;\n\n char *non_space_ending = s + s_len - 1;\n while ( isspace( (unsigned char) *non_space_ending ) ) non_space_ending--;\n\n size_t trimmed_s_len = non_space_ending - non_space_beginning + 1;\n\n if (s != non_space_beginning)\n {\n // Non-space characters exist in the beginning of s\n\n memmove(s, non_space_beginning, trimmed_s_len);\n }\n\n s[trimmed_s_len] = '\\0';\n }\n}\n"
},
{
"answer_id": 51215136,
"author": "David R Tribble",
"author_id": 170383,
"author_profile": "https://Stackoverflow.com/users/170383",
"pm_score": 2,
"selected": false,
"text": "#include <stddef.h>\n#include <ctype.h>\n\nchar * trim2(char *d, const char *s)\n{\n // Sanity checks\n if (s == NULL || d == NULL)\n return NULL;\n\n // Skip leading spaces \n const unsigned char * p = (const unsigned char *)s;\n while (isspace(*p))\n p++;\n\n // Copy the string\n unsigned char * dst = (unsigned char *)d; // d and s can be the same\n unsigned char * end = dst;\n while (*p != '\\0')\n {\n if (!isspace(*dst++ = *p++))\n end = dst;\n }\n\n // Truncate trailing spaces\n *end = '\\0';\n return d;\n}\n\nchar * trim(char *s)\n{\n return trim2(s, s);\n}\n"
},
{
"answer_id": 51716928,
"author": "Mitch Laber",
"author_id": 9133063,
"author_profile": "https://Stackoverflow.com/users/9133063",
"pm_score": 0,
"selected": false,
"text": "char* strtrim(char* const str)\n{\n if (str != nullptr)\n {\n char const* begin{ str };\n while (std::isspace(*begin))\n {\n ++begin;\n }\n\n auto end{ begin };\n auto scout{ begin };\n while (*scout != '\\0')\n {\n if (!std::isspace(*scout++))\n {\n end = scout;\n }\n }\n\n auto /* std::ptrdiff_t */ const length{ end - begin };\n if (begin != str)\n {\n std::memmove(str, begin, length);\n }\n\n str[length] = '\\0';\n }\n\n return str;\n}\n"
},
{
"answer_id": 52674830,
"author": "poby",
"author_id": 1593044,
"author_profile": "https://Stackoverflow.com/users/1593044",
"pm_score": 1,
"selected": false,
"text": "free void stripWS_LT(char *str)\n{\n char *a = str, *b = str;\n while (isspace((unsigned char)*a)) a++;\n while (*b = *a++) b++;\n while (b > str && isspace((unsigned char)*--b)) *b = 0;\n}\n"
},
{
"answer_id": 53989226,
"author": "rashok",
"author_id": 596370,
"author_profile": "https://Stackoverflow.com/users/596370",
"pm_score": 1,
"selected": false,
"text": "#include <ctype.h>\n#include <string.h>\n\nchar *trim_space(char *in)\n{\n char *out = NULL;\n int len;\n if (in) {\n len = strlen(in);\n while(len && isspace(in[len - 1])) --len;\n while(len && *in && isspace(*in)) ++in, --len;\n if (len) {\n out = strndup(in, len);\n }\n }\n return out;\n}\n isspace strndup"
},
{
"answer_id": 58016995,
"author": "Humpity",
"author_id": 2779074,
"author_profile": "https://Stackoverflow.com/users/2779074",
"pm_score": 1,
"selected": false,
"text": "isspace() void trim (char *s) // trim leading and trailing spaces+tabs\n{\n int i,j,k, len;\n\n j=k=0;\n len = strlen(s);\n // find start of string\n for (i=0; i<len; i++) if ((s[i]!=32) && (s[i]!=9)) { j=i; break; }\n // find end of string+1\n for (i=len-1; i>=j; i--) if ((s[i]!=32) && (s[i]!=9)) { k=i+1; break;} \n\n if (k<=j) {s[0]=0; return;} // all whitespace (j==k==0)\n\n len=k-j;\n for (i=0; i<len; i++) s[i] = s[j++]; // shift result to start of string\n s[i]=0; // end the string\n\n}//_trim\n"
},
{
"answer_id": 59202547,
"author": "Ace.C",
"author_id": 6191970,
"author_profile": "https://Stackoverflow.com/users/6191970",
"pm_score": 0,
"selected": false,
"text": "// only used for printf in main\n#include <stdio.h>\n\n// note the char ** means we can modify the address\nchar *trimws(char **strp) { \n char *str;\n // check if empty string\n if(!*str)\n return;\n // go to the end of the string\n for (str = *strp; *str; str++) \n ;\n // back up one from the null terminator\n str--; \n // set trailing ws to null\n for (; *str == ' '; str--) \n *str = 0;\n // increment past leading ws\n for (str = *strp; *str == ' '; str++) \n ;\n // set new begin address of string\n *strp = str; \n}\n\nint main(void) {\n char buf[256] = \" whitespace \";\n // pointer must be modifiable lvalue so we make bufp\n char **bufp = &buf;\n // pass in the address\n trimws(&bufp);\n // prints : XXXwhitespaceXXX\n printf(\"XXX%sXXX\\n\", bufp); \n return 0;\n}\n"
},
{
"answer_id": 67239486,
"author": "hesed",
"author_id": 10152015,
"author_profile": "https://Stackoverflow.com/users/10152015",
"pm_score": 0,
"selected": false,
"text": "strlen isspace char *\ntrim (char * s, char c)\n{\n unsigned o = 0;\n char * sb = s;\n\n for (; *s == c; s++)\n o++;\n\n for (; *s != '\\0'; s++)\n continue;\n for (; s - o > sb && *--s == c;)\n continue;\n\n if (o > 0)\n memmove(sb, sb + o, s + 1 - o - sb);\n if (*s != '\\0')\n *(s + 1 - o) = '\\0';\n\n return sb;\n}\n"
},
{
"answer_id": 71442959,
"author": "James M. Lay",
"author_id": 1461154,
"author_profile": "https://Stackoverflow.com/users/1461154",
"pm_score": 1,
"selected": false,
"text": "strtok(3) char *trimmed = strtok(input, \"\\r\\t\\n \");\n \" +1.123.456.7890 \"\n\" 01-01-2020\\n\"\n\"\\t2.523\"\n \" hi there \""
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14463/"
] |
122,639
|
<p>I have a temp table with the exact structure of a concrete table <code>T</code>. It was created like this: </p>
<pre><code>select top 0 * into #tmp from T
</code></pre>
<p>After processing and filling in content into <code>#tmp</code>, I want to copy the content back to <code>T</code> like this: </p>
<pre><code>insert into T select * from #tmp
</code></pre>
<p>This is okay as long as <code>T</code> doesn't have identity column, but in my case it does. Is there any way I can ignore the auto-increment identity column from <code>#tmp</code> when I copy to <code>T</code>? My motivation is to avoid having to spell out every column name in the Insert Into list. </p>
<p>EDIT: toggling identity_insert wouldn't work because the pkeys in <code>#tmp</code> may collide with those in <code>T</code> if rows were inserted into <code>T</code> outside of my script, that's if <code>#tmp</code> has auto-incremented the pkey to sync with T's in the first place. </p>
|
[
{
"answer_id": 122661,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 1,
"selected": false,
"text": "set identity_insert on\n"
},
{
"answer_id": 122699,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "SELECT * INSERT"
},
{
"answer_id": 122720,
"author": "DK.",
"author_id": 16886,
"author_profile": "https://Stackoverflow.com/users/16886",
"pm_score": 4,
"selected": true,
"text": "alter table #tmp drop column id\n create table T(ID int identity(1,1) not null, Value nvarchar(50))\ninsert into T (Value) values (N'Hello T!')\nselect top 0 * into #tmp from T\nalter table #tmp drop column ID\ninsert into #tmp (Value) values (N'Hello #tmp')\ninsert into T select * from #tmp\ndrop table #tmp\nselect * from T\ndrop table T\n"
},
{
"answer_id": 44634113,
"author": "sǝɯɐſ",
"author_id": 1579626,
"author_profile": "https://Stackoverflow.com/users/1579626",
"pm_score": 3,
"selected": false,
"text": "select * into without_id from with_id\nunion all\nselect * from with_id where 1 = 0\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10088/"
] |
122,641
|
<p>I have email addresses encoded with HTML character entities. Is there anything in .NET that can convert them to plain strings?</p>
|
[
{
"answer_id": 122650,
"author": "Daniel Schierbeck",
"author_id": 20321,
"author_profile": "https://Stackoverflow.com/users/20321",
"pm_score": 3,
"selected": false,
"text": "Server.HtmlDecode < > Server.HtmlEncode"
},
{
"answer_id": 122658,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 10,
"selected": true,
"text": "HttpUtility.HtmlDecode WebUtility.HtmlDecode System.Net"
},
{
"answer_id": 122835,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 6,
"selected": false,
"text": "System.Web.dll System.Web.dll System.Web.HttpUtility.HtmlDecode using System.Web"
},
{
"answer_id": 2639653,
"author": "Indy9000",
"author_id": 85150,
"author_profile": "https://Stackoverflow.com/users/85150",
"pm_score": 8,
"selected": false,
"text": "System.Net.WebUtility.HtmlDecode()\n"
},
{
"answer_id": 38024688,
"author": "Hypershadsy",
"author_id": 1364757,
"author_profile": "https://Stackoverflow.com/users/1364757",
"pm_score": 3,
"selected": false,
"text": "HtmlAgilityPack.HtmlEntity.DeEntitize() string string"
},
{
"answer_id": 40651824,
"author": "Abhishek Jaiswal",
"author_id": 5275530,
"author_profile": "https://Stackoverflow.com/users/5275530",
"pm_score": 4,
"selected": false,
"text": "string s = \"Svendborg Værft A/S\";\nstring a = HttpUtility.HtmlDecode(s);\nResponse.Write(a);\n Svendborg Værft A/S\n"
},
{
"answer_id": 50526007,
"author": "Tahir Alvi",
"author_id": 355191,
"author_profile": "https://Stackoverflow.com/users/355191",
"pm_score": 1,
"selected": false,
"text": "using System.Web.HttpUtility public static string HtmlEncode(string text)\n {\n if(text.length > 0){\n\n return HttpUtility.HtmlDecode(text);\n }else{\n\n return text;\n }\n\n }\n"
},
{
"answer_id": 52627634,
"author": "Vinod Srivastav",
"author_id": 3057246,
"author_profile": "https://Stackoverflow.com/users/3057246",
"pm_score": 1,
"selected": false,
"text": "System.net.dll using System.Net; // Html encode/decode\n public static string HtmDecode(this string htmlEncodedString)\n {\n if(htmlEncodedString.Length > 0)\n {\n return System.Net.WebUtility.HtmlDecode(htmlEncodedString);\n }\n else\n {\n return htmlEncodedString;\n }\n }\n\n public static string HtmEncode(this string htmlDecodedString)\n {\n if(htmlDecodedString.Length > 0)\n {\n return System.Net.WebUtility.HtmlEncode(htmlDecodedString);\n }\n else\n {\n return htmlDecodedString;\n }\n }\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
] |
122,649
|
<p>I'm looking for a simple, easy to understand algorithm to alphabetically sort an array of characters in C.</p>
|
[
{
"answer_id": 122671,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 0,
"selected": false,
"text": "int[] bubble(int a[])\n {\n for (int i = a.length; --i>=0; )\n {\n for (int j = 0; j<i; j++)\n {\n if (a[j] > a[j+1])\n {\n int T = a[j];\n a[j] = a[j+1];\n a[j+1] = T;\n }\n }\n }\n return(a);\n }\n"
},
{
"answer_id": 122674,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 4,
"selected": true,
"text": "man qsort"
},
{
"answer_id": 122697,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 2,
"selected": false,
"text": "#include <stdlib.h>\n\nint char_compare (const void * a, const void * b)\n{\n return *(const char *)a - *(const char *)b;\n}\n\nint main(){\n const char char_array[] = { 'c', 'a', 'b' };\n\n qsort (char_array, 3, sizeof(char), char_compare);\n\n return 0;\n}\n"
},
{
"answer_id": 3332765,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 0,
"selected": false,
"text": "const unsigned char in[N];\nunsigned char out[N], *p=out;\nsize_t cnt[N]={0}, i, j;\nfor (i=0; i<COUNT; i++) cnt[in[i]]++;\nfor (i=0; i<256; i++) for (j=cnt[i]; j; j--) *p++=i;\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
122,690
|
<p>I've been too lax with performing DB backups on our internal servers. </p>
<p>Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript? </p>
|
[
{
"answer_id": 122705,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 3,
"selected": false,
"text": "Use Master\n\nDeclare @ToExecute VarChar(8000)\n\nSelect @ToExecute = Coalesce(@ToExecute + 'Backup Database ' + [Name] + ' To Disk = ''D:\\Backups\\Databases\\' + [Name] + '.bak'' With Format;' + char(13),'')\nFrom\nMaster..Sysdatabases\nWhere\n[Name] Not In ('tempdb')\nand databasepropertyex ([Name],'Status') = 'online'\n\nExecute(@ToExecute)\n"
},
{
"answer_id": 122737,
"author": "Craig Trader",
"author_id": 12895,
"author_profile": "https://Stackoverflow.com/users/12895",
"pm_score": 8,
"selected": true,
"text": "\"C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Binn\\osql.exe\" \n -E -Q \"BACKUP DATABASE mydatabase TO DISK='C:\\tmp\\db.bak' WITH FORMAT\"\n"
},
{
"answer_id": 586690,
"author": "Martin Meixger",
"author_id": 64466,
"author_profile": "https://Stackoverflow.com/users/64466",
"pm_score": 3,
"selected": false,
"text": "C:\\>ExpressMaint.exe -S (local)\\sqlexpress -D ALL_USER -T DB -BU HOURS -BV 1 -B c:\\backupdir\\ -DS\n"
},
{
"answer_id": 11002314,
"author": "Ira C",
"author_id": 1451928,
"author_profile": "https://Stackoverflow.com/users/1451928",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/ksh\n#\n#.....\n(\ntsql -S {database} -U {user} -P {password} <<EOF\nselect * from {table}\ngo\nquit\nEOF\n) >{output_file.dump}\n"
},
{
"answer_id": 16754365,
"author": "John W.",
"author_id": 1893068,
"author_profile": "https://Stackoverflow.com/users/1893068",
"pm_score": 3,
"selected": false,
"text": "sqlcmd -S YOUR_SERVER_NAME\\SQLEXPRESS -E -Q \"EXEC sp_BackupDatabases @backupLocation='C:\\SQL_Backup\\', @backupType='F'\" 1>c:\\SQL_Backup\\backup.log \n"
},
{
"answer_id": 24409144,
"author": "George Vrynios",
"author_id": 1832537,
"author_profile": "https://Stackoverflow.com/users/1832537",
"pm_score": 2,
"selected": false,
"text": "\"[program dir]\\[sql server version]\\Tools\\Binn\\osql.exe\" -Q \"BACKUP DATABASE mydatabase TO DISK='C:\\tmp\\db.bak'\" -S [server] –U [login id] -P [password]"
},
{
"answer_id": 55609181,
"author": "Sagar Mahajan",
"author_id": 7901091,
"author_profile": "https://Stackoverflow.com/users/7901091",
"pm_score": 0,
"selected": false,
"text": "SET NOCOUNT ON;\ndeclare @PATH VARCHAR(200)='D:\\MyBackupFolder\\'\n -- path where you want to take backups\nIF OBJECT_ID('TEMPDB..#back') IS NOT NULL\n\nDROP TABLE #back\n\nCREATE TABLE #back\n(\nRN INT IDENTITY (1,1),\nDatabaseName NVARCHAR(200)\n\n)\n\nINSERT INTO #back \nSELECT 'MyDatabase1'\nUNION SELECT 'MyDatabase2'\nUNION SELECT 'MyDatabase3'\nUNION SELECT 'MyDatabase4'\n\n-- your databases List\n\nDECLARE @COUNT INT =0 , @RN INT =1, @SCRIPT NVARCHAR(MAX)='', @DBNAME VARCHAR(200)\n\nPRINT '---------------------FULL BACKUP SCRIPT-------------------------'+CHAR(10)\nSET @COUNT = (SELECT COUNT(*) FROM #back)\nPRINT 'USE MASTER'+CHAR(10)\nWHILE(@COUNT > = @RN)\nBEGIN\n\nSET @DBNAME =(SELECT DatabaseName FROM #back WHERE RN=@RN)\nSET @SCRIPT ='BACKUP DATABASE ' +'['+@DBNAME+']'+CHAR(10)+'TO DISK =N'''+@PATH+@DBNAME+ N'_Backup_'\n+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.bak'''+CHAR(10)+'WITH COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)\nPRINT @SCRIPT\nSET @RN=@RN+1\nEND\n\n PRINT '---------------------DIFF BACKUP SCRIPT-------------------------'+CHAR(10)\n\n SET @COUNT =0 SET @RN =1 SET @SCRIPT ='' SET @DBNAME =''\n SET @COUNT = (SELECT COUNT(*) FROM #back)\nPRINT 'USE MASTER'+CHAR(10)\nWHILE(@COUNT > = @RN)\nBEGIN\nSET @DBNAME =(SELECT DatabaseName FROM #back WHERE RN=@RN)\nSET @SCRIPT ='BACKUP DATABASE ' +'['+@DBNAME+']'+CHAR(10)+'TO DISK =N'''+@PATH+@DBNAME+ N'_Backup_'\n+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.diff'''+CHAR(10)+'WITH DIFFERENTIAL, COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)\nPRINT @SCRIPT\nSET @RN=@RN+1\nEND\n"
},
{
"answer_id": 61644743,
"author": "CraigD",
"author_id": 11311561,
"author_profile": "https://Stackoverflow.com/users/11311561",
"pm_score": 2,
"selected": false,
"text": "sqlcmd -S .\\SQLEXPRESS -E -Q \"EXEC sp_BackupDatabases @backupLocation='E:\\SQLBackups\\', @backupType='F'\" \n --// Copyright © Microsoft Corporation. All Rights Reserved.\n--// This code released under the terms of the\n--// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)\n\nUSE [master] \nGO \n\n/****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/ \n\nSET ANSI_NULLS ON \nGO \n\nSET QUOTED_IDENTIFIER ON \nGO \n\n \n-- ============================================= \n-- Author: Microsoft \n-- Create date: 2010-02-06\n-- Description: Backup Databases for SQLExpress\n-- Parameter1: databaseName \n-- Parameter2: backupType F=full, D=differential, L=log\n-- Parameter3: backup file location\n-- =============================================\n\nCREATE PROCEDURE [dbo].[sp_BackupDatabases] \n @databaseName sysname = null,\n @backupType CHAR(1),\n @backupLocation nvarchar(200) \nAS \n\n SET NOCOUNT ON; \n\n DECLARE @DBs TABLE\n (\n ID int IDENTITY PRIMARY KEY,\n DBNAME nvarchar(500)\n )\n \n -- Pick out only databases which are online in case ALL databases are chosen to be backed up\n\n -- If specific database is chosen to be backed up only pick that out from @DBs\n\n INSERT INTO @DBs (DBNAME)\n SELECT Name FROM master.sys.databases\n where state=0\n AND name=@DatabaseName\n OR @DatabaseName IS NULL\n ORDER BY Name\n\n \n -- Filter out databases which do not need to backed up\n \n IF @backupType='F'\n BEGIN\n DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')\n END\n ELSE IF @backupType='D'\n BEGIN\n DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')\n END\n ELSE IF @backupType='L'\n BEGIN\n DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')\n END\n ELSE\n BEGIN\n RETURN\n END\n \n\n -- Declare variables\n\n DECLARE @BackupName varchar(100)\n DECLARE @BackupFile varchar(100)\n DECLARE @DBNAME varchar(300)\n DECLARE @sqlCommand NVARCHAR(1000) \n DECLARE @dateTime NVARCHAR(20)\n DECLARE @Loop int \n \n -- Loop through the databases one by one\n\n SELECT @Loop = min(ID) FROM @DBs\n WHILE @Loop IS NOT NULL\n BEGIN\n \n-- Database Names have to be in [dbname] format since some have - or _ in their name\n\n SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'\n\n\n-- Set the current date and time n yyyyhhmmss format\n\n SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','') \n \n\n-- Create backup filename in path\\filename.extension format for full,diff and log backups\n\n IF @backupType = 'F'\n SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'\n ELSE IF @backupType = 'D'\n SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'\n ELSE IF @backupType = 'L'\n SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'\n \n\n-- Provide the backup a name for storing in the media\n\n IF @backupType = 'F'\n SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime\n\n IF @backupType = 'D'\n SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime\n\n IF @backupType = 'L'\n SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime\n\n\n-- Generate the dynamic SQL command to be executed\n\n IF @backupType = 'F' \n BEGIN\n SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'\n END\n\n IF @backupType = 'D'\n BEGIN\n SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT' \n END\n\n IF @backupType = 'L' \n BEGIN\n SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT' \n END\n \n\n-- Execute the generated SQL command\n\n EXEC(@sqlCommand)\n\n \n-- Goto the next database\n\nSELECT @Loop = min(ID) FROM @DBs where ID>@Loop\n \n\nEND\n"
},
{
"answer_id": 67097327,
"author": "Ashutosh Ranjan",
"author_id": 2727802,
"author_profile": "https://Stackoverflow.com/users/2727802",
"pm_score": 0,
"selected": false,
"text": "Export data using bcp utility\n/opt/mssql-tools/bin/bcp <Table_Name> out /tmp/MyData.bcp -d <database_name> -c -U <user_name> -P \"<password>\" -S <server_name>\n\nImport data using bcp utility\n\n/opt/mssql-tools/bin/bcp <Table_Name> IN /tmp/MyData.bcp -d <database_name> -c -U <user_name> -P \"<password>\" -S <server_name>\n"
},
{
"answer_id": 69494573,
"author": "Bhadresh Patel",
"author_id": 3134543,
"author_profile": "https://Stackoverflow.com/users/3134543",
"pm_score": 2,
"selected": false,
"text": "@echo off\n\nCLS\n\necho Running dump ...\n\nsqlcmd -S SERVER\\SQLEXPRESS -U username -P password -Q \"BACKUP DATABASE master TO DISK='D:\\DailyDBBackup\\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak'\"\n\necho Zipping ...\n\n\"C:\\Program Files\\7-Zip\\7z.exe\" a -tzip \"D:\\DailyDBBackup\\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%_%time:~0,2%%time:~3,2%%time:~6,2%.bak.zip\" \"D:\\DailyDBBackup\\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak\"\n\necho Deleting the SQL file ...\n\ndel \"D:\\DailyDBBackup\\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak\"\n\necho Done!\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] |
122,695
|
<p>For example, I have an ASP.NET form that is called by another aspx:</p>
<pre><code>string url = "http://somewhere.com?P1=" + Request["param"];
Response.Write(url);
</code></pre>
<p>I want to do something like this:</p>
<pre><code>string url = "http://somewhere.com?P1=" + Request["param"];
string str = GetResponse(url);
if (str...) {}
</code></pre>
<p>I need to get whatever Response.Write is getting as a result or going to url, manipulate that response, and send something else back.</p>
<p>Any help or a point in the right direction would be greatly appreciated.</p>
|
[
{
"answer_id": 122707,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "WebClient client = new WebClient();\nstring response = client.DownloadString(url);\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20682/"
] |
122,714
|
<p>When I try the following lookup in my code:</p>
<pre><code>Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (DataSource) envCtx.lookup("jdbc/mydb");
</code></pre>
<p>I get the following exception:</p>
<pre><code>java.sql.SQLException: QueryResults: Unable to initialize naming context:
Name java:comp is not bound in this Context at
com.onsitemanager.database.ThreadLocalConnection.getConnection
(ThreadLocalConnection.java:130) at
...
</code></pre>
<p>I installed embedded JBoss following the JBoss <a href="http://wiki.jboss.org/wiki/Tomcat5.5.x?action=e&windowstate=normal&mode=view" rel="nofollow noreferrer">wiki instructions</a>. And I configured Tomcat using the "Scanning every WAR by default" deployment as specified in the <a href="http://wiki.jboss.org/wiki/EmbeddedAndTomcat" rel="nofollow noreferrer">configuration wiki page</a>.</p>
<p>Quoting the config page:</p>
<blockquote>
<p>JNDI</p>
<p>Embedded JBoss components like connection pooling, EJB, JPA, and transactions make
extensive use of JNDI to publish services. Embedded JBoss overrides Tomcat's JNDI
implementation by layering itself on top of Tomcat's JNDI instantiation. There are a few > reasons for this:</p>
<ol>
<li>To avoid having to declare each and every one of these services within server.xml</li>
<li>To allow seemeless integration of the java:comp namespace between web apps and
EJBs.</li>
<li>Tomcat's JNDI implementation has a few critical bugs in it that hamper some JBoss
components ability to work</li>
<li>We want to provide the option for you of remoting EJBs and other services that can > be remotely looked up</li>
</ol>
</blockquote>
<p>Anyone have any thoughts on how I can configure the JBoss naming service which according to the above quote is overriding Tomcat's JNDI implementation so that I can do a lookup on java:comp/env? </p>
<p>FYI - My environment Tomcat 5.5.9, Seam 2.0.2sp, Embedded JBoss (Beta 3), </p>
<p>Note: I do have a -ds.xml file for my database connection properly setup and accessible on the class path per the instructions.</p>
<p>Also note: I have posted this question in embedded Jboss forum and seam user forum. </p>
|
[
{
"answer_id": 6264195,
"author": "Kirijav",
"author_id": 787306,
"author_profile": "https://Stackoverflow.com/users/787306",
"pm_score": 1,
"selected": false,
"text": "<mbean code=\"org.jboss.naming.NamingAlias\" name=\"jboss.jmx:alias=testDatasource\">\n <attribute name=\"FromName\">jdbc/Example DataSource</attribute>\n <attribute name=\"ToName\">java:/testDatasource</attribute>\n</mbean>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5917/"
] |
122,728
|
<p>I have a dilemma, I'm using Java and Oracle and trying to keep queries on PL/SQL side. Everything is OK, until I have these complex queries which may and may not have conditions. <br></p>
<p>It's not hard in Java to put together <code>WHERE</code> clause with conditions, but it's not nice.
And on PL/SQL side I also found out that the only possibility for <code>dynamic queries</code> is string manipulations like</p>
<pre><code>IF inputname IS NOT NULL THEN
query := query ||' and NAME=' || inputname;
END IF;
</code></pre>
<p>Now I'm thinking, I'm leaving query in PL/SQL and sending <code>WHERE</code> clause with function parameter.
Any good recommendations or examples please?</p>
|
[
{
"answer_id": 122759,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 1,
"selected": false,
"text": "String selectQuery =\n (new SelectQuery())\n .addColumns(t1Col1, t1Col2, t2Col1)\n .addJoin(SelectQuery.JoinType.INNER_JOIN, joinOfT1AndT2)\n .addOrderings(t1Col1)\n .validate().toString();\n"
},
{
"answer_id": 122774,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "EXECUTE IMMEDIATE lString;\n EXECUTE IMMEDIATE 'SELECT value\n FROM TABLE\n WHERE '||pWhereClause\n INTO lValue;\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13114/"
] |
122,736
|
<p>I have a stored procedure that consists of a single select query used to insert into another table based on some minor math that is done to the arguments in the procedure. Can I generate the plan used for this query by referencing the procedure somehow, or do I have to copy and paste the query and create bind variables for the input parameters?</p>
|
[
{
"answer_id": 122817,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 4,
"selected": true,
"text": "alter session set tracefile_identifier = 'something-unique'\nalter session set sql_trace = true;\nalter session set events '10046 trace name context forever, level 8';\n\nselect 'right-before-my-sp' from dual;\nexec your_stored_procedure\n\nalter session set sql_trace = false;\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
122,741
|
<p>OK, I have been working on a random image selector and queue system (so you don't see the same images too often).</p>
<p>All was going swimmingly (as far as my crappy code does) <strong>until</strong> I got to the random bit. I wanted to test it, but how do you test for it? There is no <code>Debug.Assert(i.IsRandom)</code> (sadly) :D</p>
<p>So, I got my brain on it after watering it with some tea and came up with the following, I was just wondering if I could have your thoughts?</p>
<ul>
<li>Basically I knew the <strong>random</strong> bit was the problem, so I ripped that out to a delegate (which would then be passed to the objects constructor).</li>
<li>I then created a class that pretty much performs the same logic as the <em>live</em> code, but remembers the value selected in a private variable.</li>
<li>I then threw that delegate to the live class and tested against that:</li>
</ul>
<p>i.e.</p>
<pre><code>Debug.Assert(myObj.RndVal == RndIntTester.ValuePassed);
</code></pre>
<p>But I couldn't help but think, <strong>was I wasting my time?</strong> I ran that through lots of iterations to see if it fell over at any time etc.</p>
<p>Do you think I was wasting my time with this? Or could I have got away with:</p>
<p><img src="https://imgs.xkcd.com/comics/random_number.png" alt="Awesome Random Number Generator" /></p>
<p><a href="https://stackoverflow.com/questions/122741/testing-for-random-value-thoughts-on-this-approach#122765">GateKiller's answer</a> reminded me of this:</p>
<p><img src="https://www.random.org/analysis/dilbert.jpg" alt="Dilbert Random" /></p>
<h2>Update to Clarify</h2>
<ul>
<li><strong>I should add that I basically never want to see the same result more than X number of times from a pool of Y size.</strong></li>
<li>The addition of the test container basically allowed me to see if any of the previously selected images were "randomly" selected.</li>
<li>I guess technically the thing here being tested in not the RNG (since I never wrote that code) but the fact that am I expecting <em>random</em> results from a limited pool, and I want to track them.</li>
</ul>
|
[
{
"answer_id": 122854,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "Item[] foo = …\nfor (int idx = foo.size(); idx > 1; --idx) {\n /* Pick random number from half-open interval [0, idx) */\n int rnd = random(idx); \n Item tmp = foo[idx - 1];\n foo[idx - 1] = foo[rnd];\n foo[rnd] = tmp;\n}\n Y X"
},
{
"answer_id": 123451,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 0,
"selected": false,
"text": "for (my $i=0; $i<=100000; $i++) {\n my $r = rand; # Get the random number\n $r = int($r * 1000); # Move it into the desired range\n $dist{$r} ++; # Count the occurrences of each number\n}\n\nprint \"Min occurrences: \", (sort { $a <=> $b } values %dist)[1], \"\\n\";\nprint \"Max occurrences: \", (sort { $b <=> $a } values %dist)[1], \"\\n\";\n"
},
{
"answer_id": 123822,
"author": "not-bob",
"author_id": 14770,
"author_profile": "https://Stackoverflow.com/users/14770",
"pm_score": 0,
"selected": false,
"text": " ****** ****** ****\n***********************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n 1 2 3 4 5\n12345678901234567890123456789012345678901234567890\n ****** ****** ****\n ************ ************ ************\n ************ ************ ***************\n ************ ************ ****************\n ************ ************ *****************\n ************ ************ *****************\n *************************** ******************\n **************************** ******************\n******************************* ******************\n**************************************************\n 1 2 3 4 5\n12345678901234567890123456789012345678901234567890\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
122,749
|
<p>I've been creating snapins with the new MMC 3.0 classes and C#. I can't seem to find any examples of how to get rid of the "Console Root" node when creating the *.msc files. I looked through the examples in the SDK, but I can't seem to find anything for this.</p>
<p>I have seen other snapins that do what I want, but I can't tell what version of MMC they are using.</p>
|
[
{
"answer_id": 494402,
"author": "Mark",
"author_id": 37923,
"author_profile": "https://Stackoverflow.com/users/37923",
"pm_score": 4,
"selected": true,
"text": "New Window from Here"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12829/"
] |
122,752
|
<p>I've seen <a href="https://stackoverflow.com/questions/55622/best-tools-for-working-with-docbook-xml-documents">Best tools for working with DocBook XML documents</a>, but my question is slightly different. Which is the currently recommended formatting toolchain - as opposed to editing tool - for XML DocBook?</p>
<p>In Eric Raymond's <a href="https://rads.stackoverflow.com/amzn/click/com/0131429019" rel="nofollow noreferrer" rel="nofollow noreferrer">'The Art of Unix Programming'</a> from 2003 (an excellent book!), the suggestion is XML-FO (XML Formatting Objects), but I've since seen suggestions here that indicated that XML-FO is no longer under development (though I can no longer find that question on StackOverflow, so maybe it was erroneous).</p>
<p>Assume I'm primarily interested in Unix/Linux (including MacOS X), but I wouldn't automatically ignore Windows-only solutions.</p>
<p>Is <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow noreferrer">Apache's FOP</a> the best way to go? Are there any alternatives?</p>
|
[
{
"answer_id": 122922,
"author": "Gustavo Carreno",
"author_id": 8167,
"author_profile": "https://Stackoverflow.com/users/8167",
"pm_score": 5,
"selected": true,
"text": "AC_INIT(Makefile.in)\n\nFOP=fop.sh\nHHC=hhc\nXSLTPROC=xsltproc\n\nAC_ARG_WITH(fop, [ --with-fop Where to find Apache FOP],\n[\n if test \"x$withval\" != \"xno\"; then\n FOP=\"$withval\"\n fi\n]\n)\nAC_PATH_PROG(FOP, $FOP)\n\nAC_ARG_WITH(hhc, [ --with-hhc Where to find Microsoft Help Compiler],\n[\n if test \"x$withval\" != \"xno\"; then\n HHC=\"$withval\"\n fi\n]\n)\nAC_PATH_PROG(HHC, $HHC)\n\nAC_ARG_WITH(xsltproc, [ --with-xsltproc Where to find xsltproc],\n[\n if test \"x$withval\" != \"xno\"; then\n XSLTPROC=\"$withval\"\n fi\n]\n)\nAC_PATH_PROG(XSLTPROC, $XSLTPROC)\n\nAC_SUBST(FOP)\nAC_SUBST(HHC)\nAC_SUBST(XSLTPROC)\n\nHERE=`pwd`\nAC_SUBST(HERE)\nAC_OUTPUT(Makefile)\n\ncat > config.nice <<EOT\n#!/bin/sh\n./configure \\\n --with-fop='$FOP' \\\n --with-hhc='$HHC' \\\n --with-xsltproc='$XSLTPROC' \\\n\nEOT\nchmod +x config.nice\n FOP=@FOP@\nHHC=@HHC@\nXSLTPROC=@XSLTPROC@\nHERE=@HERE@\n\n# Subdirs that contain docs\nDOCS=appendixes chapters reference \n\nXML_CATALOG_FILES=./build/docbook-xsl-1.71.0/catalog.xml\nexport XML_CATALOG_FILES\n\nall: entities.ent manual.xml html\n\nclean:\n@echo -e \"\\n=== Cleaning\\n\"\n@-rm -f html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm entities.ent .ent\n@echo -e \"Done.\\n\"\n\ndist-clean:\n@echo -e \"\\n=== Restoring defaults\\n\"\n@-rm -rf .ent autom4te.cache config.* configure Makefile html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm build/docbook-xsl-1.71.0\n@echo -e \"Done.\\n\"\n\nentities.ent: ./build/mkentities.sh $(DOCS)\n@echo -e \"\\n=== Creating entities\\n\"\n@./build/mkentities.sh $(DOCS) > .ent\n@if [ ! -f entities.ent ] || [ ! cmp entities.ent .ent ]; then mv .ent entities.ent ; fi\n@echo -e \"Done.\\n\"\n\n# Build the docs in chm format\n\nchm: chm/htmlhelp.hpp\n@echo -e \"\\n=== Creating CHM\\n\"\n@echo logo.png >> chm/htmlhelp.hhp\n@echo arrow.gif >> chm/htmlhelp.hhp\n@-cd chm && \"$(HHC)\" htmlhelp.hhp\n@echo -e \"Done.\\n\"\n\nchm/htmlhelp.hpp: entities.ent build/docbook-xsl manual.xml build/chm.xsl\n@echo -e \"\\n=== Creating input for CHM\\n\"\n@\"$(XSLTPROC)\" --output ./chm/index.html ./build/chm.xsl manual.xml\n\n# Build the docs in HTML format\n\nhtml: html/index.html\n\nhtml/index.html: entities.ent build/docbook-xsl manual.xml build/html.xsl\n@echo -e \"\\n=== Creating HTML\\n\"\n@\"$(XSLTPROC)\" --output ./html/index.html ./build/html.xsl manual.xml\n@echo -e \"Done.\\n\"\n\n# Build the docs in PDF format\n\npdf: pdf/manual.fo\n@echo -e \"\\n=== Creating PDF\\n\"\n@\"$(FOP)\" ./pdf/manual.fo ./pdf/manual.pdf\n@echo -e \"Done.\\n\"\n\npdf/manual.fo: entities.ent build/docbook-xsl manual.xml build/pdf.xsl\n@echo -e \"\\n=== Creating input for PDF\\n\"\n@\"$(XSLTPROC)\" --output ./pdf/manual.fo ./build/pdf.xsl manual.xml\n\ncheck: manual.xml\n@echo -e \"\\n=== Checking correctness of manual\\n\"\n@xmllint --valid --noout --postvalid manual.xml\n@echo -e \"Done.\\n\"\n\n# need to touch the dir because the timestamp in the tarball\n# is older than that of the tarball :)\nbuild/docbook-xsl: build/docbook-xsl-1.71.0.tar.gz\n@echo -e \"\\n=== Un-taring docbook-xsl\\n\"\n@cd build && tar xzf docbook-xsl-1.71.0.tar.gz && touch docbook-xsl-1.71.0\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15168/"
] |
122,763
|
<p>I have a dict, that looks like this:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
},
'foo/bar': {
'opt3': 3,
'opt4': 4,
},
'foo/bar/baz': {
'opt5': 5,
'opt6': 6,
}
}
</code></pre>
<p>And I need to get it to look like:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
'bar': {
'opt3': 3,
'opt4': 4,
'baz': {
'opt5': 5,
'opt6': 6,
}
}
}
}
</code></pre>
<p>I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.</p>
|
[
{
"answer_id": 122785,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": true,
"text": "def nest(d):\n rv = {}\n for key, value in d.iteritems():\n node = rv\n for part in key.split('/'):\n node = node.setdefault(part, {})\n node.update(value)\n return rv\n"
},
{
"answer_id": 122812,
"author": "Mike Elkins",
"author_id": 19193,
"author_profile": "https://Stackoverflow.com/users/19193",
"pm_score": 1,
"selected": false,
"text": "def layer(dict):\n for k,v in dict:\n if '/' in k:\n del dict[k]\n subdict = dict.get(k[:k.find('/')],{})\n subdict[k[k.find('/')+1:]] = v\n layer(subdict)\n"
},
{
"answer_id": 47448562,
"author": "Manoj Jadhav",
"author_id": 6165783,
"author_profile": "https://Stackoverflow.com/users/6165783",
"pm_score": 0,
"selected": false,
"text": "pprint https://docs.python.org/3.2/library/pprint.html"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] |
122,767
|
<p>How can I mount a floppy image file using cygwin. I would like to mount the image, copy a file to the mounted drive, and then unmount it from the command line. </p>
<p>I know you can use <a href="http://chitchat.at.infoseek.co.jp/vmware/vfd.html#beta" rel="nofollow noreferrer">Virtual Floppy Drive</a> in windows, but is there a way to do this in Cygwin?</p>
|
[
{
"answer_id": 56815490,
"author": "fjardon",
"author_id": 657700,
"author_profile": "https://Stackoverflow.com/users/657700",
"pm_score": 1,
"selected": false,
"text": "./configure LIBS = -liconv\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415/"
] |
122,772
|
<p>When I try to display the contents of a LOB (large object) column in SQL*Plus, it is truncated. How do I display the whole thing?</p>
|
[
{
"answer_id": 122776,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 7,
"selected": true,
"text": "SQL> set long 30000\nSQL> show long\nlong 30000\n"
},
{
"answer_id": 7272671,
"author": "Kevin O'Donnell",
"author_id": 203789,
"author_profile": "https://Stackoverflow.com/users/203789",
"pm_score": 4,
"selected": false,
"text": "SQL> set longchunksize 30000\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2391/"
] |
122,778
|
<p>Under VS's external tools settings there is a "Use Output Window" check box that captures the tools command line output and dumps it to a VS tab.</p>
<p>The question is: <em>can I get the same processing for my program when I hit F5?</em></p>
<p><strong>Edit:</strong> FWIW I'm in C# but if that makes a difference to your answer then it's unlikely that your answer is what I'm looking for.</p>
<p>What I want would take the output stream of the program and transfer it to the output tab in VS using the same devices that output redirection ('|' and '>') uses in the cmd prompt.</p>
|
[
{
"answer_id": 123067,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 2,
"selected": true,
"text": "void my_printf(const char *format, ...)\n{\n char buf[2048];\n\n // get the arg list and format it into a string\n va_start(arglist, format);\n vsprintf_s(buf, 2048, format, arglist);\n va_end(arglist); \n\n vprintf_s(buf); // prints to the standard output stream\n OutputDebugString(buf); // prints to the output window\n}\n"
},
{
"answer_id": 125492,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "> output.txt"
},
{
"answer_id": 125509,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "} Main"
},
{
"answer_id": 5577787,
"author": "Carl R",
"author_id": 480986,
"author_profile": "https://Stackoverflow.com/users/480986",
"pm_score": 2,
"selected": false,
"text": "using System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class DebugTextWriter : TextWriter\n {\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n Debug.WriteLine(value);\n }\n }\n}\n using System;\n\nnamespace TestConsole\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.SetOut(new DebugTextWriter());\n Console.WriteLine(\"This text goes to the Visual Studio output window.\");\n }\n }\n}\n using System.IO;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class OutputDebugStringTextWriter : TextWriter\n {\n [DllImport(\"kernel32.dll\")]\n static extern void OutputDebugString(string lpOutputString);\n\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n OutputDebugString(value.ToString());\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n OutputDebugString(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n OutputDebugString(value);\n }\n }\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
122,781
|
<p>I have a page in my desktop app, and I've implemented simple grab-and-pan. It works great.</p>
<p>When you are panning in this way and you are release, the page stops dead where you dropped it.</p>
<p>I'd like it to continue slightly with some momentum, and stop eventually. Rather like the 'throw' in the iPhone UI, I guess.</p>
<p>I'm not really chasing perfection, just a very crude simple sense of being able to 'throw' that page.</p>
|
[
{
"answer_id": 123067,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 2,
"selected": true,
"text": "void my_printf(const char *format, ...)\n{\n char buf[2048];\n\n // get the arg list and format it into a string\n va_start(arglist, format);\n vsprintf_s(buf, 2048, format, arglist);\n va_end(arglist); \n\n vprintf_s(buf); // prints to the standard output stream\n OutputDebugString(buf); // prints to the output window\n}\n"
},
{
"answer_id": 125492,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "> output.txt"
},
{
"answer_id": 125509,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "} Main"
},
{
"answer_id": 5577787,
"author": "Carl R",
"author_id": 480986,
"author_profile": "https://Stackoverflow.com/users/480986",
"pm_score": 2,
"selected": false,
"text": "using System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class DebugTextWriter : TextWriter\n {\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n Debug.WriteLine(value);\n }\n }\n}\n using System;\n\nnamespace TestConsole\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.SetOut(new DebugTextWriter());\n Console.WriteLine(\"This text goes to the Visual Studio output window.\");\n }\n }\n}\n using System.IO;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class OutputDebugStringTextWriter : TextWriter\n {\n [DllImport(\"kernel32.dll\")]\n static extern void OutputDebugString(string lpOutputString);\n\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n OutputDebugString(value.ToString());\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n OutputDebugString(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n OutputDebugString(value);\n }\n }\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15721/"
] |
122,782
|
<p>I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines:</p>
<pre><code>boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();
boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
</code></pre>
|
[
{
"answer_id": 122843,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "objcopy"
},
{
"answer_id": 123233,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 5,
"selected": true,
"text": "namespace boost_1_36_0 {\n #include <boost_1_36_0/boost/regex.hpp>\n}\nnamespace boost_1_35_0 {\n #include <boost_1_35_0/boost/shared_ptr.hpp>\n}\n #define boost boost_1_36_0\n #include <boost_1_36_0/boost/regex.hpp>\n#undef boost\n#define boost boost_1_35_0\n #include <boost_1_35_0/boost/shared_ptr.hpp>\n#undef boost\n -Dboost=boost_1_36_0 #if defined(SOME_CONDITION)\n# define HEADER <boost/some/header.hpp>\n#else\n# define HEADER <boost/some/other/header.hpp>\n#endif\n namespace boost {..} namespace boost_1_36_0 {...} BOOST_XYZ BOOST_1_36_0_XYZ"
},
{
"answer_id": 21413269,
"author": "0xC0DEGURU",
"author_id": 1353723,
"author_profile": "https://Stackoverflow.com/users/1353723",
"pm_score": 2,
"selected": false,
"text": "bcp --namespace=boost_1_36_0 --namespace-alias shared_ptr regex /path/to/install\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8701/"
] |
122,799
|
<p>There is no summary available of the big O notation for operations on the most common data structures including arrays, linked lists, hash tables etc.</p>
|
[
{
"answer_id": 17410009,
"author": "Mobiletainment",
"author_id": 1265240,
"author_profile": "https://Stackoverflow.com/users/1265240",
"pm_score": 6,
"selected": false,
"text": "+----------------------+----------+------------+----------+--------------+\n| | Insert | Delete | Search | Space Usage |\n+----------------------+----------+------------+----------+--------------+\n| Unsorted array | O(1) | O(1) | O(n) | O(n) |\n| Value-indexed array | O(1) | O(1) | O(1) | O(n) |\n| Sorted array | O(n) | O(n) | O(log n) | O(n) |\n| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |\n| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |\n| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |\n| Heap | O(log n) | O(log n)** | O(n) | O(n) |\n| Hash table | O(1) | O(1) | O(1) | O(n) |\n+----------------------+----------+------------+----------+--------------+\n\n * The cost to add or delete an element into a known location in the list \n (i.e. if you have an iterator to the location) is O(1). If you don't \n know the location, then you need to traverse the list to the location\n of deletion/insertion, which takes O(n) time. \n\n** The deletion cost is O(log n) for the minimum or maximum, O(n) for an\n arbitrary element.\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340748/"
] |
122,815
|
<p>I'm looking for a groovy equivalent on .NET
<a href="http://boo.codehaus.org/" rel="nofollow noreferrer">http://boo.codehaus.org/</a></p>
<p>So far Boo looks interesting, but it is statically typed, yet does include some of the metaprogramming features I'd be looking for.</p>
<p>Can anyone comment on the experience of using Boo and is it worth looking into for more than hobby purposes at a 1.0 Version? </p>
<p><em>Edit</em>: Changed BOO to Boo</p>
|
[
{
"answer_id": 17410009,
"author": "Mobiletainment",
"author_id": 1265240,
"author_profile": "https://Stackoverflow.com/users/1265240",
"pm_score": 6,
"selected": false,
"text": "+----------------------+----------+------------+----------+--------------+\n| | Insert | Delete | Search | Space Usage |\n+----------------------+----------+------------+----------+--------------+\n| Unsorted array | O(1) | O(1) | O(n) | O(n) |\n| Value-indexed array | O(1) | O(1) | O(1) | O(n) |\n| Sorted array | O(n) | O(n) | O(log n) | O(n) |\n| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |\n| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |\n| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |\n| Heap | O(log n) | O(log n)** | O(n) | O(n) |\n| Hash table | O(1) | O(1) | O(1) | O(n) |\n+----------------------+----------+------------+----------+--------------+\n\n * The cost to add or delete an element into a known location in the list \n (i.e. if you have an iterator to the location) is O(1). If you don't \n know the location, then you need to traverse the list to the location\n of deletion/insertion, which takes O(n) time. \n\n** The deletion cost is O(log n) for the minimum or maximum, O(n) for an\n arbitrary element.\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129162/"
] |
122,821
|
<p>I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons. </p>
<p>In the RenderContent call in the Webpart I've got some code to add event handlers:</p>
<pre><code> ArrayList nextPages = new ArrayList();
//populate nextPages ....
AfterPageRepeater.DataSource = nextPages;
AfterPageRepeater.DataBind();
foreach (Control oRepeaterControl in AfterPageRepeater.Controls)
{
if (oRepeaterControl is RepeaterItem)
{
if (oRepeaterControl.HasControls())
{
foreach (Control oControl in oRepeaterControl.Controls)
{
if (oControl is LinkButton)
{
((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click);
}
}
}
}
}
</code></pre>
<p>The function PageNavigateButton_Click is never called however. I can see it being added as an event handler in the debugger however.</p>
<p>Any ideas? I'm stumped how to do this. </p>
|
[
{
"answer_id": 122948,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "protected override void OnLoad(EventArge e)\n { base.OnLoad(e);\n EnsureChildControls();\n\n var linkButtons = from c in AfterPageRepeater.Controls\n .OfType<RepeaterItem>()\n where c.HasControls()\n select c into ris\n from lb in ris.OfType<LinkButton>()\n select lb;\n\n foreach(var linkButton in linkButtons)\n { linkButton.Click += PageNavigateButton_Click\n } \n }\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21299/"
] |
122,826
|
<p>Suppose you have a fairly large (~2.2 MLOC), fairly old (started more than 10 years ago) Windows desktop application in C/C++. About 10% of modules are external and don't have sources, only debug symbols.</p>
<p>How would you go about reducing application's memory footprint in half? At least, what would you do to find out where memory is consumed?</p>
|
[
{
"answer_id": 123054,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 0,
"selected": false,
"text": "Object arrayOfObjs[MAX_THAT_WILL_EVER_BE_USED];\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310/"
] |
122,834
|
<p>Suppose there are two scripts Requester.php and Provider.php, and Requester requires processing from Provider and makes an http request to it (Provider.php?data="data"). In this situation, Provider quickly finds the answer, but to maintain the system must perform various updates throughout the database. Is there a way to immediately return the value to Requester, and then continue processing in Provider. </p>
<p>Psuedo Code</p>
<pre><code>Provider.php
{
$answer = getAnswer($_GET['data']);
echo $answer;
//SIGNAL TO REQUESTER THAT WE ARE FINISHED
processDBUpdates();
return;
}
</code></pre>
|
[
{
"answer_id": 122966,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 0,
"selected": false,
"text": "ProviderCore ProviderInterface ProviderInterface ProviderCore ProviderCore"
},
{
"answer_id": 122997,
"author": "William OConnor - csevb10",
"author_id": 10084,
"author_profile": "https://Stackoverflow.com/users/10084",
"pm_score": 2,
"selected": true,
"text": "Requester.php Provider.php > /dev/null 2>&1 & exec(\"wget -O - \\\"$url\\\" > /dev/null 2>&1 &\"); \n"
},
{
"answer_id": 24540176,
"author": "John Foley",
"author_id": 1775336,
"author_profile": "https://Stackoverflow.com/users/1775336",
"pm_score": 0,
"selected": false,
"text": "Provider.php \n{\n // Fork process\n $pid = pcntl_fork();\n\n // You are now running both a daemon process and the parent process\n // through the rest of the code below\n\n if ($pid > 0) {\n // PARENT Process\n $answer = getAnswer($_GET['data']);\n echo $answer; \n //SIGNAL TO REQUESTER THAT WE ARE FINISHED\n return;\n }\n\n if ($pid == 0) {\n // DAEMON Process\n processDBUpdates();\n return;\n }\n\n // If you get here the daemon process failed to start\n handleDaemonErrorCondition();\n return;\n\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8880/"
] |
122,853
|
<p>I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?</p>
|
[
{
"answer_id": 122874,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "Content-Length HEAD GET HttpWebRequest req = (HttpWebRequest)WebRequest.Create(\"http://example.com/\");\nreq.Method = \"HEAD\";\nlong len;\nusing(HttpWebResponse resp = (HttpWebResponse)(req.GetResponse()))\n{\n len = resp.ContentLength;\n}\n HttpWebResponse Content-Length"
},
{
"answer_id": 122984,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 8,
"selected": true,
"text": "public long GetFileSize(string url)\n{\n long result = -1;\n\n System.Net.WebRequest req = System.Net.WebRequest.Create(url);\n req.Method = \"HEAD\";\n using (System.Net.WebResponse resp = req.GetResponse())\n {\n if (long.TryParse(resp.Headers.Get(\"Content-Length\"), out long ContentLength))\n {\n result = ContentLength;\n }\n }\n\n return result;\n}\n"
},
{
"answer_id": 46999741,
"author": "Umut D.",
"author_id": 2914860,
"author_profile": "https://Stackoverflow.com/users/2914860",
"pm_score": 1,
"selected": false,
"text": "WebClient webClient = new WebClient();\nwebClient.OpenRead(\"http://stackoverflow.com/robots.txt\");\nlong totalSizeBytes= Convert.ToInt64(webClient.ResponseHeaders[\"Content-Length\"]);\nConsole.WriteLine((totalSizeBytes));\n"
},
{
"answer_id": 51393151,
"author": "Daria",
"author_id": 4526973,
"author_profile": "https://Stackoverflow.com/users/4526973",
"pm_score": 2,
"selected": false,
"text": "HTTP HEAD HTTP GET System.Net.Http.HttpClient request.Headers.Range = new RangeHeaderValue(startByte, endByte)\n response.Content.Header {\n \"Key\": \"Content-Range\",\n \"Value\": [\n \"bytes 0-15/2328372\"\n ]\n }\n public static class HttpClientExtensions\n{\n public static async Task<long> GetContentSizeAsync(this System.Net.Http.HttpClient client, string url)\n {\n using (var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url))\n {\n // In order to keep the response as small as possible, set the requested byte range to [0,0] (i.e., only the first byte)\n request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(from: 0, to: 0);\n\n using (var response = await client.SendAsync(request))\n {\n response.EnsureSuccessStatusCode();\n\n if (response.StatusCode != System.Net.HttpStatusCode.PartialContent) \n throw new System.Net.WebException($\"expected partial content response ({System.Net.HttpStatusCode.PartialContent}), instead received: {response.StatusCode}\");\n\n var contentRange = response.Content.Headers.GetValues(@\"Content-Range\").Single();\n var lengthString = System.Text.RegularExpressions.Regex.Match(contentRange, @\"(?<=^bytes\\s[0-9]+\\-[0-9]+/)[0-9]+$\").Value;\n return long.Parse(lengthString);\n }\n }\n }\n}\n"
},
{
"answer_id": 71395577,
"author": "Ilya",
"author_id": 15122582,
"author_profile": "https://Stackoverflow.com/users/15122582",
"pm_score": 0,
"selected": false,
"text": " HttpClient client = new HttpClient(\n new HttpClientHandler() {\n Proxy = null, UseProxy = false\n } // removes the delay getting a response from the server, if you not use Proxy\n );\n\n public async Task<long?> GetContentSizeAsync(string url) {\n using (HttpResponseMessage responce = await client.GetAsync(url))\n return responce.Content.Headers.ContentLength;\n }\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
122,855
|
<p>Anyone know if it is possible to write an app that uses the Java Sound API on a system that doesn't actually have a hardware sound device?</p>
<p>I have some code I've written based on the API that manipulates some audio and plays the result but I am now trying to run this in a server environment, where the audio will be recorded to a file instead of played to line out.</p>
<p>The server I'm running on has no sound card, and I seem to be running into roadblocks with Java Sound not being able to allocate any lines if there is not a Mixer that supports it. (And with no hardware devices I'm getting no Mixers.)</p>
<p>Any info would be much appreciated -</p>
<p>thanks.</p>
|
[
{
"answer_id": 122874,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "Content-Length HEAD GET HttpWebRequest req = (HttpWebRequest)WebRequest.Create(\"http://example.com/\");\nreq.Method = \"HEAD\";\nlong len;\nusing(HttpWebResponse resp = (HttpWebResponse)(req.GetResponse()))\n{\n len = resp.ContentLength;\n}\n HttpWebResponse Content-Length"
},
{
"answer_id": 122984,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 8,
"selected": true,
"text": "public long GetFileSize(string url)\n{\n long result = -1;\n\n System.Net.WebRequest req = System.Net.WebRequest.Create(url);\n req.Method = \"HEAD\";\n using (System.Net.WebResponse resp = req.GetResponse())\n {\n if (long.TryParse(resp.Headers.Get(\"Content-Length\"), out long ContentLength))\n {\n result = ContentLength;\n }\n }\n\n return result;\n}\n"
},
{
"answer_id": 46999741,
"author": "Umut D.",
"author_id": 2914860,
"author_profile": "https://Stackoverflow.com/users/2914860",
"pm_score": 1,
"selected": false,
"text": "WebClient webClient = new WebClient();\nwebClient.OpenRead(\"http://stackoverflow.com/robots.txt\");\nlong totalSizeBytes= Convert.ToInt64(webClient.ResponseHeaders[\"Content-Length\"]);\nConsole.WriteLine((totalSizeBytes));\n"
},
{
"answer_id": 51393151,
"author": "Daria",
"author_id": 4526973,
"author_profile": "https://Stackoverflow.com/users/4526973",
"pm_score": 2,
"selected": false,
"text": "HTTP HEAD HTTP GET System.Net.Http.HttpClient request.Headers.Range = new RangeHeaderValue(startByte, endByte)\n response.Content.Header {\n \"Key\": \"Content-Range\",\n \"Value\": [\n \"bytes 0-15/2328372\"\n ]\n }\n public static class HttpClientExtensions\n{\n public static async Task<long> GetContentSizeAsync(this System.Net.Http.HttpClient client, string url)\n {\n using (var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url))\n {\n // In order to keep the response as small as possible, set the requested byte range to [0,0] (i.e., only the first byte)\n request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(from: 0, to: 0);\n\n using (var response = await client.SendAsync(request))\n {\n response.EnsureSuccessStatusCode();\n\n if (response.StatusCode != System.Net.HttpStatusCode.PartialContent) \n throw new System.Net.WebException($\"expected partial content response ({System.Net.HttpStatusCode.PartialContent}), instead received: {response.StatusCode}\");\n\n var contentRange = response.Content.Headers.GetValues(@\"Content-Range\").Single();\n var lengthString = System.Text.RegularExpressions.Regex.Match(contentRange, @\"(?<=^bytes\\s[0-9]+\\-[0-9]+/)[0-9]+$\").Value;\n return long.Parse(lengthString);\n }\n }\n }\n}\n"
},
{
"answer_id": 71395577,
"author": "Ilya",
"author_id": 15122582,
"author_profile": "https://Stackoverflow.com/users/15122582",
"pm_score": 0,
"selected": false,
"text": " HttpClient client = new HttpClient(\n new HttpClientHandler() {\n Proxy = null, UseProxy = false\n } // removes the delay getting a response from the server, if you not use Proxy\n );\n\n public async Task<long?> GetContentSizeAsync(string url) {\n using (HttpResponseMessage responce = await client.GetAsync(url))\n return responce.Content.Headers.ContentLength;\n }\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8063/"
] |
122,856
|
<p>Is there a built in dll that will give me a list of links from a string. I want to send in a string with valid html and have it parse all the links. I seem to remember there being something built into either .net or an unmanaged library.</p>
<p>I found a couple open source projects that looked promising but I thought there was a built in module. If not I may have to use one of those. I just didn't want an external dependency at this point if it wasn't necessary.</p>
|
[
{
"answer_id": 124524,
"author": "Jacob Proffitt",
"author_id": 1336,
"author_profile": "https://Stackoverflow.com/users/1336",
"pm_score": 3,
"selected": false,
"text": "<a> List<Uri> findUris(string message)\n{\n string anchorPattern = \"<a[\\\\s]+[^>]*?href[\\\\s]?=[\\\\s\\\\\\\"\\']+(?<href>.*?)[\\\\\\\"\\\\']+.*?>(?<fileName>[^<]+|.*?)?<\\\\/a>\";\n MatchCollection matches = Regex.Matches(message, anchorPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);\n if (matches.Count > 0)\n {\n List<Uri> uris = new List<Uri>();\n\n foreach (Match m in matches)\n {\n string url = m.Groups[\"url\"].Value;\n Uri testUri = null;\n if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out testUri))\n {\n uris.Add(testUri);\n }\n }\n return uris;\n }\n return null;\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1514/"
] |
122,865
|
<p>I have a <code>div</code> and an <code>iframe</code> on the page
the <code>div</code> has</p>
<pre><code>z-index: 0;
</code></pre>
<p>the <code>iframe</code> has its content with a popup having a <code>z-index</code> of 1000</p>
<pre><code>z-index: 1000;
</code></pre>
<p>However, the <code>div</code> still overshadows the popup in IE (but works fine in Firefox).</p>
<p>Does anyone know what I can do?</p>
|
[
{
"answer_id": 123199,
"author": "Rich Adams",
"author_id": 10018,
"author_profile": "https://Stackoverflow.com/users/10018",
"pm_score": 1,
"selected": false,
"text": "position: absolute;"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] |
122,877
|
<p>So I've got some C code:</p>
<pre><code>#include <stdio.h>
#include <string.h>
/* putting one of the "char*"s here causes a segfault */
void main() {
char* path = "/temp";
char* temp;
strcpy(temp, path);
}
</code></pre>
<p>This compiles, runs, and behaves as it looks. However, if one or both of the character pointers is declared as global variable, strcpy results in a segmentation fault. Why does this happen? Evidently there's an error in my understanding of scope.</p>
|
[
{
"answer_id": 122885,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 3,
"selected": false,
"text": "temp = (char *)malloc(TEMP_SIZE);\n"
},
{
"answer_id": 122903,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "DESCRIPTION\n The strcpy() function copies the string pointed to by src (including\n the terminating '\\0' character) to the array pointed to by dest. The\n strings may not overlap, and the destination string dest must be large\n enough to receive the copy.\n"
},
{
"answer_id": 122910,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 3,
"selected": false,
"text": "char temp[32]; char *temp char *temp=0"
},
{
"answer_id": 122911,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "temp // Make temp a static array of 256 chars\nchar temp[256];\nstrncpy(temp, 256, path);\n\n// Or, use dynamic memory\nchar *temp = (char *)malloc(256);\nstrncpy(temp, 256, path);\n strncpy() strcpy()"
},
{
"answer_id": 122936,
"author": "Sridhar Iyer",
"author_id": 13820,
"author_profile": "https://Stackoverflow.com/users/13820",
"pm_score": 2,
"selected": false,
"text": "strdup malloc+strcpy"
},
{
"answer_id": 123027,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 2,
"selected": false,
"text": "// Make temp a static array of 256 chars\nchar temp[256];\nstrncpy(temp, sizeof(temp), path);\ntemp[sizeof(temp)-1] = '\\0';\n 1. don't have magic numbers laced through the code, and\n2. you guarantee that your string is null terminated.\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12926/"
] |
122,882
|
<p>What is the proper technique to have <strong>ThreadA</strong> signal <strong>ThreadB</strong> of some event, without having <strong>ThreadB</strong> sit blocked waiting for an event to happen?</p>
<p>i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up.</p>
<hr>
<p>i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne().</p>
<hr>
<p>i considered having a delegate callback, but
a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, and
b) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against.</p>
<hr>
<p>i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls</p>
<p><code>Timer.Enabled = true;</code></p>
<p>but that seems like a hack.</p>
<p>In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms.</p>
<hr>
<p>i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem.</p>
<hr>
<p>What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen?</p>
|
[
{
"answer_id": 123205,
"author": "Leandro Oliveira",
"author_id": 16610,
"author_profile": "https://Stackoverflow.com/users/16610",
"pm_score": 1,
"selected": false,
"text": "AutoResetEvent ev = new AutoResetEvent(false);\n...\nif(ev.WaitOne(0, false)) {\n // event happened\n}\nelse {\n // do other stuff\n}\n"
},
{
"answer_id": 123569,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 0,
"selected": false,
"text": "List<> foreach CollectionModified"
},
{
"answer_id": 123693,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 2,
"selected": false,
"text": "AutoResetEvent WaitOne() false Queue List CopyTo List using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n private static object LockObject = new Object();\n\n private static AutoResetEvent _flag;\n private static Queue<int> _list;\n\n static void Main(string[] args)\n {\n _list = new Queue<int>();\n _flag = new AutoResetEvent(false);\n\n ThreadPool.QueueUserWorkItem(ProducerThread);\n\n int itemCount = 0;\n\n while (itemCount < 10)\n {\n if (_flag.WaitOne(0))\n {\n // there was an item\n lock (LockObject)\n {\n Console.WriteLine(\"Items in queue:\");\n while (_list.Count > 0)\n {\n Console.WriteLine(\"Found item {0}.\", _list.Dequeue());\n itemCount++;\n }\n }\n }\n else\n {\n Console.WriteLine(\"No items in queue.\");\n Thread.Sleep(125);\n }\n }\n }\n\n private static void ProducerThread(object state)\n {\n Random rng = new Random();\n\n Thread.Sleep(250);\n\n for (int i = 0; i < 10; i++)\n {\n lock (LockObject)\n {\n _list.Enqueue(rng.Next(0, 100));\n _flag.Set();\n Thread.Sleep(rng.Next(0, 250));\n }\n }\n }\n }\n}\n AutoResetEvent"
},
{
"answer_id": 123694,
"author": "herbrandson",
"author_id": 13181,
"author_profile": "https://Stackoverflow.com/users/13181",
"pm_score": 5,
"selected": true,
"text": " private static BackgroundWorker worker = new BackgroundWorker();\n static void Main(string[] args)\n {\n worker.DoWork += worker_DoWork;\n worker.RunWorkerCompleted += worker_RunWorkerCompleted;\n worker.ProgressChanged += worker_ProgressChanged;\n worker.WorkerReportsProgress = true;\n\n Console.WriteLine(\"Starting application.\");\n worker.RunWorkerAsync();\n\n Console.ReadKey();\n }\n\n static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n {\n Console.WriteLine(\"Progress.\");\n }\n\n static void worker_DoWork(object sender, DoWorkEventArgs e)\n {\n Console.WriteLine(\"Starting doing some work now.\");\n\n for (int i = 0; i < 5; i++)\n {\n Thread.Sleep(1000);\n worker.ReportProgress(i);\n }\n }\n\n static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n Console.WriteLine(\"Done now.\");\n }\n"
},
{
"answer_id": 124083,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 1,
"selected": false,
"text": "BackgroundWorker AsyncOperation asyncOperation.Post() this.asyncOperation = AsyncOperationManager.CreateOperation(null);\nthis.asyncOperation.Post(delegateMethod, arg);\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
122,883
|
<p>Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them.</p>
<p>I am talking about interfaces in a context of interfaces vs. abstract classes.</p>
|
[
{
"answer_id": 122941,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 5,
"selected": false,
"text": "Public Interface IRollOver\n Sub RollOver()\nEnd Interface\n\nPublic Class Dog Implements IRollOver\n Public Sub RollOver() Implements IRollOver.RollOver\n Console.WriteLine(\"Rolling Over!\")\n End Sub\nEnd Class\n\nPublic Sub Main()\n Dim d as New Dog()\n Dim ro as IRollOver = TryCast(d, IRollOver)\n If ro isNot Nothing Then\n ro.RollOver()\n End If\nEnd Sub\n"
},
{
"answer_id": 122971,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "public void Paint(Car car, System.Drawing.Color color)...\n public void Paint (Vehicle vehicle, System.Drawing.Color color)...\n public interface IPaintable{\n void Paint(System.Drawing.Color color);\n}\n public void Paint(IPaintable item, System.Drawing.Color color){\n item.Paint(color);\n}\n"
},
{
"answer_id": 123004,
"author": "JoshReedSchramm",
"author_id": 7018,
"author_profile": "https://Stackoverflow.com/users/7018",
"pm_score": 6,
"selected": false,
"text": "public interface IPet\n{\n void Eat(object food);\n void Sleep(int duration);\n}\n public class Dog : IPet\n public class PetStore\n{\n public static IPet GetRandomPet()\n { \n //Code to return a random Dog, Cat, or Mouse\n } \n}\n\nIPet myNewRandomPet = PetStore.GetRandomPet();\nmyNewRandomPet.Sleep(10);\n"
},
{
"answer_id": 123015,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 2,
"selected": false,
"text": "interface IReport\n{\n string RenderReport();\n}\n\nclass MyNewReport : IReport\n{\n public string RenderReport()\n {\n return \"Hello World Report!\";\n\n }\n}\n\nclass AnotherReport : IReport\n{\n public string RenderReport()\n {\n return \"Another Report!\";\n\n }\n}\n\n//This class can process any report that implements IReport!\nclass ReportEmailer()\n{\n public void EmailReport(IReport report)\n {\n Email(report.RenderReport());\n }\n}\n\nclass MyApp()\n{\n void Main()\n {\n //create specific \"MyNewReport\" report using interface\n IReport newReport = new MyNewReport();\n\n //create specific \"AnotherReport\" report using interface\n IReport anotherReport = new AnotherReport();\n\n ReportEmailer reportEmailer = new ReportEmailer();\n\n //emailer expects interface\n reportEmailer.EmailReport(newReport);\n reportEmailer.EmailReport(anotherReport);\n\n\n\n }\n\n}\n"
},
{
"answer_id": 123029,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 3,
"selected": false,
"text": "private void ProcessMessage(IMessage oneMessage)\n{\n DoSomething();\n}\n private void ProcessEmail(Email someEmail);\nprivate void ProcessFax(Fax someFax);\netc.\n ArrayList ar = (ArrayList)SomeIList;\n public class Fax : ISorteable \n{\n //implement the ISorteable stuff here.\n}\n"
},
{
"answer_id": 123030,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 1,
"selected": false,
"text": "public interface ICommand\n{\n void Execute();\n}\npublic class PrintSomething : ICommand\n{\n OutputStream Stream { get; set; }\n String Content {get; set;}\n void Execute()\n { \n Stream.Write(content);\n }\n}\n"
},
{
"answer_id": 123109,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 2,
"selected": false,
"text": "INeedFreshFoodAndWater[] array = new INeedFreshFoodAndWater[];\narray.Add(new Dog());\narray.Add(new Cat());\n\nforeach(INeedFreshFoodAndWater item in array)\n{\n item.Feed();\n item.Water();\n}\n"
},
{
"answer_id": 123342,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 1,
"selected": false,
"text": "public interface IReport\n{\n void RenderReport(); // This just defines the method prototype\n}\n\npublic abstract class Reporter\n{\n protected void DoSomething()\n {\n // This method is the same for every class that inherits from this class\n }\n}\n\npublic class ReportViolators : Reporter, IReport\n{\n public void RenderReport()\n {\n // Some kind of implementation specific to this class\n }\n}\n\npublic class ClientApp\n{\n var violatorsReport = new ReportViolators();\n\n // The interface method\n violatorsReport.RenderReport();\n\n // The abstract class method\n violatorsReport.DoSomething();\n}\n"
},
{
"answer_id": 123874,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 1,
"selected": false,
"text": "using (DisposableClass myClass = new DisposableClass())\n {\n // code goes here\n }\n"
},
{
"answer_id": 124545,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 4,
"selected": false,
"text": "// First pass - not maintainable\nvoid SubmitToWorkflow(object o, User u)\n{\n if (o is StreetMap)\n {\n var map = (StreetMap)o;\n map.LastUpdated = DateTime.UtcNow;\n map.UpdatedByUser = u.UserID;\n }\n else if (o is Person)\n {\n var person = (Person)o;\n person.LastUpdated = DateTime.Now; // Whoops .. should be UtcNow\n person.UpdatedByUser = u.UserID;\n }\n // Whoa - very unmaintainable.\n SubmitToWorkflow() // Second pass - brittle\nvoid SubmitToWorkflow(object o, User u)\n{\n if (o is DTOBase)\n {\n DTOBase dto = (DTOBase)o;\n dto.LastUpdated = DateTime.UtcNow;\n dto.UpdatedByUser = u.UserID;\n }\n // Third pass pass - also brittle\nvoid SubmitToWorkflow(DTOBase dto, User u)\n{\n dto.LastUpdated = DateTime.UtcNow;\n dto.UpdatedByUser = u.UserID;\n public interface IUpdateTracked\n{\n DateTime LastUpdated { get; set; }\n int UpdatedByUser { get; set; }\n}\n public class SomeDTO : IUpdateTracked\n{\n // IUpdateTracked implementation as well as other methods for SomeDTO\n}\n void SubmitToWorkflow(object o, User u)\n{\n IUpdateTracked updateTracked = o as IUpdateTracked;\n if (updateTracked != null)\n {\n updateTracked.LastUpdated = DateTime.UtcNow;\n updateTracked.UpdatedByUser = u.UserID;\n }\n // ...\n void SubmitToWorkflow(IUpdateTracked updateTracked, User u) LegacyDTO // Using an interface to bridge properties\npublic class LegacyDTO : IUpdateTracked\n{\n public int LegacyUserID { get; set; }\n public DateTime LastSaved { get; set; }\n\n public int UpdatedByUser\n {\n get { return LegacyUserID; }\n set { LegacyUserID = value; }\n }\n public DateTime LastUpdated\n {\n get { return LastSaved; }\n set { LastSaved = value; }\n }\n}\n // Explicit implementation of an interface\npublic class YetAnotherObject : IUpdatable\n{\n int IUpdatable.UpdatedByUser\n { ... }\n DateTime IUpdatable.LastUpdated\n { ... }\n IList // Decouples the caller and the code as both\n// operate only on IList, and are free to swap\n// out the concrete collection.\npublic IList<T> FindDuplicates( IList<T> list )\n{\n var duplicates = new List<T>()\n // TODO - write some code to detect duplicate items\n return duplicates;\n}\n class AnnualRaiseAdjuster\n : ISalaryAdjuster\n{\n AnnualRaiseAdjuster(IPayGradeDetermination payGradeDetermination) { ... }\n\n void AdjustSalary(Staff s)\n {\n var payGrade = payGradeDetermination.Determine(s);\n s.Salary = s.Salary * 1.01 + payGrade.Bonus;\n }\n}\n"
},
{
"answer_id": 11818132,
"author": "Eric J.",
"author_id": 141172,
"author_profile": "https://Stackoverflow.com/users/141172",
"pm_score": 0,
"selected": false,
"text": "show() Bird bird = GetMeAnInstanceOfABird(someCriteriaForSelectingASpecificKindOfBird);\nbird.Fly(Direction.South, Speed.CruisingSpeed);\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16820/"
] |
122,902
|
<p>As someone who is only barely proficient in javascript, is jQuery right for me? Is there a better library to use? I've seen lots of posts related to jQuery and it seems to be the most effective way to incorporate javascript into ASP.NET applications.</p>
<p>I've been out to <a href="http://jquery.com/" rel="noreferrer">jQuery's</a> site and have found the tutorials and other helpful information. Any other reference material (i.e books, blogs, etc.) would be helpful.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 3312695,
"author": "Nash",
"author_id": 363842,
"author_profile": "https://Stackoverflow.com/users/363842",
"pm_score": 0,
"selected": false,
"text": " Many plug-Ins.\n\n Only 15KB on the client Side.\n\n Community is pretty huge to guide you.\n\n Easy to work with Services(.svc,asmx) etc. I believe it is wonderful.\n You may forget JavaScripting\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19251/"
] |
122,909
|
<p>I have a file. I want to get its contents into a blob column in my oracle database or into a blob variable in my PL/SQL program. What is the best way to do that?</p>
|
[
{
"answer_id": 123017,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "// Need as OracleConnection in mConnection\n\n// Set an EMPTY_BLOB()\nString update = \"UPDATE tablename\"+\n \" SET blob_column = EMPTY_BLOB()\"+\n \" WHERE ID = \"+id;\nCallableStatement stmt = mConnection.prepareCall(update);\nstmt.executeUpdate();\n\n// Lock the row FOR UPDATE\nString select = \"BEGIN \" +\n \" SELECT \" + blob_column\n \" INTO ? \" +\n \" FROM \" + tablename +\n \" WHERE ID = '\" + id + \"'\" +\n \" FOR UPDATE; \" +\n \"END;\";\n\nstmt = mConnection.prepareCall(select);\nstmt.registerOutParameter(1, java.sql.Types.BLOB);\nstmt.executeUpdate();\n\nBLOB blob = (BLOB) stmt.getBlob(1);\nOutputStream bos = blob.setBinaryStream(0L);\nFileInputStream fis = new FileInputStream(file);\n// Code needed here to copy one stream to the other\nfis.close();\nbos.close();\nstmt.close();\n\nmConnection.commit();\n"
},
{
"answer_id": 123051,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 5,
"selected": true,
"text": "CREATE OR REPLACE DIRECTORY\n BLOB_DIR\n AS\n '/oracle/base/lobs'\n/\n\n\n\nCREATE OR REPLACE PROCEDURE BLOB_LOAD\nAS\n\n lBlob BLOB;\n lFile BFILE := BFILENAME('BLOB_DIR', 'filename');\n\nBEGIN\n\n INSERT INTO table (id, your_blob)\n VALUES (xxx, empty_blob())\n RETURNING your_blob INTO lBlob;\n\n DBMS_LOB.OPEN(lFile, DBMS_LOB.LOB_READONLY);\n\n DBMS_LOB.OPEN(lBlob, DBMS_LOB.LOB_READWRITE);\n\n DBMS_LOB.LOADFROMFILE(DEST_LOB => lBlob,\n SRC_LOB => lFile,\n AMOUNT => DBMS_LOB.GETLENGTH(lFile));\n\n DBMS_LOB.CLOSE(lFile);\n DBMS_LOB.CLOSE(lBlob);\n\n COMMIT;\n\nEND;\n/\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13693/"
] |
122,914
|
<p>Does anyone know any implementation of a templated cache of objects?</p>
<ul>
<li>You use a key to find object (the same as in std::map<>)</li>
<li>You specify a maximum number of objects that can be in the cache at the same time</li>
<li>There are facilities to create an object not found in the cache</li>
<li>There are facilities to know when an object is discarded from the cache</li>
</ul>
<p>For example : </p>
<pre><code>typedef cache<int, MyObj*> MyCache;
MyCache oCache;
oCache.SetSize(1);
oCache.Insert(make_pair(1, new MyObj());
oCache.Touch(1);
MyObj* oldObj = oCache.Delete(1);
...
</code></pre>
<p>It can be as simple as a LRU or MRU cache.</p>
<p>Any suggestions are welcomed!</p>
<p>Nic</p>
|
[
{
"answer_id": 35187400,
"author": "Straw1239",
"author_id": 3482801,
"author_profile": "https://Stackoverflow.com/users/3482801",
"pm_score": 1,
"selected": false,
"text": "template<typename K, typename V, typename Map = std::unordered_map<K, typename std::list<K>::iterator>>\nclass LRUCache\n{\n size_t maxSize;\n Map data;\n std::list<K> usageOrder;\n std::function<void(std::pair<K, V>)> onEject = [](std::pair<K, V> x){};\n\n void moveToFront(typename std::list<K>::iterator itr)\n {\n if(itr != usageOrder.begin())\n usageOrder.splice(usageOrder.begin(), usageOrder, itr);\n }\n\n\n void trimToSize()\n {\n while(data.size() > maxSize)\n {\n auto itr = data.find(usageOrder.back());\n\n onEject(std::pair<K, V>(itr->first, *(itr->second)));\n data.erase(usageOrder.back());\n usageOrder.erase(--usageOrder.end());\n }\n }\n\npublic:\n typedef std::pair<const K, V> value_type;\n typedef K key_type;\n typedef V mapped_type;\n\n\n LRUCache(size_t maxEntries) : maxSize(maxEntries)\n {\n data.reserve(maxEntries);\n }\n\n size_t size() const\n {\n return data.size();\n }\n\n void insert(const value_type& v)\n {\n usageOrder.push_front(v.first);\n data.insert(typename Map::value_type(v.first, usageOrder.begin()));\n\n trimToSize();\n }\n\n bool contains(const K& k) const\n {\n return data.count(k) != 0;\n }\n\n V& at(const K& k)\n {\n auto itr = data.at(k);\n moveToFront(itr);\n return *itr;\n }\n\n\n void setMaxEntries(size_t maxEntries)\n {\n maxSize = maxEntries;\n trimToSize();\n }\n\n void touch(const K& k)\n {\n at(k);\n }\n\n template<typename Compute>\n V& getOrCompute(const K& k)\n {\n if(!data.contains(k)) insert(value_type(k, Compute()));\n return(at(k));\n }\n\n void setOnEject(decltype(onEject) f)\n {\n onEject = f;\n }\n};\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18800/"
] |
122,919
|
<p>I have this bit of javascript written with jQuery 1.2.5. It's contained inside the main function() of a plugin that I wrote. The plugin is a horizontal gallery scroller very similar to jCarousel. It does alot of auto calculating of widths and determines how many to scroll based on that and the size of the images, which is what all the calculations are that are going on.</p>
<p>What my question is, how do I prevent this from firing off before a previous execution is finished. For instance, if I get a little click happy and just frantically mash down on <code>.digi_next</code>. Things don't go so well in the UI when that happens and I'd like to fix it :) I thought the answer might lie in <code>queue</code>, but all my attempts at using it haven't turned out anything worthwhile.</p>
<pre><code> var self = this;
$(".digi_next", this.container).click(function(){
var curLeft = $(".digi_container", self.container).css("left").split("px")[0];
var newLeft = (curLeft*1) - (self.containerPad + self.containerWidth) * self.show_photos;
if (newLeft < ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1) {
newLeft = ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1;
}
$(".digi_container", self.container).animate({
left: newLeft + "px"
}, self.rotateSpeed);
});
</code></pre>
|
[
{
"answer_id": 123091,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 4,
"selected": true,
"text": "var busy = false;\n$(\"...\").onclick(function() {\n if (busy) return false;\n busy = true;\n $(\"...\").animate(..., ..., ..., function() {\n busy= false;\n });\n return false;\n});\n"
},
{
"answer_id": 123348,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 2,
"selected": false,
"text": "$(\"...\").onclick(function(el) {\n var self = el;\n if (self.busy) return false;\n self.busy = true;\n $(\"...\").animate(..., ..., ..., function() {\n self.busy= false;\n });\n return false;\n});\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
122,920
|
<p>I'd like to line up items approximately like this:</p>
<pre><code>item1 item2 i3 longitemname
i4 longitemname2 anotheritem i5
</code></pre>
<p>Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5.</p>
<p>I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up.</p>
<p>So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left.</p>
<p>Any better suggestions?</p>
|
[
{
"answer_id": 123405,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "<ul style=\"float: left;\">\n <li>Short</li>\n <li>Loooong</li>\n <li>Even longer</li>\n</ul>\n<ul style=\"float: left;\">\n <li>Loooong</li>\n <li>Short</li>\n <li>...</li>\n</ul>\n<ul style=\"float: left;\">\n <li>Semi long</li>\n <li>...</li>\n <li>Short</li>\n</ul>\n"
},
{
"answer_id": 123416,
"author": "Parand",
"author_id": 13055,
"author_profile": "https://Stackoverflow.com/users/13055",
"pm_score": 3,
"selected": true,
"text": "<div class=\"item\">something</div>\n<div class=\"item\">something else</div>\n div.item { float: left; }\n var max_width=0;\n$('div.item').each( function() { if ($(this).width() > max_width) { max_width=$(this).width(); } } ).width(max_width);\n"
},
{
"answer_id": 123483,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 0,
"selected": false,
"text": "<ul class=\"ColumnBasedList\">\n <li><span>Item1 2</span></li>\n <li><span>Item2 3</span></li>\n <li><span>Item3 5</span></li>\n <li><span>Item4 6</span></li>\n <li><span>Item5 7</span></li>\n <li><span>Item6 8</span></li>\n</ul>\n .ColumnBasedList\n{\n width: 80%;\n margin: 0;\n padding: 0;\n}\n\n.ColumnBasedList li\n{\n list-style-type: none;\n display:inline;\n}\n\n.ColumnBasedList li span\n{\n display: -moz-inline-block;\n display: inline-block;\n width: 20em;\n margin: 0.3em;\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
122,942
|
<p>I have a table <code>UserAliases</code> (<code>UserId, Alias</code>) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.</p>
<p>Example:</p>
<pre><code>UserId/Alias
1/MrX
1/MrY
1/MrA
2/Abc
2/Xyz
</code></pre>
<p>I want the query result in the following format:</p>
<pre><code>UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz
</code></pre>
<p>Thank you.</p>
<p>I'm using SQL Server 2005.</p>
<p>p.s. actual T-SQL query would be appreciated :)</p>
|
[
{
"answer_id": 122980,
"author": "CodeRedick",
"author_id": 17145,
"author_profile": "https://Stackoverflow.com/users/17145",
"pm_score": 0,
"selected": false,
"text": "declare @result varchar(max)\n\n--must \"initialize\" result for this to work\nselect @result = ''\n\nselect @result = @result + alias\nFROM aliases\nWHERE username='Bob'\n"
},
{
"answer_id": 123025,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 7,
"selected": true,
"text": "CREATE FUNCTION [dbo].[GetAliasesById]\n(\n @userID int\n)\nRETURNS varchar(max)\nAS\nBEGIN\n declare @output varchar(max)\n select @output = COALESCE(@output + ', ', '') + alias\n from UserAliases\n where userid = @userID\n\n return @output\nEND\n\nGO\n\nSELECT UserID, dbo.GetAliasesByID(UserID)\nFROM UserAliases\nGROUP BY UserID\n\nGO\n"
},
{
"answer_id": 177153,
"author": "leoinfo",
"author_id": 6948,
"author_profile": "https://Stackoverflow.com/users/6948",
"pm_score": 4,
"selected": false,
"text": "/* EXAMPLE */\nDECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))\nINSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'\n UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'\n UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'\n\n/* QUERY */\n;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )\nSELECT \n LEFT(tmp.UserId, 10) +\n '/ ' +\n STUFF(\n ( SELECT ', '+Alias \n FROM @UserAliases \n WHERE UserId = tmp.UserId \n FOR XML PATH('') \n ) \n , 1, 2, ''\n ) AS [UserId/Alias]\nFROM tmp\n\n/* -- OUTPUT\n UserId/Alias\n 1/ MrX, MrY, MrA\n 2/ Abc, Xyz \n*/\n"
},
{
"answer_id": 891516,
"author": "Tushar Maru",
"author_id": 103344,
"author_profile": "https://Stackoverflow.com/users/103344",
"pm_score": 1,
"selected": false,
"text": "DECLARE @Str varchar(500)\n\nSELECT @Str=COALESCE(@Str,'') + CAST(ID as varchar(10)) + ','\nFROM dbo.fcUser\n\nSELECT @Str\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] |
122,951
|
<p>I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf)</p>
<pre><code>System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.
</code></pre>
<p>What is the problem with my regular expression?</p>
|
[
{
"answer_id": 145351,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 2,
"selected": false,
"text": "(?<name> subexpression)"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12834/"
] |
122,982
|
<p>Which checksum algorithm can you recommend in the following use case?</p>
<p>I want to generate checksums of small JPEG files (~8 kB each) to check if the content changed. Using the filesystem's <em>date modified</em> is unfortunately not an option.<br/>
The checksum <strong>need not</strong> be cryptographically strong but it should robustly indicate changes of any size.</p>
<p>The second criterion is <strong>speed</strong> since it should be possible to process at least <em>hundreds</em> of images per second (on a modern CPU).</p>
<p>The calculation will be done on a server with several clients. The clients send the images over Gigabit TCP to the server. So there's <strong>no disk I/O</strong> as bottleneck.</p>
|
[
{
"answer_id": 5126944,
"author": "Engin",
"author_id": 264152,
"author_profile": "https://Stackoverflow.com/users/264152",
"pm_score": 3,
"selected": false,
"text": "static const uint32_t crctab[] = {\n 0x0,\n 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,\n 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6,\n 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,\n 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac,\n 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f,\n 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a,\n 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,\n 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58,\n 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033,\n 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe,\n 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,\n 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4,\n 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,\n 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5,\n 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,\n 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07,\n 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c,\n 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1,\n 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,\n 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b,\n 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698,\n 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d,\n 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,\n 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f,\n 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,\n 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80,\n 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,\n 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a,\n 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629,\n 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c,\n 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,\n 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e,\n 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65,\n 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8,\n 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,\n 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2,\n 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,\n 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74,\n 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,\n 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21,\n 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a,\n 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087,\n 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,\n 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d,\n 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce,\n 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb,\n 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,\n 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09,\n 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,\n 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf,\n 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4\n};\n\ntypedef struct crc32ctx\n{\n uint32_t crc;\n uint32_t length;\n} CRC32Ctx;\n\n\n#define COMPUTE(var, ch) (var) = (var) << 8 ^ crctab[(var) >> 24 ^ (ch)]\n\nvoid crc32_stream_init( CRC32Ctx* ctx )\n{\n ctx->crc = 0;\n ctx->length = 0;\n}\n\nvoid crc32_stream_compute_uint32( CRC32Ctx* ctx, uint32_t data )\n{\n COMPUTE( ctx->crc, data & 0xFF );\n COMPUTE( ctx->crc, ( data >> 8 ) & 0xFF );\n COMPUTE( ctx->crc, ( data >> 16 ) & 0xFF );\n COMPUTE( ctx->crc, ( data >> 24 ) & 0xFF );\n ctx->length += 4;\n}\n\nvoid crc32_stream_compute_uint8( CRC32Ctx* ctx, uint8_t data )\n{\n COMPUTE( ctx->crc, data );\n ctx->length++;\n}\n\nvoid crc32_stream_finilize( CRC32Ctx* ctx )\n{\n uint32_t len = ctx->length;\n for( ; len != 0; len >>= 8 )\n {\n COMPUTE( ctx->crc, len & 0xFF );\n }\n ctx->crc = ~ctx->crc;\n}\n\n/*** pseudo code ***/\nCRC32Ctx crc;\ncrc32_stream_init(&crc);\n\nwhile((just_received_buffer_len = received_anything()))\n{\n for(int i = 0; i < just_received_buffer_len; i++)\n {\n crc32_stream_compute_uint8(&crc, buf[i]); // assuming buf is uint8_t*\n }\n}\ncrc32_stream_finilize(&crc);\nprintf(\"%x\", crc.crc); // ta daaa\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308/"
] |
123,002
|
<p>So I've got maybe 10 objects each of which has 1-3 dependencies (which I think is ok as far as loose coupling is concerned) but also some settings that can be used to define behavior (timeout, window size, etc).</p>
<p>Now before I started using an Inversion of Control container I would have created a factory and maybe even a simple ObjectSettings object for each of the objects that requires more than 1 setting to keep the size of the constructor to the recommended "less than 4" parameter size. I am now using an inversion of control container and I just don't see all that much of a point to it. Sure I might get a constructor with 7 parameters, but who cares? It's all being filled out by the IoC anyways.</p>
<p>Am I missing something here or is this basically correct?</p>
|
[
{
"answer_id": 142182,
"author": "Lee",
"author_id": 13943,
"author_profile": "https://Stackoverflow.com/users/13943",
"pm_score": 4,
"selected": true,
"text": "Number of constructor arguments Number of classes\n 0 57\n 1 19\n 2 25\n 3 9\n 4 3\n 5 1\n 6 3\n 7 2\n 8 2\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
123,003
|
<p>I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary.</p>
<p><strong>included.xhtml</strong> </p>
<pre><code><ui:component>
<h:inputText id="contained_field"/>
<h:commandButton actionListener="#{backingBean.update}" value="Submit"/>
</ui:component>
</code></pre>
<p><strong>example_containing.xhtml</strong></p>
<pre><code><h:form id="containing_form">
<ui:include src="/included.xhtml"/>
</h:form>
</code></pre>
<p>How may I determine the ID of the form in the <code>update</code> method at runtime? Or better yet, the ID of the input field directly.</p>
|
[
{
"answer_id": 266221,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public void update(javax.faces.event.ActionEvent ac) {\n javax.faces.component.UIComponent myCommand = ac.getComponent( );\n String id = myCommand.getId(); // get the id of the firing component\n\n ..... your code .........\n\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
123,007
|
<p>I can't quite figure this out. Microsoft Access 2000, on the report total section I have totals for three columns that are just numbers. These <code>=Sum[(ThisColumn1)], 2, 3</code>, etc and those grand totls all work fine. </p>
<p>I want to have another column that says <code>=Sum([ThisColumn1])+Sum([ThisColumn2]) + Sum([ThisColumn3])</code> but can't figure those one out. Just get a blank so I am sure there is an error.</p>
|
[
{
"answer_id": 123022,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 3,
"selected": true,
"text": "=[GrandTotal1] + [GrandTotal2] + [GrandTotal3]\n =Sum(Nz([ThisColumn1], 0))\n"
},
{
"answer_id": 123032,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "SELECT SUM(Column1 + Column2 + Column3),\n SUM(Column1),\n SUM(Column2),\n SUM(Column3),\n FROM Your_Table;\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
123,057
|
<p>I have been having some issues with LINQ-To-SQL around memory usage. I'm using it in a Windows Service to do some processing, and I'm looping through a large amount of data that I'm pulling back from the context. Yes - I know I could do this with a stored procedure but there are reasons why that would be a less than ideal solution.</p>
<p>Anyway, what I see basically is memory is not being released even after I call <code>context.SubmitChanges()</code>. So I end up having to do all sorts of weird things like only pull back 100 records at time, or create several contexts and have them all do separate tasks. If I keep the same <code>DataContext</code> and use it later for other calls, it just eats up more and more memory. Even if I call <code>Clear()</code> on the "<code>var tableRows</code>" array that the query returns to me, set it to null, and call <code>SYstem.GC.Collect()</code> - it still doesn't release the memory.</p>
<p>Now I've read some about how you should use <code>DataContexts</code> quickly and dispose of them quickly, but it seems like their ought to be a way to force the context to dump all its data (or all its tracking data for a particular table) at a certain point to guarantee the memory is free.</p>
<p>Anyone know what steps guarantee that the memory is released?</p>
|
[
{
"answer_id": 123081,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 5,
"selected": false,
"text": "IDisposable Dispose using using(DataContext myDC = new DataContext)\n{\n // Do stuff\n} //DataContext is disposed\n"
},
{
"answer_id": 127583,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 2,
"selected": false,
"text": "using(DataContext context = new DataContext())\n{\n while(true)\n {\n int skipAmount = 0;\n var rows = context.tables.Select(x => x.Dept == \"Dept\").Skip(skipAmount).Take(100);\n\n //break out of loop when out of rows\n\n foreach(table t in rows)\n {\n //make changes to t \n }\n\n context.SubmitChanges();\n skipAmount += rows.Count();\n\n rows.Clear();\n rows = null;\n\n //at this point, even though the rows have been cleared and changes have been\n //submitted, the context is still holding onto a reference somewhere to the\n //removed rows. So unless you create a new context, memory usuage keeps on growing\n }\n}\n"
},
{
"answer_id": 39530811,
"author": " Argon",
"author_id": 6839297,
"author_profile": "https://Stackoverflow.com/users/6839297",
"pm_score": 0,
"selected": false,
"text": "using (var db = new DataContext())\n{\n db.ObjectTrackingEnabled = false;\n var documents = from d in db.GetTable<T>()\n select d;\n foreach (var doc in documents)\n {\n ...\n }\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] |
123,075
|
<p>How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like:</p>
<pre><code>//MySQL
SELECT foo FROM table LIMIT 10, 10
</code></pre>
<p>But I can't find a way to define offset.</p>
|
[
{
"answer_id": 123168,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 0,
"selected": false,
"text": "create table #keys (rownum int identity(1,1), key varchar(10))\n\ninsert #keys (key)\nselect TOP 89 key from myTable ORDER BY whatever\n\ndelete #keys where rownumber < 80\n\nselect <columns> from #keys join myTable on #keys.key = myTable.key\n"
},
{
"answer_id": 197046,
"author": "Vertigo",
"author_id": 5468,
"author_profile": "https://Stackoverflow.com/users/5468",
"pm_score": 1,
"selected": true,
"text": "select *\nfrom (select top [rows] * from\n(select top [rows * pagenumber] * from mytable order by id)\norder by id desc)\norder by id\n"
},
{
"answer_id": 2811818,
"author": "Vijay Bobba",
"author_id": 338408,
"author_profile": "https://Stackoverflow.com/users/338408",
"pm_score": 2,
"selected": false,
"text": "select top n * \nfrom tablename \nwhere id not in(\nselect top k id\nfrom tablename \n) \n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5468/"
] |
123,078
|
<p>On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?</p>
|
[
{
"answer_id": 123190,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 7,
"selected": true,
"text": "class Booking < ActiveRecord::Base\n has_many :booking_payments\n ....\n def destroy\n raise \"Cannot delete booking with payments\" unless booking_payments.count == 0\n # ... ok, go ahead and destroy\n super\n end\nend\n def before_destroy\n return true if booking_payments.count == 0\n errors.add :base, \"Cannot delete booking with payments\"\n # or errors.add_to_base in Rails 2\n false\n # Rails 5\n throw(:abort)\nend\n myBooking.destroy myBooking.errors"
},
{
"answer_id": 125518,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 3,
"selected": false,
"text": "def destroy # in controller context\n if (model.valid_destroy?)\n model.destroy # if in model context, use `super`\n end\nend\n"
},
{
"answer_id": 6874233,
"author": "workdreamer",
"author_id": 855668,
"author_profile": "https://Stackoverflow.com/users/855668",
"pm_score": 6,
"selected": false,
"text": "class Booking < ActiveRecord::Base\n\nbefore_destroy :booking_with_payments?\n\nprivate\n\ndef booking_with_payments?\n errors.add(:base, \"Cannot delete booking with payments\") unless booking_payments.count == 0\n\n errors.blank? #return false, to not destroy the element, otherwise, it will delete.\nend\n"
},
{
"answer_id": 17155048,
"author": "Hugo Forte",
"author_id": 231759,
"author_profile": "https://Stackoverflow.com/users/231759",
"pm_score": 2,
"selected": false,
"text": "class ActiveRecord::Base\n def can_destroy?\n self.class.reflect_on_all_associations.all? do |assoc|\n assoc.options[:dependent] != :restrict || (assoc.macro == :has_one && self.send(assoc.name).nil?) || (assoc.macro == :has_many && self.send(assoc.name).empty?)\n end\n end\nend\n"
},
{
"answer_id": 21056053,
"author": "Mateo Vidal",
"author_id": 2077627,
"author_profile": "https://Stackoverflow.com/users/2077627",
"pm_score": 2,
"selected": false,
"text": "class Enterprise < AR::Base\n has_many :products\n before_destroy :enterprise_with_products?\n\n private\n\n def empresas_with_portafolios?\n self.portafolios.empty? \n end\nend\n\nclass Product < AR::Base\n belongs_to :enterprises\nend\n"
},
{
"answer_id": 37880585,
"author": "Raphael Monteiro",
"author_id": 4235629,
"author_profile": "https://Stackoverflow.com/users/4235629",
"pm_score": 4,
"selected": false,
"text": "before_destroy do\n cannot_delete_with_qrcodes\n throw(:abort) if errors.present?\nend\n\ndef cannot_delete_with_qrcodes\n errors.add(:base, 'Cannot delete shop with qrcodes') if qrcodes.any?\nend\n"
},
{
"answer_id": 47968834,
"author": "swordray",
"author_id": 3422600,
"author_profile": "https://Stackoverflow.com/users/3422600",
"pm_score": 1,
"selected": false,
"text": "class ApplicationRecord < ActiveRecord::Base\n before_destroy do\n throw :abort if invalid?(:destroy)\n end\nend\n class Ticket < ApplicationRecord\n validate :validate_expires_on, on: :destroy\n\n def validate_expires_on\n errors.add :expires_on if expires_on > Time.now\n end\nend\n"
},
{
"answer_id": 59034233,
"author": "thisismydesign",
"author_id": 2771889,
"author_profile": "https://Stackoverflow.com/users/2771889",
"pm_score": 4,
"selected": false,
"text": "before_destroy :ensure_something, prepend: true do\n throw(:abort) if errors.present?\nend\n\nprivate\n\ndef ensure_something\n errors.add(:field, \"This isn't a good idea..\") if something_bad\nend\n validate :validate_test, on: :destroy throw(:abort) prepend: true dependent: :destroy has_many has_many :entities, dependent: :restrict_with_error"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21317/"
] |
123,080
|
<p>I know that this is somewhat subjective, but I wonder if there is a generally accepted standard for naming assemblies which contain some "core" functions.</p>
<p>Let's say you got a larger Projects, with Assemblies like</p>
<ul>
<li>Company.Product.WebControls.dll</li>
<li>Company.Product.Net.dll</li>
<li>Company.Product.UserPages.dll</li>
</ul>
<p>and you have a Bunch of "Core" classes, like the Global Error Handler, the global Logging functionality etc.</p>
<p>How would such an assembly generally named? Here are some things I had in mind:</p>
<ul>
<li>Company.Product.dll</li>
<li>Company.Product.Core.dll</li>
<li>Company.Product.Global.dll</li>
<li>Company.Product.Administration.dll</li>
</ul>
<p>Now, while "just pick one and go on" will not cause Armageddon, I'd still like to know if there is an "accepted" way to name those assemblies.</p>
|
[
{
"answer_id": 123150,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 2,
"selected": false,
"text": "Root CompanyName.Root\n SomethingMeaningfulToMe.Root\n"
},
{
"answer_id": 146578,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 5,
"selected": false,
"text": "string int System System.Security System.Xml System.Security.Cryptography System.Security.Cryptography System.Core.dll"
},
{
"answer_id": 5974153,
"author": "Koby Mizrahy",
"author_id": 738162,
"author_profile": "https://Stackoverflow.com/users/738162",
"pm_score": 0,
"selected": false,
"text": "CSG.Core\nCSG.Data\nCSG.Services\n...\n YourCompany.Core\nYourCompany.YourProduct.Core\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
123,088
|
<p><strong>C#6 Update</strong></p>
<p>In <a href="https://msdn.microsoft.com/en-us/magazine/dn802602.aspx" rel="nofollow noreferrer">C#6 <code>?.</code> is now a language feature</a>:</p>
<pre><code>// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null;
// C#6
propertyValue1 = myObject?.StringProperty;
</code></pre>
<p>The question below still applies to older versions, but if developing a new application using the new <code>?.</code> operator is far better practice.</p>
<p><strong>Original Question:</strong></p>
<p>I regularly want to access properties on possibly null objects:</p>
<pre><code>string propertyValue1 = null;
if( myObject1 != null )
propertyValue1 = myObject1.StringProperty;
int propertyValue2 = 0;
if( myObject2 != null )
propertyValue2 = myObject2.IntProperty;
</code></pre>
<p>And so on...</p>
<p>I use this so often that I have a snippet for it.</p>
<p>You can shorten this to some extent with an inline if:</p>
<pre><code>propertyValue1 = myObject != null ? myObject.StringProperty : null;
</code></pre>
<p>However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:</p>
<pre><code>propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;
</code></pre>
<p>What I really want is <code>??</code> style syntax, which works great for directly null types:</p>
<pre><code>int? i = SomeFunctionWhichMightReturnNull();
propertyValue2 = i ?? 0;
</code></pre>
<p>So I came up with the following:</p>
<pre><code>public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action, TResult valueIfNull )
where T : class
{
if ( input != null ) return action( input );
else return valueIfNull;
}
//lets us have a null default if the type is nullable
public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action )
where T : class
where TResult : class
{ return input.IfNotNull( action, null ); }
</code></pre>
<p>This lets me us this syntax:</p>
<pre><code>propertyValue1 = myObject1.IfNotNull( x => x.StringProperty );
propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);
//or one with multiple levels
propertyValue1 = myObject.IfNotNull(
o => o.ObjectProp.IfNotNull( p => p.StringProperty ) );
</code></pre>
<p>This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.</p>
<p>This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:</p>
<pre><code>if( ( obj1 == null && obj2 == null ) ||
( obj1 != null && obj2 != null && obj1.Property == obj2.Property ) )
...
//becomes
if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property )
...
</code></pre>
<p>What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?</p>
<hr>
<p>I guess what I really want here is a compiler/language extension:</p>
<pre><code>propertyValue1 = myObject != null ? myObject.StringProperty : null;
//becomes
propertyValue1 = myObject?StringProperty;
</code></pre>
<p>This would make the complex case far easier:</p>
<pre><code>propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null
//becomes
propertyValue1 = myObject?ObjectProp?StringProperty;
</code></pre>
<p>This would only work for value types, but you could return nullable equivalents:</p>
<pre><code>int? propertyValue2 = myObject?ObjectProp?IntProperty;
//or
int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;
</code></pre>
|
[
{
"answer_id": 123140,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 0,
"selected": false,
"text": "if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property ) \n"
},
{
"answer_id": 123496,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);\n ExtentionClass::IfNotNull(myObject2, x => x.IntProperty, 0);\n"
},
{
"answer_id": 123568,
"author": "Robert Jeppesen",
"author_id": 9436,
"author_profile": "https://Stackoverflow.com/users/9436",
"pm_score": 3,
"selected": false,
"text": "propertyValue1 = myObject.IfNotNull(o => o.ObjectProp.IfNotNull( p => p.StringProperty ) );\n if(myObject != null && myObject.ObjectProp != null)\n propertyValue1 = myObject.ObjectProp.StringProperty;\n"
},
{
"answer_id": 123576,
"author": "Stefan Rusek",
"author_id": 19704,
"author_profile": "https://Stackoverflow.com/users/19704",
"pm_score": 3,
"selected": false,
"text": "class Class1\n{\n public static readonly Class1 Empty = new Class1();\n.\n.\nx = (obj1 ?? Class1.Empty).X;\n"
},
{
"answer_id": 123635,
"author": "mancaus",
"author_id": 13797,
"author_profile": "https://Stackoverflow.com/users/13797",
"pm_score": 1,
"selected": false,
"text": "\npropertyValue1 = Util.IfNotNull(myObject1, x => x.StringProperty );\npropertyValue2 = Util.IfNotNull(myObject2, x => x.IntProperty, 0);\n"
},
{
"answer_id": 124577,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "string x = null;\nint len = x.IfNotNull(y => y.Length, 0);\n public void Test()\n {\n int? x = null;\n int a = x.IfNotNull(z => z.Value + 1, 3);\n int b = x.IfNotNull(z => z.Value + 1);\n }\n"
},
{
"answer_id": 144982,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "public static U PropagateNulls<T,U> ( this T obj\n ,Expression<Func<T,U>> expr) \n{ if (obj==null) return default(U);\n\n //uses a stack to reverse Member1(Member2(obj)) to obj.Member1.Member2 \n var members = new Stack<MemberInfo>();\n\n bool searchingForMembers = true;\n Expression currentExpression = expr.Body;\n\n while (searchingForMembers) switch (currentExpression.NodeType)\n { case ExpressionType.Parameter: searchingForMembers = false; break;\n\n case ExpressionType.MemberAccess: \n { var ma= (MemberExpression) currentExpression;\n members.Push(ma.Member);\n currentExpression = ma.Expression; \n } break; \n\n case ExpressionType.Call:\n { var mc = (MethodCallExpression) currentExpression;\n members.Push(mc.Method);\n\n //only supports 1-arg static methods and 0-arg instance methods\n if ( (mc.Method.IsStatic && mc.Arguments.Count == 1) \n || (mc.Arguments.Count == 0))\n { currentExpression = mc.Method.IsStatic ? mc.Arguments[0]\n : mc.Object; \n break;\n }\n\n throw new NotSupportedException(mc.Method+\" is not supported\");\n } \n\n default: throw new NotSupportedException\n (currentExpression.GetType()+\" not supported\");\n }\n\n object currValue = obj;\n while(members.Count > 0)\n { var m = members.Pop();\n\n switch(m.MemberType)\n { case MemberTypes.Field:\n currValue = ((FieldInfo) m).GetValue(currValue); \n break;\n\n case MemberTypes.Method:\n var method = (MethodBase) m;\n currValue = method.IsStatic\n ? method.Invoke(null,new[]{currValue})\n : method.Invoke(currValue,null); \n break;\n\n case MemberTypes.Property:\n var method = ((PropertyInfo) m).GetGetMethod(true);\n currValue = method.Invoke(currValue,null);\n break;\n\n } \n\n if (currValue==null) return default(U); \n }\n\n return (U) currValue; \n}\n foo.PropagateNulls(x => x.ExtensionMethod().Property.Field.Method());\n"
},
{
"answer_id": 191596,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 5,
"selected": true,
"text": "propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty);\n"
},
{
"answer_id": 27822535,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 1,
"selected": false,
"text": "string propertyValue = myObject?.StringProperty;\n myObject int? propertyValue = myObject?.IntProperty;\n int propertyValue = myObject?.IntProperty ?? 0;\n ?. ?[..] string propertyValue = myObject?[index]; //returns null in case myObject is null\n ?. .Member var result = value?.Substring(0, Math.Min(value.Length, length)).PadRight(length);\n result value value.Length NullReferenceException"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
123,105
|
<p>Is there a window manager for <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008" rel="nofollow noreferrer">Visual Studio 2008</a> like <a href="http://www.codeplex.com/VSWindowManager" rel="nofollow noreferrer">this one</a>. I really liked it, and that's all I used in <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005" rel="nofollow noreferrer">Visual Studio 2005</a> and saw somewhere it is supposed to work in Visual Studio 2008, but it doesn't. I have tried it on many installations of Visual Studio 2008, and it doesn't remember any settings. I really liked being able to easily change window layout quickly. Right now I just manually import and export settings, but it's not an instant process.</p>
<p>What do I have to do to make it work?</p>
|
[
{
"answer_id": 338016,
"author": "pettys",
"author_id": 27846,
"author_profile": "https://Stackoverflow.com/users/27846",
"pm_score": 1,
"selected": false,
"text": "Sub DualMonitorConfiguration_Save()\n SaveWindowConfiguration(\"Dual Monitor Layout\")\nEnd Sub\n\nSub DualMonitorConfiguration_Load()\n LoadWindowConfiguration(\"Dual Monitor Layout\")\nEnd Sub\n\nSub LaptopOnlyConfiguration_Save()\n SaveWindowConfiguration(\"Laptop Only Layout\")\nEnd Sub\n\nSub LaptopOnlyConfiguration_Load()\n LoadWindowConfiguration(\"Laptop Only Layout\")\nEnd Sub\n\nPrivate Sub SaveWindowConfiguration(ByVal configName As String)\n Dim selectedConfig As WindowConfiguration\n selectedConfig = FindWindowConfiguration(configName)\n If selectedConfig Is Nothing Then\n selectedConfig = DTE.WindowConfigurations.Add(configName)\n End If\n\n selectedConfig.Update()\n DTE.StatusBar.Text = \"Window configuration saved: \" & configName\nEnd Sub\n\nSub LoadWindowConfiguration(ByVal configName As String)\n Dim selectedConfig As WindowConfiguration\n selectedConfig = FindWindowConfiguration(configName)\n If selectedConfig Is Nothing Then\n MsgBox(\"Window Configuration \"\"\" & configName & \"\"\" not found.\")\n Else\n selectedConfig.Apply()\n DTE.StatusBar.Text = \"Window configuration applied: \" & configName\n End If\nEnd Sub\n\nPrivate Function FindWindowConfiguration(ByVal name As String) As WindowConfiguration\n Dim selectedLayout As WindowConfiguration\n\n For Each config As WindowConfiguration In DTE.WindowConfigurations\n If config.Name = name Then\n Return config\n End If\n Next\n\n Return Nothing\nEnd Function\n"
},
{
"answer_id": 338039,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 1,
"selected": false,
"text": "<HostApplication>\n <Name>Microsoft Visual Studio</Name>\n <Version>9.0</Version>\n</HostApplication>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14642/"
] |
123,111
|
<p>I recently moved my website to a shared hosting solution at <a href="http://asmallorange.com" rel="nofollow noreferrer">asmallorange.com</a>, but I had to set my domain to use their provided nameservers in order for the site to properly resolve. I was determined to keep control of the domain's DNS but I could find no way to make my top level domain resolve to the shared location which was in the format of </p>
<pre><code>server.asmallorange.com/~username
</code></pre>
<p>So I know I'm missing something here, my question is this: </p>
<p><strong>What in their nameservers/DNS entry makes it possible for <em>server.sharedhost.com/~username</em> to serve as a top level domain? (ie. <a href="http://topleveldomain.com" rel="nofollow noreferrer">http://topleveldomain.com</a>)</strong></p>
|
[
{
"answer_id": 123133,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 4,
"selected": true,
"text": "Host: topleveldomain.com"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] |
123,114
|
<p>So I have logical entities (person, country, etc.), GUI elements / controls, data and navigation controllers / managers, then things like quad-trees and timers, and I always struggle with cleanly separating these things into logical namespaces.</p>
<p>I usually have something like this:</p>
<ul>
<li>Leviathan.GUI.Controls</li>
<li>Leviathan.GUI.Views</li>
<li>Leviathan.Entities</li>
<li>Leviathan.Controllers (data and other stuff)</li>
<li>Leviathan.Helpers (trees and other stuff)</li>
</ul>
<p>Are there any good guides on this? I need to stop this mess.</p>
|
[
{
"answer_id": 123138,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "Company.Product.Tier.Sub.Sub\n Company.Product.LogicalFeatureGrouping\n Company.Product.Addon\n Company.Product.LogicalFeatureGrouping.Addon\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13466/"
] |
123,127
|
<p>I am running my junit tests via ant and they are running substantially slower than via the IDE. My ant call is:</p>
<pre><code> <junit fork="yes" forkmode="once" printsummary="off">
<classpath refid="test.classpath"/>
<formatter type="brief" usefile="false"/>
<batchtest todir="${test.results.dir}/xml">
<formatter type="xml"/>
<fileset dir="src" includes="**/*Test.java" />
</batchtest>
</junit>
</code></pre>
<p>The same test that runs in near instantaneously in my IDE (0.067s) takes 4.632s when run through Ant. In the past, I've been able to speed up test problems like this by using the junit fork parameter but this doesn't seem to be helping in this case. What properties or parameters can I look at to speed up these tests?</p>
<p>More info:</p>
<p>I am using the reported time from the IDE vs. the time that the junit task outputs. This is not the sum total time reported at the end of the ant run.</p>
<p>So, bizarrely, this problem has resolved itself. What could have caused this problem? The system runs on a local disk so that is not the problem.</p>
|
[
{
"answer_id": 140974,
"author": "bsanders",
"author_id": 22200,
"author_profile": "https://Stackoverflow.com/users/22200",
"pm_score": 2,
"selected": false,
"text": "<jvmarg> -Xmx"
},
{
"answer_id": 377899,
"author": "Risser",
"author_id": 7773,
"author_profile": "https://Stackoverflow.com/users/7773",
"pm_score": 2,
"selected": false,
"text": "todir=\"${test.results.dir}/xml\"\n"
},
{
"answer_id": 36776206,
"author": "Kristof Neirynck",
"author_id": 11451,
"author_profile": "https://Stackoverflow.com/users/11451",
"pm_score": 0,
"selected": false,
"text": "<junit fork=\"yes\" forkmode=\"perTest\" printsummary=\"off\" threads=\"4\">\n <classpath refid=\"test.classpath\"/>\n <formatter type=\"brief\" usefile=\"false\"/>\n <batchtest todir=\"${test.results.dir}/xml\">\n <formatter type=\"xml\"/>\n <fileset dir=\"src\" includes=\"**/*Test.java\" />\n </batchtest>\n</junit>\n"
},
{
"answer_id": 44601405,
"author": "Chin",
"author_id": 1748450,
"author_profile": "https://Stackoverflow.com/users/1748450",
"pm_score": 0,
"selected": false,
"text": "forkmode=\"once\" <junit> usefile=\"false\" <formatter>"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] |
123,144
|
<p>I have a custom server control that loads data from a web service into a GridView. Works fine on my page. I want to be able to click on a row and pop a popupcontrol with more detail on the clicked row. I am using the client side events of the DevExpress gridview to handle the onclick. And from JavaScript I am calling a callbackpanel to access my custom server control to get properties to use in the popupcontrol. In the callback, the properties on my server control (which were previously set in order to display the data) are not set, yet any of the other standard controls on the page still have their property settings. Am I missing a setting in my customer server control that will persist my property settings into a callback?</p>
|
[
{
"answer_id": 140974,
"author": "bsanders",
"author_id": 22200,
"author_profile": "https://Stackoverflow.com/users/22200",
"pm_score": 2,
"selected": false,
"text": "<jvmarg> -Xmx"
},
{
"answer_id": 377899,
"author": "Risser",
"author_id": 7773,
"author_profile": "https://Stackoverflow.com/users/7773",
"pm_score": 2,
"selected": false,
"text": "todir=\"${test.results.dir}/xml\"\n"
},
{
"answer_id": 36776206,
"author": "Kristof Neirynck",
"author_id": 11451,
"author_profile": "https://Stackoverflow.com/users/11451",
"pm_score": 0,
"selected": false,
"text": "<junit fork=\"yes\" forkmode=\"perTest\" printsummary=\"off\" threads=\"4\">\n <classpath refid=\"test.classpath\"/>\n <formatter type=\"brief\" usefile=\"false\"/>\n <batchtest todir=\"${test.results.dir}/xml\">\n <formatter type=\"xml\"/>\n <fileset dir=\"src\" includes=\"**/*Test.java\" />\n </batchtest>\n</junit>\n"
},
{
"answer_id": 44601405,
"author": "Chin",
"author_id": 1748450,
"author_profile": "https://Stackoverflow.com/users/1748450",
"pm_score": 0,
"selected": false,
"text": "forkmode=\"once\" <junit> usefile=\"false\" <formatter>"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581/"
] |
123,154
|
<p>I'm working on a .NET WinForms app that needs to print a FEDEX shipping label. As part of the FedEx api, I can get raw label data for the printer. </p>
<p>I just don't know how to send that data to the printer through .NET (I'm using C#). To be clear, the data is already pre formatted into ZPL (Zebra printer language) I just need to send it to the printer without windows mucking it up.</p>
|
[
{
"answer_id": 123200,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 1,
"selected": false,
"text": "private void SendPrintJob(string job)\n{\n TcpClient client = null;\n NetworkStream ns = null;\n byte[] bytes;\n int bytesRead;\n\n IPEndPoint remoteIP;\n Socket sock = null;\n\n try\n {\n remoteIP = new IPEndPoint( IPAddress.Parse(hostName), portNum );\n sock = new Socket(AddressFamily.InterNetwork,\n SocketType.Stream,\n ProtocolType.Tcp);\n sock.Connect(remoteIP);\n\n\n ns = new NetworkStream(sock);\n\n if (ns.DataAvailable)\n {\n bytes = new byte[client.ReceiveBufferSize];\n bytesRead = ns.Read(bytes, 0, bytes.Length);\n }\n\n byte[] toSend = Encoding.ASCII.GetBytes(job);\n ns.Write(toSend, 0, toSend.Length);\n\n if (ns.DataAvailable)\n {\n bytes = new byte[client.ReceiveBufferSize];\n bytesRead = ns.Read(bytes, 0, bytes.Length);\n }\n }\n finally\n { \n if( ns != null ) \n ns.Close();\n\n if( sock != null && sock.Connected )\n sock.Close();\n\n if (client != null)\n client.Close();\n }\n}\n"
},
{
"answer_id": 1161153,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "^XA^PH^XZ"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21325/"
] |
123,159
|
<p>Has anyone done this? Basically, I want to use the html by keeping basic tags such as h1, h2, em, etc; clean all non http addresses in the img and a tags; and HTMLEncode every other tag. </p>
<p>I'm stuck at the HTML Encoding part. I know to remove a node you do a "node.ParentNode.RemoveChild(node);" where node is the object of the class HtmlNode. Instead of removing the node though, I want to HTMLEncode it. </p>
|
[
{
"answer_id": 123522,
"author": "Derek Slager",
"author_id": 18636,
"author_profile": "https://Stackoverflow.com/users/18636",
"pm_score": 1,
"selected": false,
"text": "node.AppendChild(new HtmlTextNode { Text = HttpUtility.HtmlEncode(nodeToDelete.OuterHtml) });\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
] |
123,181
|
<p>Is there a way to test if an object is a dictionary?</p>
<p>In a method I'm trying to get a value from a selected item in a list box. In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time.</p>
<p>I would like to do something similar to this:</p>
<pre><code>if (listBox.ItemsSource is Dictionary<??>)
{
KeyValuePair<??> pair = (KeyValuePair<??>)listBox.SelectedItem;
object value = pair.Value;
}
</code></pre>
<p>Is there a way to do this dynamically at runtime using reflection? I know it's possible to use reflection with generic types and determine the key/value parameters, but I'm not sure if there's a way to do the rest after those values are retrieved.</p>
|
[
{
"answer_id": 123191,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 4,
"selected": false,
"text": "if (listBox.ItemsSource is IDictionary)\n{\n DictionaryEntry pair = (DictionaryEntry)listBox.SelectedItem;\n object value = pair.Value;\n}\n if (listBox.DataSource is IDictionary)\n{\n listBox.ValueMember = \"Value\";\n object value = listBox.SelectedValue;\n listBox.ValueMember = \"\"; //If you need it to generally be empty.\n}\n"
},
{
"answer_id": 123194,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "IDictionary Objects"
},
{
"answer_id": 123227,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": true,
"text": "if (listBox.ItemsSource.IsGenericType && \n typeof(IDictionary<,>).IsAssignableFrom(listBox.ItemsSource.GetGenericTypeDefinition()))\n{\n var method = typeof(KeyValuePair<,>).GetProperty(\"Value\").GetGetMethod();\n var item = method.Invoke(listBox.SelectedItem, null);\n}\n"
},
{
"answer_id": 2010061,
"author": "Randall Sutton",
"author_id": 91177,
"author_profile": "https://Stackoverflow.com/users/91177",
"pm_score": 0,
"selected": false,
"text": "if(typeof(IDictionary).IsAssignableFrom(listBox.ItemsSource.GetType()))\n{\n\n}\n"
},
{
"answer_id": 29649496,
"author": "Lukas Klusis",
"author_id": 2357702,
"author_profile": "https://Stackoverflow.com/users/2357702",
"pm_score": 3,
"selected": false,
"text": "var dictionaryInterfaces = new[]\n{\n typeof(IDictionary<,>),\n typeof(IDictionary),\n typeof(IReadOnlyDictionary<,>),\n};\n\nvar dictionaries = collectionOfAnyTypeObjects\n .Where(d => d.GetType().GetInterfaces()\n .Any(t=> dictionaryInterfaces\n .Any(i=> i == t || t.IsGenericType && i == t.GetGenericTypeDefinition())))\n //notice the difference between IDictionary (interface) and Dictionary (class)\ntypeof(IDictionary<,>).IsAssignableFrom(typeof(IDictionary<,>)) // true \ntypeof(IDictionary<int, int>).IsAssignableFrom(typeof(IDictionary<int, int>)); // true\n\ntypeof(IDictionary<int, int>).IsAssignableFrom(typeof(Dictionary<int, int>)); // true\ntypeof(IDictionary<,>).IsAssignableFrom(typeof(Dictionary<,>)); // false!! in contrast with above line this is little bit unintuitive\n public class CustomReadOnlyDictionary : IReadOnlyDictionary<string, MyClass>\npublic class CustomGenericDictionary : IDictionary<string, MyClass>\npublic class CustomDictionary : IDictionary\n var dictionaries = new object[]\n{\n new Dictionary<string, MyClass>(),\n new ReadOnlyDictionary<string, MyClass>(new Dictionary<string, MyClass>()),\n new CustomReadOnlyDictionary(),\n new CustomDictionary(),\n new CustomGenericDictionary()\n};\n var dictionaries2 = dictionaries.Where(d =>\n {\n var type = d.GetType();\n return type.IsGenericType && typeof(IDictionary<,>).IsAssignableFrom(type.GetGenericTypeDefinition());\n }); // count == 0!!\n var dictionaryInterfaces = new[]\n{\n typeof(IDictionary<,>),\n typeof(IDictionary),\n typeof(IReadOnlyDictionary<,>),\n};\n\nvar dictionaries2 = dictionaries\n .Where(d => d.GetType().GetInterfaces()\n .Any(t=> dictionaryInterfaces\n .Any(i=> i == t || t.IsGenericType && i == t.GetGenericTypeDefinition()))) // count == 5\n"
},
{
"answer_id": 68077528,
"author": "forteddyt",
"author_id": 6472087,
"author_profile": "https://Stackoverflow.com/users/6472087",
"pm_score": 0,
"selected": false,
"text": "IsDictionary(Type type) private static Type[] dictionaryInterfaces = \n{\n typeof(IDictionary<,>),\n typeof(System.Collections.IDictionary),\n typeof(IReadOnlyDictionary<,>),\n};\n\npublic static bool IsDictionary(Type type) \n{\n return dictionaryInterfaces\n .Any(dictInterface =>\n dictInterface == type || // 1\n (type.IsGenericType && dictInterface == type.GetGenericTypeDefinition()) || // 2\n type.GetInterfaces().Any(typeInterface => // 3\n typeInterface == dictInterface ||\n (typeInterface.IsGenericType && dictInterface == typeInterface.GetGenericTypeDefinition())));\n}\n // 1 public System.Collections.IDictionary MyProperty {get; set;} // 2 public IDictionary<SomeObj, SomeObj> MyProperty {get; set;} // 3 .Any type dictionaryInterfaces"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12999/"
] |
123,188
|
<p>In C# when I am done entering the fields of a snippet, I can hit Enter to get to the next line. What is the equivalent Key in VB?</p>
<p>Edit: I prefer not to use the mouse.</p>
|
[
{
"answer_id": 123390,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 3,
"selected": true,
"text": "private _$PropertyName$ As $PropertyType$\nPublic WriteOnly Property $PropertyName$() As $PropertyType$\n Set(ByVal value as $PropertyType$)\n _$PropertyName$ = value\n End Set\nEnd Property $Enter$\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] |
123,198
|
<p>How do I copy a file in Python?</p>
|
[
{
"answer_id": 123212,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 13,
"selected": true,
"text": "shutil import shutil\n\nshutil.copyfile(src, dst)\n\n# 2nd option\nshutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp\n src dst src dst IOError dst copy src dst str shutil shutil.copy2() os.path copy copyfile copyfile"
},
{
"answer_id": 123226,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 6,
"selected": false,
"text": "copyfile(src, dst)\n"
},
{
"answer_id": 123238,
"author": "unmounted",
"author_id": 11596,
"author_profile": "https://Stackoverflow.com/users/11596",
"pm_score": 10,
"selected": false,
"text": "copy2(src,dst) copyfile(src,dst) dst src import shutil\nshutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given\nshutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext\n"
},
{
"answer_id": 125810,
"author": "pi.",
"author_id": 15274,
"author_profile": "https://Stackoverflow.com/users/15274",
"pm_score": 7,
"selected": false,
"text": "def copyfileobj_example(source, dest, buffer_size=1024*1024):\n \"\"\" \n Copy a file from source to dest. source and dest\n must be file-like objects, i.e. any object with a read or\n write method, like for example StringIO.\n \"\"\"\n while True:\n copy_buffer = source.read(buffer_size)\n if not copy_buffer:\n break\n dest.write(copy_buffer)\n def copyfile_example(source, dest):\n # Beware, this example does not handle any edge cases!\n with open(source, 'rb') as src, open(dest, 'wb') as dst:\n copyfileobj_example(src, dst)\n"
},
{
"answer_id": 5310215,
"author": "Noam Manos",
"author_id": 658497,
"author_profile": "https://Stackoverflow.com/users/658497",
"pm_score": 6,
"selected": false,
"text": "import os\nimport shutil\nimport tempfile\n\nfilename1 = tempfile.mktemp (\".txt\")\nopen (filename1, \"w\").close ()\nfilename2 = filename1 + \".copy\"\nprint filename1, \"=>\", filename2\n\nshutil.copy (filename1, filename2)\n\nif os.path.isfile (filename2): print \"Success\"\n\ndirname1 = tempfile.mktemp (\".dir\")\nos.mkdir (dirname1)\ndirname2 = dirname1 + \".copy\"\nprint dirname1, \"=>\", dirname2\n\nshutil.copytree (dirname1, dirname2)\n\nif os.path.isdir (dirname2): print \"Success\"\n"
},
{
"answer_id": 27575238,
"author": "mark",
"author_id": 4379542,
"author_profile": "https://Stackoverflow.com/users/4379542",
"pm_score": 4,
"selected": false,
"text": "os.system('cp nameoffilegeneratedbyprogram /otherdirectory/') os.system('cp '+ rawfile + ' rawdata.dat')\n rawfile"
},
{
"answer_id": 30431587,
"author": "rassa45",
"author_id": 4871483,
"author_profile": "https://Stackoverflow.com/users/4871483",
"pm_score": 4,
"selected": false,
"text": "for line in open(\"file.txt\", \"r\"):\n list.append(line)\n if len(list) == 1000000: \n output.writelines(list)\n del list[:]\n"
},
{
"answer_id": 36396465,
"author": "deepdive",
"author_id": 2235661,
"author_profile": "https://Stackoverflow.com/users/2235661",
"pm_score": 4,
"selected": false,
"text": "subprocess.call from subprocess import call\ncall(\"cp -p <file> <file>\", shell=True)\n"
},
{
"answer_id": 44996087,
"author": "maxschlepzig",
"author_id": 427158,
"author_profile": "https://Stackoverflow.com/users/427158",
"pm_score": 7,
"selected": false,
"text": "shutil import shutil\nshutil.copy('/etc/hostname', '/var/tmp/testhostname')\n"
},
{
"answer_id": 45694203,
"author": "fabda01",
"author_id": 6327658,
"author_profile": "https://Stackoverflow.com/users/6327658",
"pm_score": 5,
"selected": false,
"text": "with open(source, 'rb') as src, open(dest, 'wb') as dst: dst.write(src.read())\n"
},
{
"answer_id": 48273637,
"author": "AbstProcDo",
"author_id": 7301792,
"author_profile": "https://Stackoverflow.com/users/7301792",
"pm_score": 5,
"selected": false,
"text": "shutil_methods =\n{'copy':['shutil.copyfileobj',\n 'shutil.copyfile',\n 'shutil.copymode',\n 'shutil.copystat',\n 'shutil.copy',\n 'shutil.copy2',\n 'shutil.copytree',],\n 'move':['shutil.rmtree',\n 'shutil.move',],\n 'exception': ['exception shutil.SameFileError',\n 'exception shutil.Error'],\n 'others':['shutil.disk_usage',\n 'shutil.chown',\n 'shutil.which',\n 'shutil.ignore_patterns',]\n}\n shutil.copyfileobj(fsrc, fdst[, length]) In [3]: src = '~/Documents/Head+First+SQL.pdf'\nIn [4]: dst = '~/desktop'\nIn [5]: shutil.copyfileobj(src, dst)\nAttributeError: 'str' object has no attribute 'read'\n#copy the file object\nIn [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:\n ...: shutil.copyfileobj(f1, f2)\nIn [8]: os.stat(os.path.join(dst,'test.pdf'))\nOut[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)\n shutil.copyfile(src, dst, *, follow_symlinks=True) In [9]: shutil.copyfile(src, dst)\nIsADirectoryError: [Errno 21] Is a directory: ~/desktop'\n#so dst should be a filename instead of a directory name\n shutil.copy() In [10]: shutil.copy(src, dst)\nOut[10]: ~/desktop/Head+First+SQL.pdf'\n#check their metadata\nIn [25]: os.stat(src)\nOut[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)\nIn [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))\nOut[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)\n# st_atime,st_mtime,st_ctime changed\n shutil.copy2() In [30]: shutil.copy2(src, dst)\nOut[30]: ~/desktop/Head+First+SQL.pdf'\nIn [31]: os.stat(src)\nOut[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)\nIn [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))\nOut[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)\n# Preseved st_mtime\n shutil.copytree()"
},
{
"answer_id": 48374171,
"author": "kmario23",
"author_id": 2956066,
"author_profile": "https://Stackoverflow.com/users/2956066",
"pm_score": 8,
"selected": false,
"text": "shutil os subprocess import os\nimport shutil\nimport subprocess\n shutil shutil.copyfile shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)\n\n# example \nshutil.copyfile('source.txt', 'destination.txt')\n shutil.copy shutil.copy(src_file, dest_file, *, follow_symlinks=True)\n\n# example\nshutil.copy('source.txt', 'destination.txt')\n shutil.copy2 shutil.copy2(src_file, dest_file, *, follow_symlinks=True)\n\n# example\nshutil.copy2('source.txt', 'destination.txt') \n shutil.copyfileobj shutil.copyfileobj(src_file_object, dest_file_object[, length])\n\n# example\nfile_src = 'source.txt' \nf_src = open(file_src, 'rb')\n\nfile_dest = 'destination.txt' \nf_dest = open(file_dest, 'wb')\n\nshutil.copyfileobj(f_src, f_dest) \n os os.popen os.popen(cmd[, mode[, bufsize]])\n\n# example\n# In Unix/Linux\nos.popen('cp source.txt destination.txt') \n\n# In Windows\nos.popen('copy source.txt destination.txt')\n os.system os.system(command)\n\n\n# In Linux/Unix\nos.system('cp source.txt destination.txt') \n\n# In Windows\nos.system('copy source.txt destination.txt')\n subprocess subprocess.call subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)\n\n# example (WARNING: setting `shell=True` might be a security-risk)\n# In Linux/Unix\nstatus = subprocess.call('cp source.txt destination.txt', shell=True) \n\n# In Windows\nstatus = subprocess.call('copy source.txt destination.txt', shell=True)\n subprocess.check_output subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)\n\n# example (WARNING: setting `shell=True` might be a security-risk)\n# In Linux/Unix\nstatus = subprocess.check_output('cp source.txt destination.txt', shell=True)\n\n# In Windows\nstatus = subprocess.check_output('copy source.txt destination.txt', shell=True)\n"
},
{
"answer_id": 55309529,
"author": "Sundeep471",
"author_id": 1838678,
"author_profile": "https://Stackoverflow.com/users/1838678",
"pm_score": 4,
"selected": false,
"text": "open(destination, 'wb').write(open(source, 'rb').read())\n"
},
{
"answer_id": 55851299,
"author": "Marc",
"author_id": 2128265,
"author_profile": "https://Stackoverflow.com/users/2128265",
"pm_score": 4,
"selected": false,
"text": "from pathlib import Path\n\nsource = Path('../path/to/my/file.txt')\ndestination = Path('../path/where/i/want/to/store/it.txt')\ndestination.write_bytes(source.read_bytes())\n write_bytes"
},
{
"answer_id": 56524267,
"author": "Savai Maheshwari",
"author_id": 5770355,
"author_profile": "https://Stackoverflow.com/users/5770355",
"pm_score": -1,
"selected": false,
"text": "shutil.copy(src,dst)\n shutil.copystat(src,dst)\n"
},
{
"answer_id": 65168236,
"author": "Basj",
"author_id": 1422096,
"author_profile": "https://Stackoverflow.com/users/1422096",
"pm_score": 3,
"selected": false,
"text": "with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g:\n while True:\n block = f.read(16*1024*1024) # work by blocks of 16 MB\n if not block: # end of file\n break\n g.write(block)\n os.utime"
},
{
"answer_id": 65535130,
"author": "R J",
"author_id": 4941585,
"author_profile": "https://Stackoverflow.com/users/4941585",
"pm_score": 3,
"selected": false,
"text": "from os import path, makedirs\nfrom shutil import copyfile\nmakedirs(path.dirname(path.abspath(destination_path)), exist_ok=True)\ncopyfile(source_path, destination_path)\n if not path.exists(destination_path):"
},
{
"answer_id": 65709412,
"author": "Leonardo Wildt",
"author_id": 4581384,
"author_profile": "https://Stackoverflow.com/users/4581384",
"pm_score": 3,
"selected": false,
"text": "import os\n\nshutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))\n"
},
{
"answer_id": 69313723,
"author": "Raymond Toh",
"author_id": 11629229,
"author_profile": "https://Stackoverflow.com/users/11629229",
"pm_score": 5,
"selected": false,
"text": "shutil files copying removal"
},
{
"answer_id": 73220840,
"author": "Suleman Elahi",
"author_id": 6304394,
"author_profile": "https://Stackoverflow.com/users/6304394",
"pm_score": -1,
"selected": false,
"text": "def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True):\n '''\n @param src: Source File\n @param dst: Destination File (not file path)\n @param buffer_size: Buffer size to use during copy\n @param perserveFileDate: Preserve the original file date\n '''\n # Check to make sure destination directory exists. If it doesn't create the directory\n dstParent, dstFileName = os.path.split(dst)\n if(not(os.path.exists(dstParent))):\n os.makedirs(dstParent)\n \n # Optimize the buffer for small files\n buffer_size = min(buffer_size,os.path.getsize(src))\n if(buffer_size == 0):\n buffer_size = 1024\n \n if shutil._samefile(src, dst):\n raise shutil.Error(\"`%s` and `%s` are the same file\" % (src, dst))\n for fn in [src, dst]:\n try:\n st = os.stat(fn)\n except OSError:\n # File most likely does not exist\n pass\n else:\n # XXX What about other special files? (sockets, devices...)\n if shutil.stat.S_ISFIFO(st.st_mode):\n raise shutil.SpecialFileError(\"`%s` is a named pipe\" % fn)\n with open(src, 'rb') as fsrc:\n with open(dst, 'wb') as fdst:\n shutil.copyfileobj(fsrc, fdst, buffer_size)\n \n if(perserveFileDate):\n shutil.copystat(src, dst)\n"
},
{
"answer_id": 73673386,
"author": "Yaroslav Nikitenko",
"author_id": 952234,
"author_profile": "https://Stackoverflow.com/users/952234",
"pm_score": -1,
"selected": false,
"text": "os.link(source, dest)\n"
},
{
"answer_id": 74465885,
"author": "Sanaf",
"author_id": 10798137,
"author_profile": "https://Stackoverflow.com/users/10798137",
"pm_score": 1,
"selected": false,
"text": "import os\n\ncopy_file = lambda src_file, dest: os.system(f\"cp {src_file} {dest}\")\n\ncopy_file(\"./file\", \"../new_dir/file\")\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
] |
123,216
|
<p>I can't make td "Date" to have fixed height. If there is less in Body section td Date element is bigger than it should be - even if I set Date height to 10% and Body height to 90%. Any suggestions?</p>
<pre><code><tr>
<td class="Author" rowspan="2">
<a href="#">Claude</a><br />
<a href="#"><img src="Users/4/Avatar.jpeg" style="border-width:0px;" /></a>
</td>
<td class="Date">
Sent:
<span>18.08.2008 20:49:28</span>
</td>
</tr>
<tr>
<td class="Body">
<span>Id lacinia lacus arcu non quis mollis sit. Ligula elit. Ultricies elit cursus. Quis ipsum nec rutrum id tellus aliquam. Tortor arcu fermentum nibh justo leo ante vitae fringilla. Pulvinar aliquam. Fringilla mollis facilisis.</span>
</td>
</tr>
</code></pre>
<p>And my css for now is: </p>
<pre><code>table.ForumThreadViewer td.Date {
text-align: left;
vertical-align: top;
font-size: xx-small;
border-bottom: solid 1 black;
height: 20px;
}
table.ForumThreadViewer td.Body {
text-align: left;
vertical-align: top;
border-top: solid 1 black;
}
table.ForumThreadViewer td.Author {
vertical-align: top;
text-align: left;
}
</code></pre>
<p>It's working for FF but not for IE. :(</p>
|
[
{
"answer_id": 123245,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": ".Date {\n height: 50px;\n}\n"
},
{
"answer_id": 123248,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 0,
"selected": false,
"text": ".Date {\n height: 10%\n}\n.Body {\n height: 90%;\n}\n .Date td colspan=\"2\" .Body td <td> "
},
{
"answer_id": 123253,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 3,
"selected": false,
"text": "<tr> <table> <table>"
},
{
"answer_id": 125276,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 3,
"selected": true,
"text": "<div class=\"post\">\n <div class=\"author\">\n <a href=\"#\">Claude</a><br />\n <a href=\"#\"><img src=\"Users/4/Avatar.jpeg\" /></a> \n </div>\n <div class=\"content\">\n <div class=\"date\">Sent: 18.08.2008 20:49:28</div>\n <div class=\"body\">\n This is the content of the message.\n </div>\n </div>\n <div class=\"clear\"> </div>\n</div>\n div.post {\n border: 1px solid #999;\n margin-bottom: -1px; /* collapse the borders between posts */\n}\ndiv.author {\n float: left;\n width: 150px;\n border-right: 1px solid #999;\n}\ndiv.content {\n border-left: 1px solid #999;\n margin-left: 150px;\n}\ndiv.date {\n border-bottom: 1px solid #999;\n}\ndiv.clear {\n clear: both;\n height: 0;\n line-height: 0;\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] |
123,235
|
<p>I was trying to remove all the lines of a file except the last line but the following command did not work, although file.txt is not empty.</p>
<pre><code>$cat file.txt |tail -1 > file.txt
$cat file.txt
</code></pre>
<p>Why is it so?</p>
|
[
{
"answer_id": 123249,
"author": "Lewis Baumstark",
"author_id": 12000,
"author_profile": "https://Stackoverflow.com/users/12000",
"pm_score": 0,
"selected": false,
"text": "$cat file.txt | tail -1 > anotherfile.txt\n"
},
{
"answer_id": 123260,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 5,
"selected": true,
"text": "file.txt tail tail -1 file.txt >file.txt.new && mv file.txt.new file.txt\n tempfile=\"$(mktemp file.txt.XXXXXX)\"\nchown --reference=file.txt -- \"$tempfile\"\nchmod --reference=file.txt -- \"$tempfile\"\ntail -1 file.txt >\"$tempfile\" && mv -- \"$tempfile\" file.txt\n <<< lastline=\"$(tail -1 file.txt)\"; cat >file.txt <<<\"$lastline\"\n tail -1 file.txt | sponge file.txt\n"
},
{
"answer_id": 123264,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 1,
"selected": false,
"text": "tail -1 file.txt > file2.txt; mv file2.txt file.txt\n"
},
{
"answer_id": 123266,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 0,
"selected": false,
"text": "tail -1 > file.txt"
},
{
"answer_id": 127665,
"author": "Chris",
"author_id": 21695,
"author_profile": "https://Stackoverflow.com/users/21695",
"pm_score": 3,
"selected": false,
"text": "sed -i '$!d' file\n"
},
{
"answer_id": 2512984,
"author": "m104",
"author_id": 4039,
"author_profile": "https://Stackoverflow.com/users/4039",
"pm_score": 2,
"selected": false,
"text": "replace_with_filter() {\n local filename=\"$1\"; shift\n local dd_output byte_count filter_status dd_status\n dd_output=$(\"$@\" <\"$filename\" | dd conv=notrunc of=\"$filename\" 2>&1; echo \"${PIPESTATUS[@]}\")\n { read; read; read -r byte_count _; read filter_status dd_status; } <<<\"$dd_output\"\n (( filter_status > 0 )) && return \"$filter_status\"\n (( dd_status > 0 )) && return \"$dd_status\"\n dd bs=1 seek=\"$byte_count\" if=/dev/null of=\"$filename\"\n}\n\nreplace_with_filter file.txt tail -1\n dd dd dd"
},
{
"answer_id": 2513246,
"author": "ghostdog74",
"author_id": 131527,
"author_profile": "https://Stackoverflow.com/users/131527",
"pm_score": 1,
"selected": false,
"text": "echo \"$(tail -1 file.txt)\" > file.txt\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
123,236
|
<p>We have a customer requesting data in XML format. Normally this is not required as we usually just hand off an Access database or csv files and that is sufficient. However in this case I need to automate the exporting of proper XML from a dozen tables.</p>
<p>If I can do it out of SQL Server 2005, that would be preferred. However I can't for the life of me find a way to do this. I can dump out raw xml data but this is just a tag per row with attribute values. We need something that represents the structure of the tables. Access has an export in xml format that meets our needs. However I'm not sure how this can be automated. It doesn't appear to be available in any way through SQL so I'm trying to track down the necessary code to export the XML through a macro or vbscript.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 123282,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 0,
"selected": false,
"text": "Const acExportTable = 0\n\nSet objAccess = CreateObject(\"Access.Application\")\nobjAccess.OpenCurrentDatabase \"C:\\Scripts\\Test.mdb\"\n\n'Export the table \"Inventory\" to test.xml\nobjAccess.ExportXML acExportTable,\"Inventory\",\"c:\\scripts\\test.xml\"\n"
},
{
"answer_id": 123298,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "SELECT\n *\nFROM\n Customers\nINNER JOIN Orders ON Orders.CustID = Customers.CustID\nFOR XML AUTO\n"
},
{
"answer_id": 128606,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 1,
"selected": false,
"text": "<customer id=\"204\">\n <firstname>John</firstname>\n <lastname>Public</lastname>\n</customer>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8345/"
] |
123,239
|
<p>This is a sample (edited slightly, but you get the idea) of my XML file:</p>
<pre><code><HostCollection>
<ApplicationInfo />
<Hosts>
<Host>
<Name>Test</Name>
<IP>192.168.1.1</IP>
</Host>
<Host>
<Name>Test</Name>
<IP>192.168.1.2</IP>
</Host>
</Hosts>
</HostCollection>
</code></pre>
<p>When my application (VB.NET app) loads, I want to loop through the list of hosts and their attributes and add them to a collection. I was hoping I could use the XPathNodeIterator for this. The examples I found online seemed a little muddied, and I'm hoping someone here can clear things up a bit.</p>
|
[
{
"answer_id": 123275,
"author": "kitsune",
"author_id": 13466,
"author_profile": "https://Stackoverflow.com/users/13466",
"pm_score": 3,
"selected": true,
"text": "Dim doc As XmlDocument = New XmlDocument()\ndoc.Load(\"hosts.xml\")\nDim nodeList as XmlNodeList\nnodeList = doc.SelectNodes(\"/HostCollectionInfo/Hosts/Host\")\n"
},
{
"answer_id": 123310,
"author": "ckarras",
"author_id": 5688,
"author_profile": "https://Stackoverflow.com/users/5688",
"pm_score": 1,
"selected": false,
"text": " XPathDocument xpathDoc;\n using (StreamReader input = ...)\n { \n xpathDoc = new XPathDocument(input);\n }\n\n XPathNavigator nav = xpathDoc.CreateNavigator();\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);\n\n XPathNodeIterator nodes = nav.Select(\"/HostCollection/Hosts/Host\", nsmgr);\n\n while (nodes.MoveNext())\n {\n // access the current Host with nodes.Current\n }\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
] |
123,263
|
<p>I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?</p>
|
[
{
"answer_id": 123294,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 6,
"selected": true,
"text": "string[] formats = {\"yyyyMMdd\", \"MM/dd/yy\"};\nvar Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);\n DateTime result;\nstring[] formats = {\"yyyyMMdd\", \"MM/dd/yy\"};\nDateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);\n"
},
{
"answer_id": 123357,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 2,
"selected": false,
"text": "DateTime outDt;\nbool blnYYYMMDD = \n DateTime.TryParseExact(yourString,\"yyyyMMdd\"\n ,CultureInfo.CurrentCulture,DateTimeStyles.None\n , out outDt);\n"
},
{
"answer_id": 123376,
"author": "Skippy",
"author_id": 2903,
"author_profile": "https://Stackoverflow.com/users/2903",
"pm_score": 0,
"selected": false,
"text": "DateTime output;\nstring input = \"09/23/2008\";\nif (DateTime.TryParseExact(input,\"MM/dd/yy\", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output) || DateTime.TryParseExact(input,\"yyyyMMdd\", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output))\n{\n //handle valid date\n}\nelse\n{\n //handle invalid date\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625/"
] |
123,323
|
<p>How many messages does the queue for a standard window hold? What happens when the queue overflows?</p>
<p>The documentation for <code>GetMessage</code> and relatives doesn't say anything about this, and <code>PeekMessage</code> only gives you a yes/no for certain classes of messages, not a message count.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa925082.aspx" rel="noreferrer">This page</a> says that the queues are implemented using memory-mapped files, and that there is no message count limit, but that page is about WinCE. Does this apply to desktop Win32 as well?</p>
|
[
{
"answer_id": 123331,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 5,
"selected": true,
"text": "PostMessage"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319/"
] |
123,334
|
<p>NOTE: I am not set on using VI, it is just the first thing that came to mind that might be able to do what I need. Feel free to suggest any other program.</p>
<p>I have a form with nearly 100 fields that I would like to auto-fill with PHP. I know how to do the autofill, but I would like to avoid manually adding the needed text to 100 fields.</p>
<p>Is there an automated way I can take the text:</p>
<pre><code><input name="riskRating" id="riskRating" type="text" />
</code></pre>
<p>and change it to:</p>
<pre><code><input name="riskRating" id="riskRating" type="text" value="<?php echo $data['riskRating']; ?>" />
</code></pre>
<p>Remember that I am wanting to do this to almost 100 fields. I am trying to avoid going to each field, pasting in the PHP code and changing the variable name manually.</p>
<p>I'm hoping some VI guru out there knows off the top of his/her head.</p>
|
[
{
"answer_id": 123373,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 2,
"selected": false,
"text": ":%s:\\(<input name=\"\\([^\"]\\+\\)\" id=\"[^\"]\\+\" type=\"text\" \\)/>:\\1value=\"<?php echo $data ['\\2']; ?>\" />:gci"
},
{
"answer_id": 123414,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 4,
"selected": true,
"text": ":%s:<input\\(.* id=\"\\([^\"]*\\)\".*\\) />:<input \\1 value=\"<?php echo $data['\\2']; ?> />:g\n"
},
{
"answer_id": 123457,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 2,
"selected": false,
"text": "<input (.*) id=\"(.*?)\" (.*) />\n <input \\1 id=\"\\2\" \\3 value=\"<?php echo $data['\\2']; ?>\" />\n"
},
{
"answer_id": 123463,
"author": "gsempe",
"author_id": 21052,
"author_profile": "https://Stackoverflow.com/users/21052",
"pm_score": -1,
"selected": false,
"text": "/type=\"text\"\n :%s//type=\"text\" value=\"<?php echo $data riskrating]; ?>\"/g\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.