qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
272,361
|
<p>I wrote a PHP code like this</p>
<pre><code>$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
</code></pre>
<p>But when I remove "http://" from <code>$site</code> I get the following warning:</p>
<blockquote>
<p>Warning:
file_get_contents(www.google.com)
[function.file-get-contents]: failed
to open stream:</p>
</blockquote>
<p>I tried <code>try</code> and <code>catch</code> but it didn't work.</p>
|
[
{
"answer_id": 272373,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 5,
"selected": false,
"text": "$content = @file_get_contents($site);"
},
{
"answer_id": 272377,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 10,
"selected": true,
"text": "if($content === FALSE) { // handle error here... } @ $content = @file_get_contents($site);"
},
{
"answer_id": 617721,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "$content = @file_get_contents(\"http://www.google.com\");\nif (strpos($http_response_header[0], \"200\")) { \n echo \"SUCCESS\";\n} else { \n echo \"FAILED\";\n} \n"
},
{
"answer_id": 3406181,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 7,
"selected": false,
"text": "set_error_handler(\n function ($severity, $message, $file, $line) {\n throw new ErrorException($message, $severity, $severity, $file, $line);\n }\n);\n\ntry {\n file_get_contents('www.google.com');\n}\ncatch (Exception $e) {\n echo $e->getMessage();\n}\n\nrestore_error_handler();\n"
},
{
"answer_id": 6463291,
"author": "Aram Kocharyan",
"author_id": 549848,
"author_profile": "https://Stackoverflow.com/users/549848",
"pm_score": 5,
"selected": false,
"text": "// Returns the contents of a file\nfunction file_contents($path) {\n $str = @file_get_contents($path);\n if ($str === FALSE) {\n throw new Exception(\"Cannot access '$path' to read contents.\");\n } else {\n return $str;\n }\n}\n\n// Example\ntry {\n file_contents(\"a\");\n file_contents(\"b\");\n file_contents(\"c\");\n} catch (Exception $e) {\n // Deal with it.\n echo \"Error: \" , $e->getMessage();\n}\n"
},
{
"answer_id": 9461675,
"author": "ogie",
"author_id": 1235083,
"author_profile": "https://Stackoverflow.com/users/1235083",
"pm_score": -1,
"selected": false,
"text": "$url = @file_get_contents(\"http://www.itreb.info\");\nif ($url) {\n // if url is true execute this \n echo $url;\n} else {\n // if not exceute this \n echo \"connection error\";\n}\n"
},
{
"answer_id": 13365281,
"author": "Laurie",
"author_id": 1603948,
"author_profile": "https://Stackoverflow.com/users/1603948",
"pm_score": 7,
"selected": false,
"text": "if (($data = @file_get_contents(\"http://www.google.com\")) === false) {\n $error = error_get_last();\n echo \"HTTP request failed. Error was: \" . $error['message'];\n} else {\n echo \"Everything went better than expected\";\n}\n try/catch error_get_last file_get_contents"
},
{
"answer_id": 21976530,
"author": "Jrm",
"author_id": 3344672,
"author_profile": "https://Stackoverflow.com/users/3344672",
"pm_score": 3,
"selected": false,
"text": "$this->response_body = @file_get_contents($this->url, false, $context);\nif ($this->response_body === false) {\n $error = error_get_last();\n $error = explode(': ', $error['message']);\n $error = trim($error[2]) . PHP_EOL;\n fprintf(STDERR, 'Error: '. $error);\n die();\n}\n"
},
{
"answer_id": 21976746,
"author": "RafaSashi",
"author_id": 2456038,
"author_profile": "https://Stackoverflow.com/users/2456038",
"pm_score": 4,
"selected": false,
"text": "function custom_file_get_contents($url) {\n return file_get_contents(\n $url,\n false,\n stream_context_create(\n array(\n 'http' => array(\n 'ignore_errors' => true\n )\n )\n )\n );\n}\n\n$content=FALSE;\n\nif($content=custom_file_get_contents($url)) {\n //play with the result\n} else {\n //handle the error\n}\n"
},
{
"answer_id": 24831155,
"author": "Bob Stein",
"author_id": 673991,
"author_profile": "https://Stackoverflow.com/users/673991",
"pm_score": 0,
"selected": false,
"text": "$site=\"http://www.google.com\";\n$old_error_reporting = error_reporting(E_ALL ^ E_WARNING);\n$content = file_get_content($site);\nerror_reporting($old_error_reporting);\nif ($content === FALSE) {\n echo \"Error getting '$site'\";\n} else {\n echo $content;\n}\n"
},
{
"answer_id": 38642120,
"author": "Brad",
"author_id": 26130,
"author_profile": "https://Stackoverflow.com/users/26130",
"pm_score": -1,
"selected": false,
"text": "try {\n $content = file_get_contents($site);\n} catch(\\Exception $e) {\n return 'The file was not found';\n}\n"
},
{
"answer_id": 39837955,
"author": "Jesús Díaz",
"author_id": 1679158,
"author_profile": "https://Stackoverflow.com/users/1679158",
"pm_score": -1,
"selected": false,
"text": "$file = \"path/to/file\";\n\nif(file_exists($file)){\n $content = file_get_contents($file);\n}\n"
},
{
"answer_id": 54588076,
"author": "Muhammad Adeel Malik",
"author_id": 8307587,
"author_profile": "https://Stackoverflow.com/users/8307587",
"pm_score": -1,
"selected": false,
"text": "$content = @file_get_contents($site); \n"
},
{
"answer_id": 55815800,
"author": "Michael de Oz",
"author_id": 4215940,
"author_profile": "https://Stackoverflow.com/users/4215940",
"pm_score": -1,
"selected": false,
"text": "public function get($curl,$options){\n $context = stream_context_create($options);\n $file = @file_get_contents($curl, false, $context);\n $str1=$str2=$status=null;\n sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);\n if($status==200)\n return $file \n else \n throw new \\Exception($http_response_header[0]);\n}\n"
},
{
"answer_id": 60255497,
"author": "Frank Rich",
"author_id": 9986479,
"author_profile": "https://Stackoverflow.com/users/9986479",
"pm_score": -1,
"selected": false,
"text": "if (!file_get_contents($data)) {\n exit('<h1>ERROR MESSAGE</h1>');\n} else {\n return file_get_contents($data);\n}\n"
},
{
"answer_id": 69505316,
"author": "Công Thịnh",
"author_id": 16816194,
"author_profile": "https://Stackoverflow.com/users/16816194",
"pm_score": -1,
"selected": false,
"text": "public function getTitle($url)\n {\n try {\n if (strpos($url, 'www.youtube.com/watch') !== false) {\n $apikey = 'AIzaSyCPeA3MlMPeT1CU18NHfJawWAx18VoowOY';\n $videoId = explode('&', explode(\"=\", $url)[1])[0];\n $url = 'https://www.googleapis.com/youtube/v3/videos?id=' . $videoId . '&key=' . $apikey . '&part=snippet';\n\n $ch = curl_init();\n\n curl_setopt($ch, CURLOPT_HEADER, 0);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);\n curl_setopt($ch, CURLOPT_VERBOSE, 0);\n curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);\n $response = curl_exec($ch);\n curl_close($ch);\n\n $data = json_decode($response);\n $value = json_decode(json_encode($data), true);\n\n $title = $value['items'][0]['snippet']['title'];\n } else {\n set_error_handler(\n function () {\n return false;\n }\n );\n if (($str = file_get_contents($url)) === false) {\n $title = $url;\n } else {\n preg_match(\"/\\<title\\>(.*)\\<\\/title\\>/i\", $str, $title);\n $title = $title[1];\n if (preg_replace('/[\\x00-\\x1F\\x7F-\\xFF]/', '', $title))\n $title = utf8_encode($title);\n $title = html_entity_decode($title);\n }\n restore_error_handler();\n }\n } catch (Exception $e) {\n $title = $url;\n }\n return $title;\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22634/"
] |
272,368
|
<p>If I have a method with a parameter that's an interface, whats the fasts way to see if the interface's reference is of a specific generic type?</p>
<p>More specifically, if I have:</p>
<pre><code>interface IVehicle{}
class Car<T> : IVehicle {}
CheckType(IVehicle param)
{
// How do I check that param is Car<int>?
}
</code></pre>
<p>I'm also going to have to cast after the check. So if there is a way to kill 2 birds with one stone on this one let me know.</p>
|
[
{
"answer_id": 272393,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "Car<int> CheckType(IVehicle param)\n{\n Car<int> car = param as Car<int>;\n if (car != null)\n {\n ...\n }\n}\n"
},
{
"answer_id": 272396,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "Car<int> carOfInt = param as Car<int>;\nif (carOfInt != null)\n{\n // .. yes, it's a Car<int>\n}\n"
},
{
"answer_id": 272402,
"author": "MrKurt",
"author_id": 35296,
"author_profile": "https://Stackoverflow.com/users/35296",
"pm_score": 0,
"selected": false,
"text": "interface IVehicle { }\nclass Car<T> : IVehicle \n{\n static Car<int> CheckType(IVehicle v)\n {\n return v as Car<int>;\n }\n}\n v Car<int>"
},
{
"answer_id": 272405,
"author": "Nick",
"author_id": 26161,
"author_profile": "https://Stackoverflow.com/users/26161",
"pm_score": 2,
"selected": false,
"text": "if(param is Car<int>)\n{\n // Hey, I'm a Car<int>!\n}\n"
},
{
"answer_id": 272444,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "interface IVehicle{}\n\nclass Car<T> : IVehicle {\n\n public static bool CheckType(IVehicle param)\n {\n return param is Car<T>;\n }\n}\n Car<string> c1 = new Car<string>();\nCar<int> c2 = new Car<int>();\nConsole.WriteLine(Car<int>.CheckType(c1));\nConsole.WriteLine(Car<int>.CheckType(c2));\n"
},
{
"answer_id": 273075,
"author": "Robert Giesecke",
"author_id": 35443,
"author_profile": "https://Stackoverflow.com/users/35443",
"pm_score": 1,
"selected": false,
"text": "is CheckType(IVehicle param)\n{\n var isofYourType = param is Car<int>;\n ...\n}\n CheckType(IVehicle param)\n{\n var value = param as Car<int>;\n if(value != null) \n ...\n}\n Car<T> class Car<T>\n{ }\n\ninterface IVehicle { }\n\nclass YourCar : Car<int>, IVehicle\n{ }\n\nstatic bool IsOfType(IVehicle param)\n{\n Type typeRef = param.GetType();\n while (typeRef != null)\n {\n if (typeRef.IsGenericType &&\n typeRef.GetGenericTypeDefinition() == typeof(Car<>))\n {\n return true;\n }\n typeRef = typeRef.BaseType;\n }\n return false;\n}\n\nstatic void Main(string[] args)\n{\n IVehicle test = new YourCar();\n bool x = IsOfType(test);\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
272,387
|
<p>In SQL Server 2005, I want to print out a blank line with the PRINT statement, however, when I run</p>
<pre><code>PRINT ''
</code></pre>
<p>it actually prints a line with a single space.</p>
<p>Does anyone know if it's possible to just print a blank line without the space?</p>
<p>If I print a new line character, it doesn't print a space, but I end up with two new lines.</p>
|
[
{
"answer_id": 272430,
"author": "Loris",
"author_id": 23824,
"author_profile": "https://Stackoverflow.com/users/23824",
"pm_score": 3,
"selected": false,
"text": "PRINT 'BLABLABLA'\nPRINT ''\n PRINT 'BLABLABLA\n' <- the string finishes here!\n"
},
{
"answer_id": 273013,
"author": "user12861",
"author_id": 12861,
"author_profile": "https://Stackoverflow.com/users/12861",
"pm_score": 3,
"selected": false,
"text": "print '\n'"
},
{
"answer_id": 1718073,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "-- Search the web for: SQL PRINT NewLine\n-- What you'll end up finding:\n\nDECLARE @CR AS CHAR(1) -- Carriage Return (CR)\nDECLARE @LF AS CHAR(1) -- Line Feed (LF)\nDECLARE @CrLf AS CHAR(2) -- Carriage Return / Line Feed\n\nSET @CR = CHAR(10)\nSET @LF = CHAR(13)\nSET @CrLf = @CR + @LF\n\nPRINT '--==--==--==--==--=='\nPRINT @CrLf + 'Use variables as you see fit' + @CrLf\nPRINT '--==--==--==--==--=='\n\n-- AntGut\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,401
|
<p>Is there a way on the CVS command line to list all files associated with a tag?</p>
|
[
{
"answer_id": 272420,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "cvs ls -lR -r tag\n"
},
{
"answer_id": 272497,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "cvs -q rlog -R -N -S -rTAGNAME MODULENAME\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21176/"
] |
272,409
|
<p>I'd like to be able to place all my ASP Classic include files outside of the web root. This assures no include files can be called directly via the URL. </p>
<p>What is the best way to accomplish this?</p>
<p>I know I can use a <a href="http://msdn.microsoft.com/en-us/library/zwk103ab.aspx" rel="nofollow noreferrer">virtual directory</a> to reference an includes folder outside of web root, but doesn't that still allow direct access to that directory via the URL? Perhaps I'm misunderstanding the nature of virtual directories.</p>
|
[
{
"answer_id": 15271867,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 0,
"selected": false,
"text": "E:\\includes\\\n \\include.asp\n \\another.asp\nE:\\websites\\\n \\business-website.com\\\n \\config.asp\n \\default.asp\n \\personal-website.com\\\n \\config.asp\n \\default.asp\n \\whatever-website.com\\\n \\config.asp\n \\default.asp\n business-website.com -> E:\\websites\\business-website.com\\\n v. dir /include -> E:\\includes\\\npersonal-website.com -> E:\\websites\\personal-website.com\\\n v. dir /include -> E:\\includes\\\nwhatever-website.com -> E:\\websites\\whatever-website.com\\\n v. dir /include -> E:\\includes\\\n default.asp Files in current directory:\n<!-- #include file=\"config.asp\" -->\n\nFiles in current directory (using virtual path):\n<!-- #include virtual=\"/config.asp\" -->\n\nFiles in include directory:\n<!-- #include virtual=\"/include/include.asp\" -->\n include.asp Files in current directory:\n<!-- #include file=\"another.asp\" -->\n\nFiles in current directory (using virtual path):\n<!-- #include virtual=\"/include/another.asp\" -->\n\nFiles in root application:\n<!-- #include virtual=\"/config.asp\" -->\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26180/"
] |
272,412
|
<p>i want something like this</p>
<ol>
<li><p>the user enter a website link</p></li>
<li><p>i need check the link if the link
doesn't start with 'http://' I want
to append 'http://' to the link .</p></li>
</ol>
<p>how can I do that in PHP ? </p>
|
[
{
"answer_id": 272421,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 5,
"selected": true,
"text": "if (stripos($url, 'http://') !== 0) {\n $url = 'http://' . $url;\n}\n"
},
{
"answer_id": 272432,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": false,
"text": "if (0 !== stripos($url, 'http://') && 0 !== stripos($url, 'https://')) {\n $url = 'http://' . $url;\n}\n"
},
{
"answer_id": 272437,
"author": "Chris Kloberdanz",
"author_id": 28714,
"author_profile": "https://Stackoverflow.com/users/28714",
"pm_score": 2,
"selected": false,
"text": "if (!preg_match(\"/^http:\\/{2}/\",$url)){\n $url = 'http://' . $url;\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22634/"
] |
272,428
|
<p>What is the meaning of the concepts 'covariance' and 'contravariance'?</p>
<p>Given 2 classes, <strong>Animal</strong> and <strong>Elephant</strong> (which inherits from <strong>Animal</strong>), my understanding is that you would get a run-time errors if you try and put an Elephant into an array of Animals, and this happens because Elephant is "bigger" (more specific) than Animal. But could you place an Animal into an array of Elephant, seeing how Elephant is guaranteed to contain the Animal properties?</p>
|
[
{
"answer_id": 12925555,
"author": "David",
"author_id": 94669,
"author_profile": "https://Stackoverflow.com/users/94669",
"pm_score": 0,
"selected": false,
"text": "var things = new List<IThing<IContent>> { new ConcreteThing() }\n public class ConcreteThing : IThing<ConcreteContent>\n{\n\n}\n public interface IThing<out T> where T : IContent\n{\n}\n"
},
{
"answer_id": 53305322,
"author": "Hemendr",
"author_id": 5139020,
"author_profile": "https://Stackoverflow.com/users/5139020",
"pm_score": -1,
"selected": false,
"text": "public interface IGoOut<out T>\n{\n T Func();\n}\npublic interface IComeIn<in T>\n{\n void Action(T obj);\n}\npublic class GoOutClass<T>:IGoOut<T>\n{\n public T Func()\n {\n return default(T);\n }\n}\n\npublic class ComeInClass<T> : IComeIn<T>\n{\n public void Action(T obj) { }\n}\n\n==========================================================\nobject obj = null;\n//Covariance Example [Array + IEnumerable<T> + IEnumerator<T> + IInterface<Out T> + Func<T>]\nobject[] array = (string[]) obj;\nIEnumerable<object> enumerable = (IEnumerable<string>) obj;\nIEnumerator<object> enumerator = (IEnumerator<string>)obj;\nIGoOut<object> goOut = (GoOutClass<string>)obj;\nFunc<object> func = (Func<string>)obj;\n\n\n//Contravariance Example[IInterface<in T>]\nIComeIn<string> comeIn = (ComeInClass<object>) obj;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
272,429
|
<p>I have 4 different named instances of SQL Server 2005 on a single server (for testing purposes). There is no default instance on the server.</p>
<p>Because I will eventually need to allow communication to these instances across the firewall, I have set the ports of each instance statically listening on all IPs for the server.</p>
<p><strong>Edit</strong>: TCP/IP, Shared Memory, and Named Pipes are all enabled. VIA is disabled. The ports are statically set for All IPs on the TCP/IP protocol, and each named instance is using a separate port.</p>
<p>I also have SQLBrowser service running, and all instances are configured to allow remote connections.</p>
<p>One instance is set to the default port (1433), and it works fine.</p>
<p>The other instances, however, exhibit very strange behavior. When I connect to them using the Sql Server Management Studio within the network (so I'm not even crossing the firewall yet), the studio connects without complaining. However, as soon as I try to expand the Database list for the instance, or refresh the instance, or pretty much anything else, I get the following error:</p>
<p>TITLE: Microsoft SQL Server Management Studio</p>
<hr>
<p>Failed to retrieve data for this request. (Microsoft.SqlServer.SmoEnum)</p>
<p>For help, click: <a href="http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&LinkId=20476" rel="nofollow noreferrer">http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&LinkId=20476</a></p>
<hr>
<p>ADDITIONAL INFORMATION:</p>
<p>Failed to connect to server . (Microsoft.SqlServer.ConnectionInfo)</p>
<hr>
<p>A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233)</p>
<p>For help, click: <a href="http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=233&LinkId=20476" rel="nofollow noreferrer">http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=233&LinkId=20476</a></p>
<hr>
|
[
{
"answer_id": 272567,
"author": "andyhky",
"author_id": 2764,
"author_profile": "https://Stackoverflow.com/users/2764",
"pm_score": 3,
"selected": true,
"text": "> sqlcmd -S\n> tcp:NameOfTheServer\\sqlexpress,1433\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24954/"
] |
272,433
|
<p>Some programs read the company name that you entered when Windows was installed and display it in the program. How is this done? Are they simply reading the name from the registry?</p>
|
[
{
"answer_id": 272496,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 1,
"selected": false,
"text": "int details = SystemParametersInfo(SPI_GETOEMINFO, OEMInfo.Capacity, OEMInfo, 0);\n if (details != 0)\n {\n MessageBox.Show(OEMInfo.ToString());\n }\n"
},
{
"answer_id": 272500,
"author": "Xiaofu",
"author_id": 31967,
"author_profile": "https://Stackoverflow.com/users/31967",
"pm_score": 4,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\RegisteredOrganization\n string org = (string)Microsoft.Win32.Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\", \"RegisteredOrganization\", \"\");\n"
},
{
"answer_id": 272501,
"author": "GeneQ",
"author_id": 22556,
"author_profile": "https://Stackoverflow.com/users/22556",
"pm_score": 2,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\RegisteredOrganization\n using Microsoft.Win32;\n RegistryKey hklm = Registry.LocalMachine;\nhklm = hklm.OpenSubKey(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\");\nObject obp = hklm.GetValue(\"RegisteredOrganization\");`\nConsole.WriteLine(\"RegisteredOrganization :{0}\",obp);`\n string org = (string)Microsoft.Win32.Registry.GetValue(\"HKEY_LOCAL_MACHINE\\\\\\Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\", \"RegisteredOrganization\", \"\");\n"
},
{
"answer_id": 272508,
"author": "Ken Pespisa",
"author_id": 30812,
"author_profile": "https://Stackoverflow.com/users/30812",
"pm_score": 0,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\RegisteredOrganization\n"
},
{
"answer_id": 272603,
"author": "Murph",
"author_id": 1070,
"author_profile": "https://Stackoverflow.com/users/1070",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Management;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n ManagementClass c = new ManagementClass(\"Win32_OperatingSystem\");\n\n foreach (ManagementObject o in c.GetInstances())\n {\n Console.WriteLine(\"Registered User: {0}, Organization: {1}\", o[\"RegisteredUser\"], o[\"Organization\"]);\n }\n Console.WriteLine(\"Finis!\");\n Console.ReadKey();\n }\n }\n}\n"
},
{
"answer_id": 272642,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": -1,
"selected": false,
"text": "using Microsoft.Win32;\n\nnamespace Extensions\n{\n public static class MyExtensions\n {\n public static string CompanyName(this RegistryKey key)\n {\n // this string goes in my resources file usually\n return (string)key.OpenSubKey(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\").GetValue(\"RegisteredOrganization\");\n }\n }\n}\n RegistryKey key = Registry.LocalMachine;\nreturn key.CompanyName();\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,438
|
<p>Suppose I create a table in Postgresql with a comment on a column:</p>
<pre><code>create table t1 (
c1 varchar(10)
);
comment on column t1.c1 is 'foo';
</code></pre>
<p>Some time later, I decide to add another column:</p>
<pre><code>alter table t1 add column c2 varchar(20);
</code></pre>
<p>I want to look up the comment contents of the first column, and associate with the new column:</p>
<pre><code>select comment_text from (what?) where table_name = 't1' and column_name = 'c1'
</code></pre>
<p>The (what?) is going to be a system table, but after having looked around in pgAdmin and searching on the web I haven't learnt its name.</p>
<p>Ideally I'd like to be able to:</p>
<pre><code>comment on column t1.c1 is (select ...);
</code></pre>
<p>but I have a feeling that's stretching things a bit far. Thanks for any ideas.</p>
<p>Update: based on the suggestions I received here, I wound up writing a program to automate the task of transferring comments, as part of a larger process of changing the datatype of a Postgresql column. You can read about that <a href="http://wirespeed.wordpress.com/2008/11/07/alter-column-type-postgres/" rel="nofollow noreferrer">on my blog</a>.</p>
|
[
{
"answer_id": 272539,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "CREATE OR REPLACE FUNCTION copy_comment(varchar,int,varchar,varchar) RETURNS int AS $PROC$\nDECLARE\n src_tbl ALIAS FOR $1;\n src_col ALIAS FOR $2;\n dst_tbl ALIAS FOR $3;\n dst_col ALIAS FOR $4;\n row RECORD;\n oid INT;\n comment VARCHAR;\nBEGIN\n FOR row IN EXECUTE 'SELECT DISTINCT tableoid FROM ' || quote_ident(src_tbl) LOOP\n oid := row.tableoid;\n END LOOP;\n\n FOR row IN EXECUTE 'SELECT col_description(' || quote_literal(oid) || ',' || quote_literal(src_col) || ')' LOOP\n comment := row.col_description;\n END LOOP;\n\n EXECUTE 'COMMENT ON COLUMN ' || quote_ident(dst_tbl) || '.' || quote_ident(dst_col) || ' IS ' || quote_literal(comment);\n\n RETURN 1;\nEND;\n$PROC$ LANGUAGE plpgsql;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18625/"
] |
272,454
|
<p><a href="http://localhost:50034/Admin/Delete/723" rel="nofollow noreferrer">http://localhost:50034/Admin/Delete/723</a></p>
<p>Always needs this parameter to perform the action, however, if you go to the URL without the parameter, an exception occurs. How do you handle this and redirect back to the main page without doing anything?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 272472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public ActionResult Details(int? Id)\n{\n if (Id == null)\n return RedirectToAction(\"Index\");\n return View();\n}\n"
},
{
"answer_id": 272482,
"author": "Torkel",
"author_id": 24425,
"author_profile": "https://Stackoverflow.com/users/24425",
"pm_score": 4,
"selected": true,
"text": "public class MyController : Controller\n{\n public void Delete(int? id)\n {\n if (!id.HasValue)\n {\n return RedirectToAction(\"Index\", \"Home\");\n }\n\n ///\n }\n}\n"
},
{
"answer_id": 272515,
"author": "Matthew",
"author_id": 20162,
"author_profile": "https://Stackoverflow.com/users/20162",
"pm_score": 1,
"selected": false,
"text": " routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n );\n public ActionResult Delete(int? id)\n{\n if (id.HasValue)\n {\n // do your normal stuff \n // to delete\n return View(\"afterDeleteView\");\n }\n else\n {\n // no id value passed\n return View(\"noParameterView\");\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,457
|
<p>I'm looking into tightening up our ad code by moving it to an external jQuery script, but I obviously still need some HTML to target the ad to. So I was wondering if I can target a noscript element (or within a noscript element) since I'm going to have to leave that on the page anyway, or if I need to have some other element for the JavaScript to target?</p>
<pre><code><noscript>
<div class="ad"><a href="foo"><img src="bar" alt="ad" /></a></div>
</noscript>
</code></pre>
<p>My intention would be to change or strip the noscript element.</p>
|
[
{
"answer_id": 272474,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 4,
"selected": true,
"text": "<noscript> <noscript> clone()"
},
{
"answer_id": 272545,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 2,
"selected": false,
"text": " <noscript>asdfasFSD</noscript>\n\n <script>\n alert(document.getElementsByTagName(\"noscript\")[0].innerHTML);\n </script>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16124/"
] |
272,458
|
<p>I want my validation.xml to only check for a null if certain options are selected from a dropdown. So far I have</p>
<pre><code><field property="empFDServiceStartDate" depends="requiredif, date">
<arg0 key="Service Start date" resource="false"/>
<var>
<var-name>field[0]</var-name>
<var-value>moverChangeType</var-value>
</var>
<var>
<var-name>fieldTest[0]</var-name>
<var-value>EQUALS</var-value>
</var>
<var>
<var-name>fieldValue[0]</var-name>
<var-value>Conversion</var-value>
</var>
</field>
</code></pre>
<p>When the value "Conversion" is selected from the moverChangeType dropdown, I was hoping that the empFDServiceStartDate field would be checked for nulls before being saved. At the moment this doesn't work and it allows me to save nulls.</p>
<p>Any idea?</p>
<p>I am tied to struts 1.1 and therefore can't use newer commands.</p>
<p>M</p>
|
[
{
"answer_id": 272495,
"author": "Fred",
"author_id": 33630,
"author_profile": "https://Stackoverflow.com/users/33630",
"pm_score": 0,
"selected": false,
"text": "<field property=\"empFDServiceStartDate\" depends=\"requiredif, date\">\n <arg0 key=\"Service Start date\" resource=\"false\"/>\n <var>\n <var-name>test</var-name>\n <var-value>(moverChangeType == \"Conversion\")</var-value>\n </var>\n</field>\n"
},
{
"answer_id": 277365,
"author": "Fred",
"author_id": 33630,
"author_profile": "https://Stackoverflow.com/users/33630",
"pm_score": 1,
"selected": false,
"text": "<field property=\"empFDServiceStartDate\" depends=\"requiredif, date\">\n <arg0 key=\"Service Start date\" resource=\"false\"/>\n <var>\n <var-name>test</var-name>\n <var-value>((moverChangeType == \"Conversion\") or (moverChangeType == \"SomethingElse\"))</var-value>\n </var> \n</field>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,459
|
<p>I wonder if there is a way to set the value of #define in run time.</p>
<p>I assume that there is a query for Oracle specific and Sql Server specific at the code below.</p>
<pre><code>#define oracle
// ...
#if oracle
// some code
#else
// some different code.
#endif
</code></pre>
|
[
{
"answer_id": 272476,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "#if"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4215/"
] |
272,479
|
<p>This function exists on OS X and allows you to pass custom local to the function. setlocale is not thread-safe, and passing locale as parameter is.</p>
<p>If there is no equivalent, any way of locale-independent printf, or printf just for doubles (%g) will be ok.</p>
|
[
{
"answer_id": 272554,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 2,
"selected": false,
"text": "uselocale printf"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
] |
272,503
|
<p>How can I programmatically remove a (known) password from an Excel VBA project?</p>
<p>To be clear: I want to remove the password from the VBA Project, not the workbook or any worksheets.</p>
|
[
{
"answer_id": 7835861,
"author": "Uygar Y",
"author_id": 331338,
"author_profile": "https://Stackoverflow.com/users/331338",
"pm_score": 7,
"selected": false,
"text": "xl workbook.xml <workbookProtection workbookPassword=\"XXXX\" lockStructure=\"1\"/> XXXX XXXX <workbookProtection workbookPassword=\"\" lockStructure=\"1\"/> xl/worksheets/ Sheet1.xml sheet2.xml <sheetProtection password=\"XXXX\" sheet=\"1\" objects=\"1\" scenarios=\"1\" /> <sheetProtection password=\"\" sheet=\"1\" objects=\"1\" scenarios=\"1\" />"
},
{
"answer_id": 48415913,
"author": "Joji Thomas Eapen",
"author_id": 6412888,
"author_profile": "https://Stackoverflow.com/users/6412888",
"pm_score": 5,
"selected": false,
"text": ".xlsm .zip xl/vbaProject.bin DPB= DPx= .zip .xlsm .xlsm"
},
{
"answer_id": 63581446,
"author": "Timo",
"author_id": 1705829,
"author_profile": "https://Stackoverflow.com/users/1705829",
"pm_score": 2,
"selected": false,
"text": "xls Notepad++ DPB= DPx= error 40230"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11916/"
] |
272,504
|
<p>I am using the following code fragment in a php script to safely update a shared resource. </p>
<pre><code>$lock_id = sem_get( ftok( 'tmp/this.lock', 'r'));
sem_acquire($lock_id)
//do something
sem_release($lock_id)
</code></pre>
<p>When I stress test this code with large number of requests I get an error:</p>
<pre><code>Warning: semop() failed acquiring SYSVSEM_SETVAL for key 0x1e: No space left on device in blahblah.php on line 1293
</code></pre>
<p>php sources show the following code for failed acquiring SYSVSEM_SETVAL</p>
<pre><code>while (semop(semid, sop, 3) == -1) {
if (errno != EINTR) {
php3_error(E_WARNING, "semop() failed acquiring SYSVSEM_SETVAL for key 0x%x: %s", key, strerror(errno));
break;
}
}
</code></pre>
<p>which means semop fails with EINTR. man page reveals that the semop() system call was interrupted by a signal. </p>
<p>My question is can I safely ignore this error and retry sem_acquire? </p>
<p><strong>Edit</strong>: I have misunderstood this problem, Pl see the clarification I have posted below.</p>
<p>raj</p>
|
[
{
"answer_id": 272616,
"author": "bog",
"author_id": 20909,
"author_profile": "https://Stackoverflow.com/users/20909",
"pm_score": 2,
"selected": true,
"text": "sem_get() sem_get() sem_op()"
},
{
"answer_id": 272870,
"author": "Rajkumar S",
"author_id": 25453,
"author_profile": "https://Stackoverflow.com/users/25453",
"pm_score": 0,
"selected": false,
"text": "errno == EINTR ENOSPC EINTR ENOSPC semmnu semmni*semms semmnu"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25453/"
] |
272,509
|
<p>I want to explicitly call a view from my controller.</p>
<p>Right now I have:</p>
<pre><code>def some_action
.. do something ...
respond_to do |format|
format.xml
end
end
</code></pre>
<p>... then it calls my some_action.xml.builder view. How can I call some other view? Is there a parameter in respond_to I'm missing?</p>
<p>Thanks,</p>
<p>JP</p>
|
[
{
"answer_id": 272559,
"author": "Gabe Hollombe",
"author_id": 30632,
"author_profile": "https://Stackoverflow.com/users/30632",
"pm_score": 4,
"selected": false,
"text": "# Renders the template located in [TEMPLATE_ROOT]/weblog/show.r(html|xml) (in Rails, app/views/weblog/show.erb)\n render :template => \"weblog/show\"\n\n# Renders the template with a local variable\n render :template => \"weblog/show\", :locals => {:customer => Customer.new}\n"
},
{
"answer_id": 272572,
"author": "Kevin Kaske",
"author_id": 2737,
"author_profile": "https://Stackoverflow.com/users/2737",
"pm_score": 6,
"selected": true,
"text": "respond_to do |format|\n format.html { render :template => \"weblog/show\" }\nend\n"
},
{
"answer_id": 272583,
"author": "Cameron Price",
"author_id": 35526,
"author_profile": "https://Stackoverflow.com/users/35526",
"pm_score": 3,
"selected": false,
"text": "respond_to do |format|\n format.html { render :action => 'show' }\nend\n"
},
{
"answer_id": 16300605,
"author": "Fellow Stranger",
"author_id": 1417223,
"author_profile": "https://Stackoverflow.com/users/1417223",
"pm_score": 3,
"selected": false,
"text": "render \"edit\"\n"
},
{
"answer_id": 25024461,
"author": "Nate",
"author_id": 761771,
"author_profile": "https://Stackoverflow.com/users/761771",
"pm_score": 2,
"selected": false,
"text": "lookup_context before_filter do\n lookup_context.prefixes << 'view_prefix'\nend\n view/view_prefix/show.html show application class MagicController\n before_filter do\n lookup_context.prefixes << 'secondary'\n end\n\n def show\n # ...\n end\nend\n\napp.get '/magic/1`\n GET view/application/show.erb view/magic/show.erb view/secondary/show.erb"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10333/"
] |
272,511
|
<p>Is it possible to write a GUI from inside a function?</p>
<p>The problem is that the callback of all GUI-functions are evaluated in the global workspace. But functions have their own workspace and can not access variables in the global workspace. Is it possible to make the GUI-functions use the workspace of the function? For example:</p>
<pre><code>function myvar = myfunc()
myvar = true;
h_fig = figure;
% create a useless button
uicontrol( h_fig, 'style', 'pushbutton', ...
'string', 'clickme', ...
'callback', 'myvar = false' );
% wait for the button to be pressed
while myvar
pause( 0.2 );
end
close( h_fig );
disp( 'this will never be displayed' );
end
</code></pre>
<p>This event-loop will run indefinitely, since the callback will not modify <code>myvar</code> in the function. Instead it will create a new <code>myvar</code> in the global workspace.</p>
|
[
{
"answer_id": 277818,
"author": "bastibe",
"author_id": 1034,
"author_profile": "https://Stackoverflow.com/users/1034",
"pm_score": 1,
"selected": false,
"text": "function myfunc()\n h_fig = figure;\n\n % add continue_loop to the GUI-handles structure\n fig_handles = guihandles( h_fig );\n fig_handles.continue_loop = true;\n guidata( h_fig, fig_handles );\n\n % create a useless button\n uicontrol( h_fig, 'style', 'pushbutton', ...\n 'string', 'clickme', ...\n 'callback', @gui_callback );\n\n % wait for the button to be pressed\n while fig_handles.continue_loop\n fig_handles = guidata( h_fig ); % update handles\n pause( 0.2 );\n end\n\n close( h_fig );\n disp( 'callback ran successfully' );\nend\n\n% The arguments are the Matlab-defaults for GUI-callbacks.\nfunction gui_callback( hObject, eventdata, handles )\n % modify and save handles-Structure\n handles.continue_loop = false;\n guidata( hObject, handles );\nend\n fig_handles.continue_loop"
},
{
"answer_id": 425347,
"author": "gnovice",
"author_id": 52738,
"author_profile": "https://Stackoverflow.com/users/52738",
"pm_score": 4,
"selected": true,
"text": "function make_useless_button()\n\n % Initialize variables and graphics:\n iCounter = 0;\n hFigure = figure;\n hButton = uicontrol('Style', 'pushbutton', 'Parent', hFigure, ...\n 'String', 'Blah', 'Callback', @increment);\n\n % Nested callback function:\n function increment(~, ~)\n iCounter = iCounter+1;\n disp(iCounter);\n end\n\nend\n increment make_useless_button iCounter increment ~ function make_stop_button()\n\n % Initialize variables and graphics:\n keepLooping = true;\n hFigure = figure;\n hButton = uicontrol('Style', 'pushbutton', 'Parent', hFigure, ...\n 'String', 'Stop', 'Callback', @stop_fcn);\n\n % Keep looping until the button is pressed:\n while keepLooping,\n drawnow;\n end\n\n % Delete the figure:\n delete(hFigure);\n\n % Nested callback function:\n function stop_fcn(~, ~)\n keepLooping = false;\n end\n\nend\n drawnow keepLooping"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1034/"
] |
272,518
|
<p>When I do a ReadLinesFromFile on a file in MSBUILD and go to output that file again, I get all the text on one line. All the Carriage returns and LineFeeds are stripped out.</p>
<pre><code><Project DefaultTargets = "Deploy"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
<ItemGroup>
<MyTextFile Include="$(ReleaseNotesDir)$(NewBuildNumber).txt"/>
</ItemGroup>
<Target Name="ReadReleaseNotes">
<ReadLinesFromFile
File="@(MyTextFile)" >
<Output
TaskParameter="Lines"
ItemName="ReleaseNoteItems"/>
</ReadLinesFromFile>
</Target>
<Target Name="MailUsers" DependsOnTargets="ReadReleaseNotes" >
<Mail SmtpServer="$(MailServer)"
To="$(MyEMail)"
From="$(MyEMail)"
Subject="Test Mail Task"
Body="@(ReleaseNoteItems)" />
</Target>
<Target Name="Deploy">
<CallTarget Targets="MailUsers" />
</Target>
</Project>
</code></pre>
<p>I get the text from the file which normally looks like this</p>
<blockquote>
<pre><code>- New Deployment Tool for BLAH
- Random other stuff()""
</code></pre>
</blockquote>
<p>Coming out like this</p>
<blockquote>
<pre><code>- New Deployment Tool for BLAH;- Random other stuff()""
</code></pre>
</blockquote>
<p>I know that the code for ReadLinesFromFile will pull the data in one line at a time and strip out the carriage returns.</p>
<p>Is there a way to put them back in?
So my e-mail looks all nicely formatted?</p>
<p>Thanks </p>
|
[
{
"answer_id": 274720,
"author": "Todd",
"author_id": 31940,
"author_profile": "https://Stackoverflow.com/users/31940",
"pm_score": 6,
"selected": true,
"text": "ReadLinesFromFile @() <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n\n <ItemGroup>\n <Color Include=\"Red\" />\n <Color Include=\"Blue\" />\n <Color Include=\"Green\" />\n</ItemGroup>\n\n<Target Name=\"Build\">\n <Message Text=\"ItemGroup Color: @(Color)\" />\n</Target>\n\n</Project>\n ItemGroup Color: Red;Blue;Green\n ReadItemsFromFile <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n\n <ItemGroup>\n <File Include=\"$(MSBuildProjectDirectory)\\Test.txt\" />\n </ItemGroup>\n\n <Target Name=\"Build\">\n <ReadLinesFromFile File=\"@(File)\">\n <Output TaskParameter=\"Lines\" ItemName=\"FileContents\" />\n </ReadLinesFromFile>\n\n <Message Text=\"FileContents: @(FileContents)\" />\n <Message Text=\"FileContents Transformed: @(FileContents->'%(Identity)', '%0a%0d')\" />\n </Target>\n\n</Project>\n Red\nGreen\nBlue\n [C:\\temp]:: msbuild test.proj\nMicrosoft (R) Build Engine Version 3.5.21022.8\n[Microsoft .NET Framework, Version 2.0.50727.1433]\nCopyright (C) Microsoft Corporation 2007. All rights reserved.\n\nBuild started 11/8/2008 8:16:59 AM.\nProject \"C:\\temp\\test.proj\" on node 0 (default targets).\n FileContents: Red;Green;Blue\n FileContents Transformed: Red\nGreen\nBlue\nDone Building Project \"C:\\temp\\test.proj\" (default targets).\n\n\nBuild succeeded.\n 0 Warning(s)\n 0 Error(s)\n\nTime Elapsed 00:00:00.03\n @(FileContents->'%(Identity)', '%0a%0d') \n Identity '%0a%0d' %0a %0d"
},
{
"answer_id": 9335100,
"author": "user75810",
"author_id": 75810,
"author_profile": "https://Stackoverflow.com/users/75810",
"pm_score": 5,
"selected": false,
"text": "$([System.IO.File]::ReadAllText($FilePath))\n"
},
{
"answer_id": 35156845,
"author": "romi ares",
"author_id": 2381476,
"author_profile": "https://Stackoverflow.com/users/2381476",
"pm_score": 1,
"selected": false,
"text": "$([System.IO.File]::ReadAllText($(SourceFilePath))):\n\n< WriteLinesToFile File=\"$(DestinationFilePath)\" Lines=\"$([System.IO.File]::ReadAllText($(SourceFilePath)))\"\n Overwrite=\"true\" \n />\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2806/"
] |
272,523
|
<p>I am using winsock and C++ to set up a server application. The problem I'm having is that the call to <code>listen</code> results in a first chance exception. I guess normally these can be ignored (?) but I've found others having the same issue I am where it causes the application to hang every once in a while. Any help would be greatly appreciated.</p>
<p>The first chance exception is:</p>
<blockquote>
<p>First-chance exception at 0x*12345678* in <em>MyApp</em>.exe: 0x000006D9: There are no more endpoints available from the endpoint mapper.</p>
</blockquote>
<p>I've found some evidence that this could be cause by the socket And the code that I'm working with is as follows. The exception occurs on the call to <code>listen</code> in the fifth line from the bottom.</p>
<pre><code> m_accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_accept_fd == INVALID_SOCKET)
{
return false;
}
int optval = 1;
if (setsockopt (m_accept_fd, SOL_SOCKET, SO_REUSEADDR,
(char*)&optval, sizeof(optval)))
{
closesocket(m_accept_fd);
m_accept_fd = INVALID_SOCKET;
return false;
}
struct sockaddr_in local_addr;
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = INADDR_ANY;
local_addr.sin_port = htons(m_port);
if (bind(m_accept_fd, (struct sockaddr *)&local_addr,
sizeof(struct sockaddr_in)) == SOCKET_ERROR)
{
closesocket(m_accept_fd);
return false;
}
if (listen (m_accept_fd, 5) == SOCKET_ERROR)
{
closesocket(m_accept_fd);
return false;
}
</code></pre>
|
[
{
"answer_id": 272682,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 1,
"selected": false,
"text": "listen (m_accept_fd, 5)\n// Limit here ^^^\n"
},
{
"answer_id": 274370,
"author": "Darian Miller",
"author_id": 35696,
"author_profile": "https://Stackoverflow.com/users/35696",
"pm_score": 4,
"selected": true,
"text": "HKLM\\System\\CurrentControlSet\\Services\\Tcpip\\Parameters\n MaxUserPort REG_DWORD 65534 (decimal)\n TcpTimedWaitDelay REG_DWORD 60 (decimal)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34731/"
] |
272,528
|
<p>I was thinking of adding some <strong>Achievements</strong> to our internal bug-tracking and time logging system. It's connected to an SQL Server back-end.</p>
<p>At first I thought that the system could be run on the database, using triggers to, for example, know when:</p>
<ul>
<li>you've logged 1000 hours</li>
<li>created 1000 tickets</li>
<li>closed your own ticket</li>
<li>worked on a ticket that has been not touched in a while.</li>
<li>etc (you know - database-ish things)</li>
</ul>
<p>But then I realized that I would also want purely <strong>front-end achivements</strong> </p>
<ul>
<li>used the advanced search abiltiy</li>
<li>sorted by a column</li>
<li>reset settings to default</li>
<li>searched 500 times</li>
</ul>
<p>It seems like the logic of every achievement must be hand coded. Could anyone imagine an some sort of <em>Achievements Rules Engine</em>, that you for example create scripts for?</p>
<p>And how to store them? If the achievement is:</p>
<ul>
<li>change column sort order 50 times in one session</li>
</ul>
<p>that would imply that every time they sort a listview column it updates the database. </p>
<p>Any thoughts on this Win32 application design problem? I don't think that the <a href="http://en.wikipedia.org/wiki/Gang_of_Four" rel="nofollow noreferrer">Gang of Four</a> have an Achievements <strong>design pattern</strong>.</p>
<hr>
<p><strong>Note:</strong> It's a Win32 client application, not a web-site.</p>
<hr>
<p>i definetly like the idea of an eventing system. Various actions the user takes can raise events through a single eventing object:</p>
<pre><code>protected void TimeEntriesListView_ColumnSort(object sender, EventArgs e)
{
_globalListener.RaiseEvent(EventType.ListViewColumnSort, sender, e);
}
protected void TimeEntriesListView_ColumnDrag(object sender, EventArgs e)
{
_globalListener.RaiseEvent(EventType.ListViewColumnDrag, sender, e);
}
</code></pre>
<p>That object can then have logic added to it to decide which events it wants to count. But more reasonably, various event listeners can attached to the central event listener, and have their custom achievement logic.</p>
|
[
{
"answer_id": 470026,
"author": "ceetheman",
"author_id": 16154,
"author_profile": "https://Stackoverflow.com/users/16154",
"pm_score": 2,
"selected": false,
"text": "Event: TicketCreated\nCondition: UserTicketCount >= 1000\nAchivement: \"Created 1000 tickets\"\n Event: SettingsChanged\nCondition: Settings = DEFAULT\nAchievement: \"Reset to Default\"\n"
},
{
"answer_id": 1760359,
"author": "Bo Flexson",
"author_id": 199706,
"author_profile": "https://Stackoverflow.com/users/199706",
"pm_score": 1,
"selected": false,
"text": "EventItems:\nUserId, EventName, DateOccured, AnyOtherInfo\n\nAchievementQualifiers: \nAchievement Name, AchievementCheckSQL, EventsThisAppliesTo \n(Normalize this, if multiple events apply)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
272,535
|
<p>What program can I use to decompile a class file? Will I actually get Java code, or is it just JVM assembly code?</p>
<p>On Java performance questions on this site I often see responses from people who have "decompiled" the Java class file to see how the compiler optimizes certain things.</p>
|
[
{
"answer_id": 272595,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 10,
"selected": true,
"text": ".class"
},
{
"answer_id": 19144727,
"author": "bmaupin",
"author_id": 399105,
"author_profile": "https://Stackoverflow.com/users/399105",
"pm_score": 5,
"selected": false,
"text": "-skip"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
272,541
|
<p>Is it possible to disable AJAX without disabling JavaScript completely? </p>
|
[
{
"answer_id": 272588,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 5,
"selected": true,
"text": "// ==UserScript==\n// @name Google Clk\n// @namespace googleclk\n// @description Disable Google click tracking\n// @include http://*google.com/*\n// ==/UserScript==\n// Override google's clk() function, which reports all clicks back to google\nunsafeWindow.clk = function(url) {} // { alert(url); } // I use this to test.\n"
},
{
"answer_id": 272612,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "XMLHttpRequest = function(){}\nXMLHttpRequest.prototype = {\n open: function(){},\n send: function(){}\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18196/"
] |
272,544
|
<p>I'm reading Erica Sadun's <em>iPhone Developer's Cookbook</em>, and ran into a question.</p>
<p>She says in the book that the way to find the user's Documents directory is with the code:</p>
<pre><code>[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
</code></pre>
<p>but that seems slightly brittle, and dissimiliar to the normal Mac way of doing it, which would be:</p>
<pre><code>NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
</code></pre>
<p>Are there any particular reasons to use one over the other?</p>
|
[
{
"answer_id": 272677,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 8,
"selected": true,
"text": "NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)\n var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)\n"
},
{
"answer_id": 346992,
"author": "Lee",
"author_id": 31063,
"author_profile": "https://Stackoverflow.com/users/31063",
"pm_score": 6,
"selected": false,
"text": "NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);\nNSString *documentsDirectory = [paths objectAtIndex:0];\n"
},
{
"answer_id": 12850202,
"author": "Zelko",
"author_id": 999638,
"author_profile": "https://Stackoverflow.com/users/999638",
"pm_score": 4,
"selected": false,
"text": "let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first\n"
},
{
"answer_id": 27995841,
"author": "Nguyễn Văn Chung",
"author_id": 4373040,
"author_profile": "https://Stackoverflow.com/users/4373040",
"pm_score": 1,
"selected": false,
"text": "NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];\nNSString *zipLocalPath = [documentPath stringByAppendingString:fileName];\n"
},
{
"answer_id": 46130372,
"author": "Suresh Velusamy",
"author_id": 1614189,
"author_profile": "https://Stackoverflow.com/users/1614189",
"pm_score": -1,
"selected": false,
"text": "var paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735/"
] |
272,552
|
<p>How can I read the status of the battery on my MacBookPro from my own application?</p>
<p>Googling has so far only revealed APIs for device drivers to handle power events - there's nothing about user-land processes accessing this information.</p>
<p>thanks.</p>
|
[
{
"answer_id": 272774,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 6,
"selected": true,
"text": "IOPSCopyPowerSourcesInfo() IOPSCopyPowerSourcesList() IOPSGetPowerSourceDescription()"
},
{
"answer_id": 58019144,
"author": "Bruno",
"author_id": 1347601,
"author_profile": "https://Stackoverflow.com/users/1347601",
"pm_score": 0,
"selected": false,
"text": "pmset -g batt | head -n 1 | cut -c19- | rev | cut -c 2- | rev\n Battery Power\nAC Power\n"
},
{
"answer_id": 72106684,
"author": "hd1",
"author_id": 783412,
"author_profile": "https://Stackoverflow.com/users/783412",
"pm_score": -1,
"selected": false,
"text": "NSPipe *pipe = [NSPipe pipe];\nNSFileHandle *file = pipe.fileHandleForReading;\nNSTask *task = [[NSTask alloc] init];\ntask.launchPath = @\"/usr/bin/pmset -g batt | perl -ne ' print \\\"$1\\n\\\" if /([0-9]+%)/'\";\nNSPipe *pipe = [NSPipe pipe];\ntask.standardOutput = pipe;\n[task launch];\nNSData *data = [pipe availableData];\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6782/"
] |
272,584
|
<p>I have a UITableView cell that is going to have a variable size depending on it's content (potentially several lines of text). </p>
<p>SInce it appears that heightForRowAtIndexPath is called <em>before</em> I layout the cell, I just guess the correct height by calling [NSString sizeWithFont] on my text string. Is there a better way to set the height <em>after</em> I've laid out the text in the cell and have an idea of exactly what size it should be?</p>
|
[
{
"answer_id": 273008,
"author": "Olie",
"author_id": 34820,
"author_profile": "https://Stackoverflow.com/users/34820",
"pm_score": 4,
"selected": true,
"text": "if (0 == heightTable[index]) {\n heightTable[index] = [self prepLayoutForCellAtIndex:index];\n}\nreturn (heightTable[index]);\n"
},
{
"answer_id": 273059,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 2,
"selected": false,
"text": "- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {\nUITableViewCell *cell = [self tableView: tableView cellForRowAtIndexPath: indexPath];\nreturn cell.bounds.size.height;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1967/"
] |
272,590
|
<p>We are developing a WPF application that uses the System.AddIn framework to host add-ins that display additional WPF content. Everything seems to be working fine, but overnight, the application threw the following NullReferenceException:</p>
<pre>
Message: Error : Object reference not set to an instance of an object.
StackTrace : at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers)
at System.AddIn.Pipeline.AddInHwndSourceWrapper.TranslateAccelerator(MSG msg, ModifierKeys modifiers)
at MS.Internal.Controls.AddInHost.System.Windows.Interop.IKeyboardInputSink.TranslateAccelerator(MSG& msg, ModifierKeys modifiers)
at System.Windows.Interop.HwndHost.OnKeyUp(KeyEventArgs e)
at System.Windows.UIElement.OnKeyUpThunk(Object sender, KeyEventArgs e)
at System.Windows.Input.KeyEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawKeyboardActions actions, Int32 scanCode, Boolean isExtendedKey, Boolean isSystemKey, Int32 virtualKey)
at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(MSG& msg, Boolean& handled)
at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers)
at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled)
at System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled)
at System.Windows.Interop.ThreadMessageEventHandler.Invoke(MSG& msg, Boolean& handled)
at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
</pre>
<p>As you can see, none of our code is in the stack trace, so I have no place to fix anything. Anybody have any ideas about possible workarounds?</p>
<p>Thanks for the help!</p>
|
[
{
"answer_id": 273008,
"author": "Olie",
"author_id": 34820,
"author_profile": "https://Stackoverflow.com/users/34820",
"pm_score": 4,
"selected": true,
"text": "if (0 == heightTable[index]) {\n heightTable[index] = [self prepLayoutForCellAtIndex:index];\n}\nreturn (heightTable[index]);\n"
},
{
"answer_id": 273059,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 2,
"selected": false,
"text": "- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {\nUITableViewCell *cell = [self tableView: tableView cellForRowAtIndexPath: indexPath];\nreturn cell.bounds.size.height;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9268/"
] |
272,607
|
<p>Is there a way to pre-compute an array of values based on templates? In the following example I would like the 'powers_of_2' array to have 256 values computed at compile-time if that is possible without having to type all of the values.</p>
<pre><code>#include <iostream>
using namespace std;
template <int X, char Y>
struct power {
enum { value = X * power<X,Y-1>::value };
};
template <int X>
struct power<X,1> {
enum { value = X };
};
template <int X>
struct power<X,0> {
enum { value = 1 };
};
int _tmain(int argc, _TCHAR* argv[])
{
int powers_of_2[] = { power<2,0>::value, power<2,1>::value, ..., power<2,255>::value };
cout << powers_of_2[1] << endl;
return 0;
}
</code></pre>
|
[
{
"answer_id": 272712,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "typedef unsigned char BYTE32[32];\nBYTE32 powers_of_2[256] =\n{\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0},\n// :\n// :\n {32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}\n};\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778/"
] |
272,618
|
<p>I've created a MATLAB class, something like:</p>
<pre><code>classdef myclass
properties
x_array = [];
end
methods
function increment(obj,value)
obj.x_array = [obj.x_array ; value);
end
end
end
</code></pre>
<p>The problem is, the property <code>x_array</code> is never modified when I invoke the <code>increment()</code> function:
ex:</p>
<pre><code>>>s = myclass
>>increment(s,5)
>>s.x_array
ans = []
</code></pre>
<p>I did some research, and I reached a conclusion that this is because of MATLAB using Lazy Copy for objects, making my class inherit the HANDLE class should have solved this, but it didn't, does anybody know why this is happening? And if extending the handle class is indeen the solution, isn't this the right way to do it:</p>
<pre><code>classdef myclass < handle
</code></pre>
<p>or are there any extra steps?</p>
|
[
{
"answer_id": 272920,
"author": "Azim J",
"author_id": 4612,
"author_profile": "https://Stackoverflow.com/users/4612",
"pm_score": 5,
"selected": false,
"text": "classdef myclass<handle\n properties\n x_array = []\n end\n methods\n function obj=increment(obj,val)\n obj.x_array=[obj.x_array val];\n end\n end\nend\n >> s=myclass;\n>> s.increment(5)\n>> s.increment(6)\n>> s\n\ns = \n\nmyclass handle\n\nproperties:\n x_array: [5 6]\n\nlists of methods, events, superclasses\n"
},
{
"answer_id": 39391035,
"author": "Meisam Jalalvand",
"author_id": 6809197,
"author_profile": "https://Stackoverflow.com/users/6809197",
"pm_score": 0,
"selected": false,
"text": "s s = increment(s,5);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34830/"
] |
272,620
|
<p>I am trying to setup a WCF service with multiple endpoints with one of the endpoints using the enableWebScript endpoint behavior so that a Javascript proxy will be created on the client (jsdebug/js).</p>
<p>When adding the Service Reference to my AJAX ScriptManager, the jsdebug file is not found unless the address of the endpoint is blank. The ScriptManager proxy seems to always generate a path of "MyService.svc/jsdebug" to look for the file even though my service has an address of "ajax". The proxy should generate the path as "MyService.svc/ajax/jsdebug".</p>
<p>Is there a setting to get the Proxy generated with the right path? My service is at the root of my website.</p>
<p>works:</p>
<pre><code><endpoint address=""
behaviorConfiguration="ajaxBehavior"
binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="MyTest.Web.ICustomerService" />
</code></pre>
<p>want this (doesn't work):</p>
<pre><code><endpoint address="ajax"
behaviorConfiguration="ajaxBehavior"
binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="MyTest.Web.ICustomerService" />
</code></pre>
|
[
{
"answer_id": 692198,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "<enableWebScript /> service.svc/<operation> service.svc/Add Add <enableWebScript /> UriTemplate"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24188/"
] |
272,630
|
<p>I'm desperately searching for a tool allowing me to copy documents with their old versions from a SharePoint 2003 to a SharePoint 2007 site.<br />
Do you know about any simple (and preferably free) tool which does this?<br /></p>
|
[
{
"answer_id": 6958763,
"author": "Craig J",
"author_id": 880861,
"author_profile": "https://Stackoverflow.com/users/880861",
"pm_score": 1,
"selected": false,
"text": " ` catch (Exception e)\n {\n Console.WriteLine(e.Message);\n bDownloadError = true;\n }\n finally\n {\n if (bDownloadError)\n {\n Console.WriteLine(\"Error in downloading file: \" + fileName);\n Console.WriteLine(\"Moving to next file\");\n }\n\n }\n if (!bDownloadError)\n {\n if (Program.beVerbose)\n {\n Console.WriteLine(\"Attaching \" + fileName);\n }\n byte[] fileContents = MBSPSiteMap.ByteArrayFromFilePath(downloadPath);\n newItem.Attachments.Add(fileName, fileContents);\n File.Delete(downloadPath);\n } `\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34022/"
] |
272,633
|
<p>Given the string "ThisStringHasNoSpacesButItDoesHaveCapitals" what is the best way to add spaces before the capital letters. So the end string would be "This String Has No Spaces But It Does Have Capitals"</p>
<p>Here is my attempt with a RegEx</p>
<pre><code>System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0")
</code></pre>
|
[
{
"answer_id": 272666,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "value value = System.Text.RegularExpressions.Regex.Replace(value, \"[A-Z]\", \" $0\");\n"
},
{
"answer_id": 272809,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 7,
"selected": false,
"text": "\" This String...\" instead of \"This String...\"\n newValue = Regex.Replace(value, \"([a-z])([A-Z])\", \"$1 $2\");\n @\"(\\p{Ll})(\\p{Lu})\" newValue = Regex.Replace(value, @\"((?<=\\p{Ll})\\p{Lu})|((?!\\A)\\p{Lu}(?>\\p{Ll}))\", \" $0\");\n"
},
{
"answer_id": 272897,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "private string SplitCamelCase(string s) \n{ \n Regex upperCaseRegex = new Regex(@\"[A-Z]{1}[a-z]*\"); \n MatchCollection matches = upperCaseRegex.Matches(s); \n List<string> words = new List<string>(); \n foreach (Match match in matches) \n { \n words.Add(match.Value); \n } \n return String.Join(\" \", words.ToArray()); \n}\n"
},
{
"answer_id": 272929,
"author": "Binary Worrier",
"author_id": 18797,
"author_profile": "https://Stackoverflow.com/users/18797",
"pm_score": 9,
"selected": true,
"text": "string AddSpacesToSentence(string text, bool preserveAcronyms)\n{\n if (string.IsNullOrWhiteSpace(text))\n return string.Empty;\n StringBuilder newText = new StringBuilder(text.Length * 2);\n newText.Append(text[0]);\n for (int i = 1; i < text.Length; i++)\n {\n if (char.IsUpper(text[i]))\n if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||\n (preserveAcronyms && char.IsUpper(text[i - 1]) && \n i < text.Length - 1 && !char.IsUpper(text[i + 1])))\n newText.Append(' ');\n newText.Append(text[i]);\n }\n return newText.ToString();\n}\n if (char.IsUpper(text[i]))\n if (char.IsUpper(text[i - 1]))\n if (preserveAcronyms && i < text.Length - 1 && !char.IsUpper(text[i + 1]))\n newText.Append(' ');\n else ;\n else if (text[i - 1] != ' ')\n newText.Append(' ');\n string AddSpacesToSentence(string text)\n{\n if (string.IsNullOrWhiteSpace(text))\n return \"\";\n StringBuilder newText = new StringBuilder(text.Length * 2);\n newText.Append(text[0]);\n for (int i = 1; i < text.Length; i++)\n {\n if (char.IsUpper(text[i]) && text[i - 1] != ' ')\n newText.Append(' ');\n newText.Append(text[i]);\n }\n return newText.ToString();\n}\n"
},
{
"answer_id": 677522,
"author": "Richard Priddy",
"author_id": 82024,
"author_profile": "https://Stackoverflow.com/users/82024",
"pm_score": 2,
"selected": false,
"text": "public static string AddSpacesToSentence(string text)\n{\n if (string.IsNullOrEmpty(text))\n return \"\";\n StringBuilder newText = new StringBuilder(text.Length * 2);\n newText.Append(text[0]);\n for (int i = 1; i < result.Length; i++)\n {\n if (char.IsUpper(result[i]) && !char.IsUpper(result[i - 1]))\n {\n newText.Append(' ');\n }\n else if (i < result.Length)\n {\n if (char.IsUpper(result[i]) && !char.IsUpper(result[i + 1]))\n newText.Append(' ');\n\n }\n newText.Append(result[i]);\n }\n return newText.ToString();\n}\n !char.IsUpper(text[i - 1])"
},
{
"answer_id": 5021570,
"author": "EtienneT",
"author_id": 9140,
"author_profile": "https://Stackoverflow.com/users/9140",
"pm_score": 7,
"selected": false,
"text": "var val = \"ThisIsAStringToTest\";\nval = string.Concat(val.Select(x => Char.IsUpper(x) ? \" \" + x : x.ToString())).TrimStart(' ');\n"
},
{
"answer_id": 5021700,
"author": "Justin Morgan",
"author_id": 399649,
"author_profile": "https://Stackoverflow.com/users/399649",
"pm_score": 2,
"selected": false,
"text": "Regex.Replace(value, @\"\\B[A-Z]\", \" $0\")\n \\B \\b XYzabc Yzabc X Yzabc"
},
{
"answer_id": 5149388,
"author": "tchrist",
"author_id": 471272,
"author_profile": "https://Stackoverflow.com/users/471272",
"pm_score": 3,
"selected": false,
"text": "Testing TheLoneRanger\n Worst: The_Lone_Ranger\n Ok: The_Lone_Ranger\n Better: The_Lone_Ranger\n Best: The_Lone_Ranger\nTesting MountMᶜKinleyNationalPark\n [WRONG] Worst: Mount_MᶜKinley_National_Park\n [WRONG] Ok: Mount_MᶜKinley_National_Park\n [WRONG] Better: Mount_MᶜKinley_National_Park\n Best: Mount_Mᶜ_Kinley_National_Park\nTesting ElÁlamoTejano\n [WRONG] Worst: ElÁlamo_Tejano\n Ok: El_Álamo_Tejano\n Better: El_Álamo_Tejano\n Best: El_Álamo_Tejano\nTesting TheÆvarArnfjörðBjarmason\n [WRONG] Worst: TheÆvar_ArnfjörðBjarmason\n Ok: The_Ævar_Arnfjörð_Bjarmason\n Better: The_Ævar_Arnfjörð_Bjarmason\n Best: The_Ævar_Arnfjörð_Bjarmason\nTesting IlCaffèMacchiato\n [WRONG] Worst: Il_CaffèMacchiato\n Ok: Il_Caffè_Macchiato\n Better: Il_Caffè_Macchiato\n Best: Il_Caffè_Macchiato\nTesting MisterDženanLjubović\n [WRONG] Worst: MisterDženanLjubović\n [WRONG] Ok: MisterDženanLjubović\n Better: Mister_Dženan_Ljubović\n Best: Mister_Dženan_Ljubović\nTesting OleKingHenryⅧ\n [WRONG] Worst: Ole_King_HenryⅧ\n [WRONG] Ok: Ole_King_HenryⅧ\n [WRONG] Better: Ole_King_HenryⅧ\n Best: Ole_King_Henry_Ⅷ\nTesting CarlosⅤºElEmperador\n [WRONG] Worst: CarlosⅤºEl_Emperador\n [WRONG] Ok: CarlosⅤº_El_Emperador\n [WRONG] Better: CarlosⅤº_El_Emperador\n Best: Carlos_Ⅴº_El_Emperador\n #!/usr/bin/env perl\nuse utf8;\nuse strict;\nuse warnings;\n\n# First I'll prove these are fine variable names:\nmy (\n $TheLoneRanger ,\n $MountMᶜKinleyNationalPark ,\n $ElÁlamoTejano ,\n $TheÆvarArnfjörðBjarmason ,\n $IlCaffèMacchiato ,\n $MisterDženanLjubović ,\n $OleKingHenryⅧ ,\n $CarlosⅤºElEmperador ,\n);\n\n# Now I'll load up some string with those values in them:\nmy @strings = qw{\n TheLoneRanger\n MountMᶜKinleyNationalPark\n ElÁlamoTejano\n TheÆvarArnfjörðBjarmason\n IlCaffèMacchiato\n MisterDženanLjubović\n OleKingHenryⅧ\n CarlosⅤºElEmperador\n};\n\nmy($new, $best, $ok);\nmy $mask = \" %10s %-8s %s\\n\";\n\nfor my $old (@strings) {\n print \"Testing $old\\n\";\n ($best = $old) =~ s/(?<=\\p{Lowercase})(?=[\\p{Uppercase}\\p{Lt}])/_/g;\n\n ($new = $old) =~ s/(?<=[a-z])(?=[A-Z])/_/g;\n $ok = ($new ne $best) && \"[WRONG]\";\n printf $mask, $ok, \"Worst:\", $new;\n\n ($new = $old) =~ s/(?<=\\p{Ll})(?=\\p{Lu})/_/g;\n $ok = ($new ne $best) && \"[WRONG]\";\n printf $mask, $ok, \"Ok:\", $new;\n\n ($new = $old) =~ s/(?<=\\p{Ll})(?=[\\p{Lu}\\p{Lt}])/_/g;\n $ok = ($new ne $best) && \"[WRONG]\";\n printf $mask, $ok, \"Better:\", $new;\n\n ($new = $old) =~ s/(?<=\\p{Lowercase})(?=[\\p{Uppercase}\\p{Lt}])/_/g;\n $ok = ($new ne $best) && \"[WRONG]\";\n printf $mask, $ok, \"Best:\", $new;\n}\n"
},
{
"answer_id": 6536233,
"author": "Randyaa",
"author_id": 9518,
"author_profile": "https://Stackoverflow.com/users/9518",
"pm_score": 1,
"selected": false,
"text": "replaceAll(\"(?<=[^^\\\\p{Uppercase}])(?=[\\\\p{Uppercase}])\",\" \");\n"
},
{
"answer_id": 9316659,
"author": "Daryl",
"author_id": 227436,
"author_profile": "https://Stackoverflow.com/users/227436",
"pm_score": 0,
"selected": false,
"text": "\"((?<=\\p{Ll})\\p{Lu})|((?!\\A)\\p{Lu}(?>\\p{Ll}))|((?<=[\\p{Ll}\\p{Lu}])\\p{Nd})|((?<=\\p{Nd})\\p{Lu})\"\n \\p{Ll} [a-z] \\p{Lu} [A-Z] \\p{Nd} [0-9]"
},
{
"answer_id": 11037992,
"author": "cyril",
"author_id": 1456860,
"author_profile": "https://Stackoverflow.com/users/1456860",
"pm_score": 1,
"selected": false,
"text": "static string AddSpacesToColumnName(string columnCaption)\n {\n if (string.IsNullOrWhiteSpace(columnCaption))\n return \"\";\n StringBuilder newCaption = new StringBuilder(columnCaption.Length * 2);\n newCaption.Append(columnCaption[0]);\n int pos = 1;\n for (pos = 1; pos < columnCaption.Length-1; pos++)\n { \n if (char.IsUpper(columnCaption[pos]) && !(char.IsUpper(columnCaption[pos - 1]) && char.IsUpper(columnCaption[pos + 1])))\n newCaption.Append(' ');\n newCaption.Append(columnCaption[pos]);\n }\n newCaption.Append(columnCaption[pos]);\n return newCaption.ToString();\n }\n"
},
{
"answer_id": 11677460,
"author": "Artem",
"author_id": 1555960,
"author_profile": "https://Stackoverflow.com/users/1555960",
"pm_score": 1,
"selected": false,
"text": "\"FooBarBaz\".gsub(/(?!^)(?=[A-Z])/, ' ') # => \"Foo Bar Baz\"\n"
},
{
"answer_id": 12566426,
"author": "Yetiish",
"author_id": 855448,
"author_profile": "https://Stackoverflow.com/users/855448",
"pm_score": 0,
"selected": false,
"text": "public string AddSpacesBeforeUpperCase(string nonSpacedString)\n {\n if (string.IsNullOrEmpty(nonSpacedString))\n return string.Empty;\n\n StringBuilder newText = new StringBuilder(nonSpacedString.Length * 2);\n newText.Append(nonSpacedString[0]);\n\n for (int i = 1; i < nonSpacedString.Length; i++)\n {\n char currentChar = nonSpacedString[i];\n\n // If it is whitespace, we do not need to add another next to it\n if(char.IsWhiteSpace(currentChar))\n {\n continue;\n }\n\n char previousChar = nonSpacedString[i - 1];\n char nextChar = i < nonSpacedString.Length - 1 ? nonSpacedString[i + 1] : nonSpacedString[i];\n\n if (char.IsUpper(currentChar) && !char.IsWhiteSpace(nextChar) \n && !(char.IsUpper(previousChar) && char.IsUpper(nextChar)))\n {\n newText.Append(' ');\n }\n else if (i < nonSpacedString.Length)\n {\n if (char.IsUpper(currentChar) && !char.IsWhiteSpace(nextChar) && !char.IsUpper(nextChar))\n {\n newText.Append(' ');\n }\n }\n\n newText.Append(currentChar);\n }\n\n return newText.ToString();\n }\n"
},
{
"answer_id": 12732616,
"author": "Kevin Stricker",
"author_id": 486620,
"author_profile": "https://Stackoverflow.com/users/486620",
"pm_score": 4,
"selected": false,
"text": "public static string UnPascalCase(this string text)\n{\n if (string.IsNullOrWhiteSpace(text))\n return \"\";\n var newText = new StringBuilder(text.Length * 2);\n newText.Append(text[0]);\n for (int i = 1; i < text.Length; i++)\n {\n var currentUpper = char.IsUpper(text[i]);\n var prevUpper = char.IsUpper(text[i - 1]);\n var nextUpper = (text.Length > i + 1) ? char.IsUpper(text[i + 1]) || char.IsWhiteSpace(text[i + 1]): prevUpper;\n var spaceExists = char.IsWhiteSpace(text[i - 1]);\n if (currentUpper && !spaceExists && (!nextUpper || !prevUpper))\n newText.Append(' ');\n newText.Append(text[i]);\n }\n return newText.ToString();\n}\n Assert.AreEqual(\"For You And I\", \"ForYouAndI\".UnPascalCase());\nAssert.AreEqual(\"For You And The FBI\", \"ForYouAndTheFBI\".UnPascalCase());\nAssert.AreEqual(\"A Man A Plan A Canal Panama\", \"AManAPlanACanalPanama\".UnPascalCase());\nAssert.AreEqual(\"DNS Server\", \"DNSServer\".UnPascalCase());\nAssert.AreEqual(\"For You And I\", \"For You And I\".UnPascalCase());\nAssert.AreEqual(\"Mount Mᶜ Kinley National Park\", \"MountMᶜKinleyNationalPark\".UnPascalCase());\nAssert.AreEqual(\"El Álamo Tejano\", \"ElÁlamoTejano\".UnPascalCase());\nAssert.AreEqual(\"The Ævar Arnfjörð Bjarmason\", \"TheÆvarArnfjörðBjarmason\".UnPascalCase());\nAssert.AreEqual(\"Il Caffè Macchiato\", \"IlCaffèMacchiato\".UnPascalCase());\n//Assert.AreEqual(\"Mister Dženan Ljubović\", \"MisterDženanLjubović\".UnPascalCase());\n//Assert.AreEqual(\"Ole King Henry Ⅷ\", \"OleKingHenryⅧ\".UnPascalCase());\n//Assert.AreEqual(\"Carlos Ⅴº El Emperador\", \"CarlosⅤºElEmperador\".UnPascalCase());\nAssert.AreEqual(\"For You And The FBI\", \"For You And The FBI\".UnPascalCase());\nAssert.AreEqual(\"A Man A Plan A Canal Panama\", \"A Man A Plan A Canal Panama\".UnPascalCase());\nAssert.AreEqual(\"DNS Server\", \"DNS Server\".UnPascalCase());\nAssert.AreEqual(\"Mount Mᶜ Kinley National Park\", \"Mount Mᶜ Kinley National Park\".UnPascalCase());\n"
},
{
"answer_id": 12902560,
"author": "KCITGuy",
"author_id": 1748092,
"author_profile": "https://Stackoverflow.com/users/1748092",
"pm_score": 2,
"selected": false,
"text": "create FUNCTION dbo.PascalCaseWithSpace(@pInput AS VARCHAR(MAX)) RETURNS VARCHAR(MAX)\nBEGIN\n declare @output varchar(8000)\n\nset @output = ''\n\n\nDeclare @vInputLength INT\nDeclare @vIndex INT\nDeclare @vCount INT\nDeclare @PrevLetter varchar(50)\nSET @PrevLetter = ''\n\nSET @vCount = 0\nSET @vIndex = 1\nSET @vInputLength = LEN(@pInput)\n\nWHILE @vIndex <= @vInputLength\nBEGIN\n IF ASCII(SUBSTRING(@pInput, @vIndex, 1)) = ASCII(Upper(SUBSTRING(@pInput, @vIndex, 1)))\n begin \n\n if(@PrevLetter != '' and ASCII(@PrevLetter) = ASCII(Lower(@PrevLetter)))\n SET @output = @output + ' ' + SUBSTRING(@pInput, @vIndex, 1)\n else\n SET @output = @output + SUBSTRING(@pInput, @vIndex, 1) \n\n end\n else\n begin\n SET @output = @output + SUBSTRING(@pInput, @vIndex, 1) \n\n end\n\nset @PrevLetter = SUBSTRING(@pInput, @vIndex, 1) \n\n SET @vIndex = @vIndex + 1\nEND\n\n\nreturn @output\nEND\n"
},
{
"answer_id": 17888613,
"author": "lbrendanl",
"author_id": 1362348,
"author_profile": "https://Stackoverflow.com/users/1362348",
"pm_score": 0,
"selected": false,
"text": "using namespace std;\n\nvoid AddSpacesToSentence(string& testString)\n stringstream ss;\n ss << testString.at(0);\n for (auto it = testString.begin() + 1; it != testString.end(); ++it )\n {\n int index = it - testString.begin();\n char c = (*it);\n if (isupper(c))\n {\n char prev = testString.at(index - 1);\n if (isupper(prev))\n {\n if (index < testString.length() - 1)\n {\n char next = testString.at(index + 1);\n if (!isupper(next) && next != ' ')\n {\n ss << ' ';\n }\n }\n }\n else if (islower(prev)) \n {\n ss << ' ';\n }\n }\n\n ss << c;\n }\n\n cout << ss.str() << endl;\n"
},
{
"answer_id": 19052099,
"author": "Rob Hardy",
"author_id": 1733091,
"author_profile": "https://Stackoverflow.com/users/1733091",
"pm_score": 5,
"selected": false,
"text": "public static class Extensions\n{\n public static string ToSentence( this string Input )\n {\n return new string(Input.SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new[] { ' ', c } : new[] { c }).ToArray());\n }\n}\n MyCasedString.ToSentence()"
},
{
"answer_id": 19361158,
"author": "Brad Irby",
"author_id": 188138,
"author_profile": "https://Stackoverflow.com/users/188138",
"pm_score": 1,
"selected": false,
"text": "<Extension()>\nPublic Function IsNullOrWhiteSpace(value As String) As Boolean\n If value Is Nothing Then\n Return True\n End If\n For i As Integer = 0 To value.Length - 1\n If Not Char.IsWhiteSpace(value(i)) Then\n Return False\n End If\n Next\n Return True\nEnd Function\n\n<Extension()>\nPublic Function UnPascalCase(text As String) As String\n If text.IsNullOrWhiteSpace Then\n Return String.Empty\n End If\n\n Dim newText = New StringBuilder()\n newText.Append(text(0))\n For i As Integer = 1 To text.Length - 1\n Dim currentUpper = Char.IsUpper(text(i))\n Dim prevUpper = Char.IsUpper(text(i - 1))\n Dim nextUpper = If(text.Length > i + 1, Char.IsUpper(text(i + 1)) Or Char.IsWhiteSpace(text(i + 1)), prevUpper)\n Dim spaceExists = Char.IsWhiteSpace(text(i - 1))\n If (currentUpper And Not spaceExists And (Not nextUpper Or Not prevUpper)) Then\n newText.Append(\" \")\n End If\n newText.Append(text(i))\n Next\n Return newText.ToString()\nEnd Function\n"
},
{
"answer_id": 24089054,
"author": "DavidRR",
"author_id": 1497596,
"author_profile": "https://Stackoverflow.com/users/1497596",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Text.RegularExpressions;\n\npublic class RegexExample\n{\n public static void Main()\n {\n var text = \"ThisStringHasNoSpacesButItDoesHaveCapitals\";\n\n // Use negative lookbehind to match all capital letters\n // that do not appear at the beginning of the string.\n var pattern = \"(?<!^)([A-Z])\";\n\n var rgx = new Regex(pattern);\n var result = rgx.Replace(text, \" $1\");\n Console.WriteLine(\"Input: [{0}]\\nOutput: [{1}]\", text, result);\n }\n}\n Input: [ThisStringHasNoSpacesButItDoesHaveCapitals]\nOutput: [This String Has No Spaces But It Does Have Capitals]\n using System;\nusing System.Text.RegularExpressions;\n\npublic class RegexExample\n{\n public static void Main()\n {\n var text = \"ThisStringHasNoSpacesASCIIButItDoesHaveCapitalsLINQ\";\n\n // Use positive lookbehind to locate all upper-case letters\n // that are preceded by a lower-case letter.\n var patternPart1 = \"(?<=[a-z])([A-Z])\";\n\n // Used positive lookbehind and lookahead to locate all\n // upper-case letters that are preceded by an upper-case\n // letter and followed by a lower-case letter.\n var patternPart2 = \"(?<=[A-Z])([A-Z])(?=[a-z])\";\n\n var pattern = patternPart1 + \"|\" + patternPart2;\n var rgx = new Regex(pattern);\n var result = rgx.Replace(text, \" $1$2\");\n\n Console.WriteLine(\"Input: [{0}]\\nOutput: [{1}]\", text, result);\n }\n}\n Input: [ThisStringHasNoSpacesASCIIButItDoesHaveCapitalsLINQ]\nOutput: [This String Has No Spaces ASCII But It Does Have Capitals LINQ]\n"
},
{
"answer_id": 24177148,
"author": "Jonas Pegerfalk",
"author_id": 1918,
"author_profile": "https://Stackoverflow.com/users/1918",
"pm_score": 1,
"selected": false,
"text": "\"PascalCaseInputStringIsTurnedIntoSentence\".Humanize() => \"Pascal case input string is turned into sentence\"\n\"Underscored_input_string_is_turned_into_sentence\".Humanize() => \"Underscored input string is turned into sentence\"\n\"Underscored_input_String_is_turned_INTO_sentence\".Humanize() => \"Underscored input String is turned INTO sentence\"\n\n// acronyms are left intact\n\"HTML\".Humanize() => \"HTML\"\n"
},
{
"answer_id": 27326598,
"author": "Serj Sagan",
"author_id": 550975,
"author_profile": "https://Stackoverflow.com/users/550975",
"pm_score": 0,
"selected": false,
"text": "public string Sentencify(string value)\n{\n if (string.IsNullOrWhiteSpace(value))\n return string.Empty;\n\n string final = string.Empty;\n for (int i = 0; i < value.Length; i++)\n {\n if (i != 0 && Char.IsUpper(value[i]))\n {\n if (!Char.IsUpper(value[i - 1]))\n final += \" \";\n else if (i < (value.Length - 1))\n {\n if (!Char.IsUpper(value[i + 1]) && !((value.Length >= i && value[i + 1] == 's') ||\n (value.Length >= i + 1 && value[i + 1] == 'e' && value[i + 2] == 's')))\n final += \" \";\n }\n }\n\n final += value[i];\n }\n\n return final;\n}\n string test1 = \"RegularOTs\";\nstring test2 = \"ThisStringHasNoSpacesASCIIButItDoesHaveCapitalsLINQ\";\nstring test3 = \"ThisStringHasNoSpacesButItDoesHaveCapitals\";\n"
},
{
"answer_id": 29222001,
"author": "CrazyTim",
"author_id": 737393,
"author_profile": "https://Stackoverflow.com/users/737393",
"pm_score": 0,
"selected": false,
"text": "Dim s As String = \"ThisStringHasNoSpacesButItDoesHaveCapitals\"\ns = System.Text.RegularExpressions.Regex.Replace(s, \"([a-z])([A-Z](?=[A-Z])[a-z]*)\", \"$1 $2\")\ns = System.Text.RegularExpressions.Regex.Replace(s, \"([A-Z])([A-Z][a-z])\", \"$1 $2\")\ns = System.Text.RegularExpressions.Regex.Replace(s, \"([a-z])([A-Z][a-z])\", \"$1 $2\")\ns = System.Text.RegularExpressions.Regex.Replace(s, \"([a-z])([A-Z][a-z])\", \"$1 $2\") // repeat a second time\n \"ThisStringHasNoSpacesButItDoesHaveCapitals\"\n\"IAmNotAGoat\"\n\"LOLThatsHilarious!\"\n\"ThisIsASMSMessage\"\n \"This String Has No Spaces But It Does Have Capitals\"\n\"I Am Not A Goat\"\n\"LOL Thats Hilarious!\"\n\"This Is ASMS Message\" // (Difficult to handle single letter words when they are next to acronyms.)\n"
},
{
"answer_id": 34857039,
"author": "st3_121",
"author_id": 3259100,
"author_profile": "https://Stackoverflow.com/users/3259100",
"pm_score": 0,
"selected": false,
"text": "for (int i = 0; i < result.Length; i++)\n{\n if (char.IsUpper(result[i]))\n {\n counter++;\n if (i > 1) //stops from adding a space at if string starts with Capital\n {\n result = result.Insert(i, \" \");\n i++; //Required** otherwise stuck in infinite \n //add space loop over a single capital letter.\n }\n }\n}\n"
},
{
"answer_id": 35486198,
"author": "Matthias Thomann",
"author_id": 2987659,
"author_profile": "https://Stackoverflow.com/users/2987659",
"pm_score": 3,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nconst string myStringWithoutSpaces = \"ThisIsAStringWithoutSpaces\";\nvar myStringWithSpaces = Regex.Replace(myStringWithoutSpaces, \"([A-Z])([a-z]*)\", \" $1$2\");\n \"This Is A String Without Spaces\"\n"
},
{
"answer_id": 36755271,
"author": "johnny 5",
"author_id": 1938988,
"author_profile": "https://Stackoverflow.com/users/1938988",
"pm_score": 2,
"selected": false,
"text": "public string ResolveName(string name)\n{\n var tmpDisplay = Regex.Replace(name, \"([^A-Z ])([A-Z])\", \"$1 $2\");\n return Regex.Replace(tmpDisplay, \"([A-Z]+)([A-Z][^A-Z$])\", \"$1 $2\").Trim();\n}\n"
},
{
"answer_id": 42671598,
"author": "João Sequeira",
"author_id": 5218746,
"author_profile": "https://Stackoverflow.com/users/5218746",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// String Extension Method\n/// Adds white space to strings based on Upper Case Letters\n/// </summary>\n/// <example>\n/// strIn => \"HateJPMorgan\"\n/// preserveAcronyms false => \"Hate JP Morgan\"\n/// preserveAcronyms true => \"Hate JPMorgan\"\n/// </example>\n/// <param name=\"strIn\">to evaluate</param>\n/// <param name=\"preserveAcronyms\" >determines saving acronyms (Optional => false) </param>\npublic static string AddSpaces(this string strIn, bool preserveAcronyms = false)\n{\n if (string.IsNullOrWhiteSpace(strIn))\n return String.Empty;\n\n var stringBuilder = new StringBuilder(strIn.Length * 2)\n .Append(strIn[0]);\n\n int i;\n\n for (i = 1; i < strIn.Length - 1; i++)\n {\n var c = strIn[i];\n\n if (Char.IsUpper(c) && (Char.IsLower(strIn[i - 1]) || (preserveAcronyms && Char.IsLower(strIn[i + 1]))))\n stringBuilder.Append(' ');\n\n stringBuilder.Append(c);\n }\n\n return stringBuilder.Append(strIn[i]).ToString();\n}\n"
},
{
"answer_id": 43238888,
"author": "Dave Cousineau",
"author_id": 621316,
"author_profile": "https://Stackoverflow.com/users/621316",
"pm_score": 1,
"selected": false,
"text": "Aggregate someString\n.Aggregate(\n new StringBuilder(),\n (str, ch) => {\n if (char.IsUpper(ch) && str.Length > 0)\n str.Append(\" \");\n str.Append(ch);\n return str;\n }\n).ToString();\n"
},
{
"answer_id": 44899859,
"author": "Hareendra Donapati",
"author_id": 6690847,
"author_profile": "https://Stackoverflow.com/users/6690847",
"pm_score": 0,
"selected": false,
"text": " private string GetProperName(string Header)\n {\n if (Header.ToCharArray().Where(c => Char.IsUpper(c)).Count() == 1)\n {\n return Header;\n }\n else\n {\n string ReturnHeader = Header[0].ToString();\n for(int i=1; i<Header.Length;i++)\n {\n if (char.IsLower(Header[i-1]) && char.IsUpper(Header[i]))\n {\n ReturnHeader += \" \" + Header[i].ToString();\n }\n else\n {\n ReturnHeader += Header[i].ToString();\n }\n }\n\n return ReturnHeader;\n }\n\n return Header;\n }\n"
},
{
"answer_id": 50480513,
"author": "Artur A",
"author_id": 304371,
"author_profile": "https://Stackoverflow.com/users/304371",
"pm_score": 0,
"selected": false,
"text": "fold Aggregate public static string SpaceCapitals(this string arg) =>\n new string(arg.Aggregate(new List<Char>(),\n (accum, x) => \n {\n if (Char.IsUpper(x) &&\n accum.Any() &&\n // prevent double spacing\n accum.Last() != ' ' &&\n // prevent spacing acronyms (ASCII, SCSI)\n !Char.IsUpper(accum.Last()))\n {\n accum.Add(' ');\n }\n\n accum.Add(x);\n\n return accum;\n }).ToArray());\n \" SpacedWord \" => \" Spaced Word \", \n\n\"Inner Space\" => \"Inner Space\", \n\n\"SomeACRONYM\" => \"Some ACRONYM\".\n"
},
{
"answer_id": 55565072,
"author": "Prince Owusu",
"author_id": 5265873,
"author_profile": "https://Stackoverflow.com/users/5265873",
"pm_score": 0,
"selected": false,
"text": " string AddSpacesToSentence(string value, bool spaceLowerChar = true, bool spaceDigitChar = true, bool spaceSymbolChar = false)\n {\n var result = \"\";\n\n for (int i = 0; i < value.Length; i++)\n {\n char currentChar = value[i];\n char nextChar = value[i < value.Length - 1 ? i + 1 : value.Length - 1];\n\n if (spaceLowerChar && char.IsLower(currentChar) && !char.IsLower(nextChar))\n {\n result += value[i] + \" \";\n }\n else if (spaceDigitChar && char.IsDigit(currentChar) && !char.IsDigit(nextChar))\n {\n result += value[i] + \" \";\n }\n else if(spaceSymbolChar && char.IsSymbol(currentChar) && !char.IsSymbol(nextChar))\n {\n result += value[i];\n }\n else\n {\n result += value[i];\n }\n }\n\n return result;\n }\n"
},
{
"answer_id": 63618605,
"author": "Adam Short",
"author_id": 9993088,
"author_profile": "https://Stackoverflow.com/users/9993088",
"pm_score": 1,
"selected": false,
"text": "private string CamelCaseToSpaces(string s)\n {\n if (string.IsNullOrEmpty(s)) return string.Empty;\n\n StringBuilder stringBuilder = new StringBuilder();\n for (int i = 0; i < s.Length; i++)\n {\n stringBuilder.Append(s[i]);\n\n int nextChar = i + 1;\n if (nextChar < s.Length && char.IsUpper(s[nextChar]) && !char.IsUpper(s[i]))\n {\n stringBuilder.Append(\" \");\n }\n }\n\n return stringBuilder.ToString();\n }\n"
},
{
"answer_id": 69785447,
"author": "hossein sedighian",
"author_id": 10143546,
"author_profile": "https://Stackoverflow.com/users/10143546",
"pm_score": 0,
"selected": false,
"text": "string InsertSpace(string text ) {\n return string.Join(\"\" , text.Select(ch => char.IsUpper(ch) ? \" \" : \"\" + ch)) ;\n} \n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45/"
] |
272,635
|
<p>I'm doing some shennanigans with jQuery to put little plus/minus icons next to my expanders. Its similar to the windows file trees, or firebugs code expanders.</p>
<p>It works, but its not specific enough. </p>
<p>Hopefully this makes sense...</p>
<pre><code>$('div.toggle').hide();//hide all divs that are part of the expand/collapse
$('ul.product-info li a').toggle(function(event){
event.preventDefault();
$(this).next('div').slideToggle(200);//find the next div and sliiiide it
$('img.expander').attr('src','img/content/info-close.gif');//this is the part thats not specific enough!!!
},function(event) { // opposite here
event.preventDefault();
$(this).next('div').slideToggle(200);
$('img.expander').attr('src','img/content/info-open.gif');
});
<ul class="product-info">
<li>
<a class="img-link" href="#"><img class="expander" src="img/content/info-open.gif" alt="Click to exand this section" /> <span>How it compares to the other options</span>
</a>
<div class="toggle"><p>Content viewable when expanded!</p></div>
</li>
</ul>
</code></pre>
<p>There are loads of <code>$('img.expander')</code> tags on the page, but I need to be specific. I've tried the next() functionality ( like I've used to find the next div), but it says that its undefined. How can I locate my specific img.expander tag? Thanks.</p>
<p>EDIT, updated code as per Douglas' solution:</p>
<pre><code>$('div.toggle').hide();
$('ul.product-info li a').toggle(function(event){
//$('#faq-copy .answer').hide();
event.preventDefault();
$(this).next('div').slideToggle(200);
$(this).contents('img.expander').attr('src','img/content/info-close.gif');
//alert('on');
},function(event) { // same here
event.preventDefault();
$(this).next('div').slideToggle(200);
$(this).contents('img.expander').attr('src','img/content/info-open.gif');
});
</code></pre>
|
[
{
"answer_id": 272711,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 1,
"selected": false,
"text": "$(this).siblings('img.expander').attr('src','img/content/info-close.gif');\n"
},
{
"answer_id": 272720,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 2,
"selected": false,
"text": "ul.product-info.open span.toggler {\n background-image: url( \"open-toggler.png\" );\n}\nul.product-info.closed span.toggler {\n background-image: url( \"closed-toggler.png\" );\n}\n\nul.product-info.open div.toggle {\n display: block;\n}\nul.product-info.closed div.toggle {\n display: hidden;\n}\n"
},
{
"answer_id": 272721,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": true,
"text": "$(this).contents('img.expander')\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
272,638
|
<p>Below is what I'm trying to achieve. The problem is "errors" is not defined. If I remove my match logic, the errors are displayed on the web page. Is there anyway of evaluating the text the error contains?</p>
<pre><code><logic:messagesPresent>
<tr>
<td class="errorcicon"><img src="images/icon_caution.gif" width="18" height="18" alt="Caution" /></td>
<td></td>
<td colspan="4"><html:errors /></td>
</tr>
</logic:messagesPresent>
<logic:match name="errors" property="text" value="Service Start date is required" >
<% pageContext.setAttribute("NOORIGIONALSERVICEDATE", "-1");%>
</logic:match>
</code></pre>
|
[
{
"answer_id": 272711,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 1,
"selected": false,
"text": "$(this).siblings('img.expander').attr('src','img/content/info-close.gif');\n"
},
{
"answer_id": 272720,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 2,
"selected": false,
"text": "ul.product-info.open span.toggler {\n background-image: url( \"open-toggler.png\" );\n}\nul.product-info.closed span.toggler {\n background-image: url( \"closed-toggler.png\" );\n}\n\nul.product-info.open div.toggle {\n display: block;\n}\nul.product-info.closed div.toggle {\n display: hidden;\n}\n"
},
{
"answer_id": 272721,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": true,
"text": "$(this).contents('img.expander')\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,644
|
<p>I have a class called <code>Ship</code> and a class called <code>Lifeboat</code></p>
<p>Lifeboat inherits from Ship.</p>
<p>Ship contains a method called <code>Validate()</code> which is called before save and it has an abstract method called <code>FurtherValidate()</code> which it calls from Validate. The reason this is in place is so when you call validate on the base it also validates the class that is inheriting. So we have</p>
<pre><code>public class Ship
public bool Validate()
{
//validate properties only found on a ship
FurtherValidate();
}
public abstract bool FurtherValidate();
</code></pre>
<p>So <code>Lifeboat</code> has </p>
<pre><code>public override bool FurtherValidate()
{
//validate properties only found on a lifeboat
}
</code></pre>
<p>This means anyone implementing <code>Ship</code> also needs to provide their own validation for their class and it's guaranteed to be called on the save as the base ship. <code>Validate()</code> is called which in turns calls the inherited validate.</p>
<p>How can we re work this so we still force inherited classes to implement <code>FurtherValidate()</code> but <code>FurtherValidate()</code> can never be called by the programmer. Currently you can called <code>Lifeboat.FurtherValidate()</code> and I want to somehow prevent this.</p>
|
[
{
"answer_id": 272654,
"author": "alvin",
"author_id": 15121,
"author_profile": "https://Stackoverflow.com/users/15121",
"pm_score": 3,
"selected": false,
"text": "protected abstract bool FurtherValidate();\n FurtherValidate ValidateCore"
},
{
"answer_id": 272656,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "protected"
},
{
"answer_id": 272685,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 3,
"selected": false,
"text": "public class Ship\n{ \n public virtual bool Validate() \n { \n //validate properties only found on a ship\n return true;\n }\n}\npublic class Lifeboat : Ship\n{ \n public override bool Validate() \n { \n base.Validate(); \n // lifeboat specific code\n return true;\n }\n}\n"
},
{
"answer_id": 272703,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 3,
"selected": true,
"text": "FurtherValidate protected internal"
},
{
"answer_id": 272921,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 1,
"selected": false,
"text": "Ship protected IValidator FurtherValidation { private get; set; }\n\npublic bool Validate()\n{\n//validate properties only found on a ship\n\n if (FurtherValidation == null)\n throw new ValidationIsRequiredException();\n if (!FurtherValidation.IsValid(this))\n // logic for invalid state\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27412/"
] |
272,665
|
<p>First of all, some background.</p>
<p>We have an order processing system, where staff enter billing data about orders in an app that stores it in a sql server 2000 database. This database isn't the real billing system: it's just a holding location so that the records can be run into a mainframe system via a nightly batch process. </p>
<p>This batch process is a canned third party package provided by an outside vendor. Part of what it's supposed to do is provide a report for any records that were rejected. The reject report is worked manually.</p>
<p>Unfortunately, it turns out the third party software doesn't catch all the errors. We have separate processes that pull back the data from the mainframe into another table in the database and load the rejected charges into yet another table. </p>
<p>An audit process then runs to make sure everything that was originally entered by the staff can be accounted for somewhere. This audit takes the form of an sql query we run, and it looks something like this:</p>
<pre><code>SELECT *
FROM [StaffEntry] s with (nolock)
LEFT JOIN [MainFrame] m with (nolock)
ON m.ItemNumber = s.ItemNumber
AND m.Customer=s.Customer
AND m.CustomerPO = s.CustomerPO -- purchase order
AND m.CustPORev = s.CustPORev -- PO revision number
LEFT JOIN [Rejected] r with (nolock) ON r.OrderID = s.OrderID
WHERE s.EntryDate BETWEEN @StartDate AND @EndDate
AND r.OrderID IS NULL AND m.MainFrameOrderID IS NULL
</code></pre>
<p>That's heavily modified, of course, but I believe the important parts are represented. The problem is that this query is starting to take too long to run, and I'm trying to figure out how to speed it up.</p>
<p>I'm pretty sure the problem is the JOIN from the <code>StaffEntry</code> table to the <code>MainFrame</code> table. Since both hold data for every order since the beginning of time (2003 in this system), they tend to be a little large. The <code>OrderID</code> and <code>EntryDate</code> values used in the <code>StaffEntry</code> table are not preserved when imported to the mainframe, which is why that join is a little more complicated. And finally, since I'm looking for records in the <code>MainFrame</code> table that don't exist, after doing the JOIN we have that ugly <code>IS NULL</code> in the where clause.</p>
<p>The <code>StaffEntry</code> table is indexed by EntryDate (clustered) and separately on Customer/PO/rev. <code>MainFrame</code> is indexed by customer and the mainframe charge number (clustered, this is needed for other systems) and separately by customer/PO/Rev. <code>Rejected</code> is not indexed at all, but it's small and testing shows it's not the problem. </p>
<p>So, I'm wondering if there is another (hopefully faster) way I can express that relationship?</p>
|
[
{
"answer_id": 272684,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "SELECT *\nFROM [StaffEntry] s\nLEFT JOIN [MainFrame] m ON m.ItemNumber = s.ItemNumber \n AND m.Customer=s.Customer \n AND m.CustomerPO = s.CustomerPO -- purchase order\n AND m.CustPORev = s.CustPORev -- PO revision number\nLEFT JOIN [Rejected] r ON r.OrderID = s.OrderID\nWHERE s.EntryDate BETWEEN @StartDate AND @EndDate\n AND r.OrderID IS NULL AND s.OrderID IS NULL\n s.OrderID IS NULL r.OrderID = s.OrderID [Rejected] SELECT *\nFROM [StaffEntry] s\nLEFT JOIN [MainFrame] m ON m.ItemNumber = s.ItemNumber \n AND m.Customer=s.Customer \n AND m.CustomerPO = s.CustomerPO -- purchase order\n AND m.CustPORev = s.CustPORev -- PO revision number\nWHERE s.EntryDate BETWEEN @StartDate AND @EndDate\n AND s.OrderID IS NULL\n"
},
{
"answer_id": 272690,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 3,
"selected": false,
"text": "SELECT *\nFROM [StaffEntry] s (nolock)\nLEFT JOIN [MainFrame] m (nolock) ON m.ItemNumber = s.ItemNumber \n AND m.Customer=s.Customer \n AND m.CustomerPO = s.CustomerPO -- purchase order\n AND m.CustPORev = s.CustPORev -- PO revision number\nWHERE s.EntryDate BETWEEN @StartDate AND @EndDate\n AND s.OrderID IS NULL\n SELECT *\nFROM [StaffEntry] s (nolock)\nLEFT JOIN [MainFrame] m (nolock) ON m.ItemNumber = s.ItemNumber \n AND m.Customer=s.Customer \n AND m.CustomerPO = s.CustomerPO -- purchase order\n AND m.CustPORev = s.CustPORev -- PO revision number\nWHERE s.EntryDate BETWEEN @StartDate AND @EndDate\n AND s.OrderID IS NULL AND m.ItemNumber IS NULL\n"
},
{
"answer_id": 272741,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "JOIN m r m"
},
{
"answer_id": 272866,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "StaffEntry.EntryDate StaffEntry MainFrame StaffEntry Rejected"
},
{
"answer_id": 273972,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 1,
"selected": false,
"text": "SELECT ...\nFROM [Rejected] r\n RIGHT MERGE JOIN [StaffEntry] s with (nolock) ON r.OrderID = s.OrderID\n LEFT JOIN [MainFrame] m with (nolock) ON....\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
272,674
|
<p>I am looking for a data structure that operates similar to a hash table, but where the table has a size limit. When the number of items in the hash reaches the size limit, a culling function should be called to get rid of the least-retrieved key/value pairs in the table.</p>
<p>Here's some pseudocode of what I'm working on:</p>
<pre><code>class MyClass {
private Map<Integer, Integer> cache = new HashMap<Integer, Integer>();
public int myFunc(int n) {
if(cache.containsKey(n))
return cache.get(n);
int next = . . . ; //some complicated math. guaranteed next != n.
int ret = 1 + myFunc(next);
cache.put(n, ret);
return ret;
}
}
</code></pre>
<p>What happens is that there are some values of <code>n</code> for which <code>myFunc()</code> will be called lots of times, but many other values of <code>n</code> which will only be computed once. So the cache could fill up with millions of values that are never needed again. I'd like to have a way for the cache to automatically remove elements that are not frequently retrieved.</p>
<p>This feels like a problem that must be solved already, but I'm not sure what the data structure is that I would use to do it efficiently. Can anyone point me in the right direction?</p>
<hr>
<p><strong>Update</strong> I knew this had to be an already-solved problem. It's called an LRU Cache and is easy to make by extending the LinkedHashMap class. Here is the code that incorporates the solution:</p>
<pre><code>class MyClass {
private final static int SIZE_LIMIT = 1000;
private Map<Integer, Integer> cache =
new LinkedHashMap<Integer, Integer>(16, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest)
{
return size() > SIZE_LIMIT;
}
};
public int myFunc(int n) {
if(cache.containsKey(n))
return cache.get(n);
int next = . . . ; //some complicated math. guaranteed next != n.
int ret = 1 + myFunc(next);
cache.put(n, ret);
return ret;
}
}
</code></pre>
|
[
{
"answer_id": 272729,
"author": "ReneS",
"author_id": 33229,
"author_profile": "https://Stackoverflow.com/users/33229",
"pm_score": 5,
"selected": true,
"text": "LRUList Map LinkedHashMap removeEldestEntry(Map.Entry)"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
272,676
|
<p>I would like to print <em>only</em> the contents of a textarea element from a website page. In particular, I would like to ensure that nothing gets clipped by the boundary of the textarea as the contents will be quite large.</p>
<p>What is the best strategy for tackling this?</p>
|
[
{
"answer_id": 272689,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<link rel=\"stylesheet\" type=\"text/css\" href=\"print.css\" media=\"print\" />\n"
},
{
"answer_id": 273609,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 1,
"selected": false,
"text": "textarea {\n display: none;\n}\n\n*/ #divtext {\n display: block;\n}\n\ndiv, DIV {\n border-style: none !important;\n float: none !important;\n overflow: visible !important;\n display: inline !important;\n}\n\n/* disable nearly all styles -- especially the nicedit ones! */\n\n#nav-wrapper, #navigation, img, p.message, .about, label, input, button, #nav-right, #nav-left, .template, #header, .nicEdit-pane, .nicEdit-selected, .nicEdit-panelContain, .nicEdit-panel, .nicEdit-frame {\n display: none !important;\n}\n\n/*hide Nicedit buttons */\n\n.nicEdit-button-active, .nicEdit-button-hover, .nicEdit-buttonContain, .nicEdit-button, .nicEdit-buttonEnabled, .nicEdit-selectContain, .nicEdit-selectControl, .nicEdit-selectTxt {\n display: none !important;\n}\n <script type=\"text/javascript\" src=\"/media/nicEdit.js\"></script>\n<script type=\"text/javascript\">\n bkLib.onDomLoaded(function () {\n var nic = new nicEditor({\n fullPanel: true\n }).panelInstance('storyText');\n\n document.getElementById(\"storyText\").nic = nic;\n nic.addEvent('blur', function () {\n document.getElementById(\"storyText\").value = \n nic.instanceById('storyText').getContent();\n document.getElementById(\"divtext\").innerHTML = nic.instanceById('storyText').getContent();\n });\n });\n</script>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990/"
] |
272,694
|
<p>I've got a strange problem with indexing PDF files in SQL Server 2005, and hope someone can help. My database has a table called MediaFile with the following fields - MediaFileId int identity pk, FileContent image, and FileExtension varchar(5). I've got my web application storing file contents in this table with no problems, and am able to use full-text searching on doc, xls, etc with no problems - the only file extension not working is PDF. When performing full-text searches on this table for words which I know exist inside of PDF files saved in the table, these files are not returned in the search results.</p>
<p>The OS is Windows Server 2003 SP2, and I've installed <a href="http://www.adobe.com/support/downloads/detail.jsp?ftpID=2611" rel="noreferrer">Adobe iFilter 6.0</a>. Following the instructions on <a href="http://weblogs.asp.net/wallym/archive/2005/02/28/382060.aspx" rel="noreferrer">this blog entry</a>, I executed the following commands:</p>
<pre><code>exec sp_fulltext_service 'load_os_resources', 1;
exec sp_fulltext_service 'verify_signature', 0;
</code></pre>
<p>After this, I restarted the SQL Server, and verified that the iFilter for the PDF extensions is installed correctly by executing the following command:</p>
<pre><code>select document_type, path from sys.fulltext_document_types where document_type = '.pdf'
</code></pre>
<p>This returns the following information, which looks correct:</p>
<blockquote>
<p>document_type: .pdf<br/>
path: C:\Program Files\Adobe\PDF IFilter 6.0\PDFFILT.dll</p>
</blockquote>
<p>Then I (re)created the index on the MediaFile table, selecting FileContent as the column to index and the FileExtension as its type. The wizard creates the index and completes successfully. To test, I'm performing a search like this:</p>
<pre><code>SELECT MediaFileId, FileExtension FROM MediaFile WHERE CONTAINS(*, '"house"');
</code></pre>
<p>This returns DOC files which contain this term, but not any PDF files, although I know that there are definitely PDF files in the table which contain the word <em>house</em>.</p>
<p>Incidentally, I got this working once for a few minutes, where the search above returned the correct PDF files, but then it just stopped working again for no apparent reason.</p>
<p>Any ideas as to what could be stopping SQL Server 2005 from indexing PDF's, even though Adobe iFilter is installed and appears to be loaded?</p>
|
[
{
"answer_id": 282339,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "* SELECT MediaFileId, FileExtension FROM MediaFile WHERE CONTAINS(FileContent, 'house')\n Image varbinary(MAX)"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775/"
] |
272,726
|
<p>I have a Stored Procedure that is constantly failing with the error message "Timeout expired," on a specific user.</p>
<p>All other users are able to invoke the sp just fine, and even I am able to invoke the sp normally using the Query Analyzer--it finishes in just 10 seconds. However with the user in question, the logs show that the ASP always hangs for about 5 minutes and then aborts with a timeout.</p>
<p>I invoke from the ASP page like so "<code>EXEC SP_TV_GET_CLOSED_BANKS_BY_USERS '006111'</code>"</p>
<p>Anybody know how to diagnose the problem? I have already tried looking at deadlocks in the DB, but didn't find any.</p>
<p>Thanks,</p>
|
[
{
"answer_id": 275739,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 3,
"selected": false,
"text": "DECLARE @MaskedParam varchar(10)\nSELECT @MaskedParam = @SignaureParam\n\nSELECT...WHERE column = @MaskedParam\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12772/"
] |
272,730
|
<p>How do I limit a SQL Server Profiler trace to a specific database? I can't see how to filter the trace to not see events for all databases on the instance I connect to.</p>
|
[
{
"answer_id": 337122,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "SELECT * \nFROM master..sysdatabases \nWHERE name like '%your_db_name%' -- Remove this line to see all databases\nORDER BY dbid\n"
},
{
"answer_id": 31539413,
"author": "6dev6il6",
"author_id": 913342,
"author_profile": "https://Stackoverflow.com/users/913342",
"pm_score": 2,
"selected": false,
"text": "TextData DatabaseName % %MyDatabaseName% %TextDataToFilter% %% DatabaseName"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,738
|
<p>Is there any way of pulling in a CSS stylesheet into FireFox 2 or 3 that is not a static file? </p>
<p>Bellow is the code we are using to pull in a stylesheet dynamically generated by a CGI script.</p>
<pre><code><link rel="stylesheet" href="/cgi-bin/Xebra?ShowIt&s=LH4X6I2l4fSYwf4pky4k&shw=795430-0&path=customer/DEMO/demo1.css" type="text/css">
</code></pre>
<p>/cgi-bin/Xebra?ShowIt&s=LH4X6I2l4fSYwf4pky4k&shw=795430-0&path=customer/DEMO/demo1.css</p>
<p><strong>Note that the URL above that pulls in the CSS does not end with .css rather the parameters do.</strong></p>
|
[
{
"answer_id": 272755,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 4,
"selected": true,
"text": "Content-type: text/css\n"
},
{
"answer_id": 272766,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": 2,
"selected": false,
"text": "Content-Type: text/css\n"
},
{
"answer_id": 272773,
"author": "John Dunagan",
"author_id": 28939,
"author_profile": "https://Stackoverflow.com/users/28939",
"pm_score": 0,
"selected": false,
"text": "<link rel=\"stylesheet\" type=\"text/css href=\"<% =getStylesheetPath() %>\" media=\"all\">\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18149/"
] |
272,750
|
<p>I am writing an application which blocks on input from two <code>istreams</code>.</p>
<p>Reading from either <code>istream</code> is a synchronous (blocking) call, so, I decided to create two <code>Boost::thread</code>s to do the reading.</p>
<p>Either one of these threads can get to the "end" (based on some input received), and once the "end" is reached, both input streams stop receiving. Unfortunately, I cannot know which will do so.</p>
<p>Thus, I cannot <code>join()</code> on both threads, because only one thread (cannot be predetermined which one) will actually return (unblock).</p>
<p>I must somehow force the other to exit, but it is blocked waiting for input, so it cannot itself decide it is time to return (condition variables or what not).</p>
<p>Is their a way to either:</p>
<ul>
<li>Send a signal a boost::thread, or</li>
<li>Force an <code>istream</code> to "fail", or</li>
<li>Kill a Boost::thread?</li>
</ul>
<p>Note:</p>
<ul>
<li>One of the <code>istreams</code> is <code>cin</code></li>
<li>I am trying to restart the process, so I cannot close the input streams in a way that prohibits reseting them.</li>
</ul>
<p>Edit:</p>
<ul>
<li>I do know when the "end" is reached, and I do know which thread has successfully finished, and which needs to be killed. Its the killing I need to figure out (or a different strategy for reading from an istream).</li>
<li>I need both threads to exit and cleanup properly :(</li>
</ul>
<p>Thanks!</p>
|
[
{
"answer_id": 1131988,
"author": "neuro",
"author_id": 135549,
"author_profile": "https://Stackoverflow.com/users/135549",
"pm_score": 1,
"selected": false,
"text": "while(!stopped && !interrupted)\n{\n io.blockingCall(timeout);\n if(!stopped && !interrupted)\n {\n doSomething();\n }\n}\n"
},
{
"answer_id": 1248882,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 0,
"selected": false,
"text": "select() select() cin STDIN_FILENO open() ifstream select()"
},
{
"answer_id": 4363272,
"author": "Drew Dormann",
"author_id": 16287,
"author_profile": "https://Stackoverflow.com/users/16287",
"pm_score": 2,
"selected": false,
"text": "boost::thread::terminate() boost::this_thread::sleep();"
},
{
"answer_id": 8055317,
"author": "get",
"author_id": 1036228,
"author_profile": "https://Stackoverflow.com/users/1036228",
"pm_score": 2,
"selected": false,
"text": "cin>>whatever boost::thread::terminate() cin"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29701/"
] |
272,764
|
<p>I want a small (< 30MB) standalone Windows executable (a single file) that creates a window which asks the user for the location of a directory and then launches a different program in that directory. </p>
<p>This executable has to run on XP, Vista, Server 2003, and Server 2008 versions of Windows in 32-bits and 64 bits on x86-64 architecture as well as Itanium chips. </p>
<p>It would be spectacular if we only had to build it once in order to run it on all these platforms, but that is not a requirement. This is for a proprietary system, so GPL code is off-limits.</p>
<p>What is the fastest way to put this together?</p>
<p>These are some things I'm looking into, so if you have info about their viability, I'm all about it:</p>
<ul>
<li>Perl/Tk using perl2exe to get the binary.</li>
<li>Ruby with wxruby</li>
<li>Learn MFC programming and do it the right way like everybody else.</li>
</ul>
|
[
{
"answer_id": 272795,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\nwin = InputBox(\"Please type your Windows folder location.\")\nIf Right(win,1) <> \"\\\" Then\n win = win & \"\\\"\nEnd If\nWshShell.Run win & \"system32\\calc.exe\"\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8344/"
] |
272,765
|
<p>I've created a c# webservice that allows our front end support teams to view and update a few selected Active Directory values using system.directoryservices</p>
<p>Fields that I want to update are [job] title, department, telephone and employeeid.</p>
<p>I can use a service account with "delegates rights" to update [job] title, department, telephone etc. but when I try to update employeeid I get an "not authorised" error message.</p>
<p>If I use a domain admin account then the same code works fine.</p>
<p>I don't want to use a domain admin account for this webservice, so what privileges do I need?</p>
|
[
{
"answer_id": 272777,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 0,
"selected": false,
"text": "string distinguishedname = \"CN=Wicks\\, Guy,OU=Users,DC=ad,DC=com\"\nusing (DirectoryEntry myDirectoryEntry = new DirectoryEntry(string.Format(\"LDAP://{0}\", distinguishedname), null, null, AuthenticationTypes.Secure))\n{\n try\n {\n myDirectoryEntry.Username = \"serviceaccount\";\n myDirectoryEntry.Password = \"pa55word\";\n\n myDirectoryEntry.Properties[\"employeeid\"][0] = employeeID;\n myDirectoryEntry.CommitChanges();\n setresult.result = myDirectoryEntry.Properties[\"employeeid\"][0].ToString();\n }\n catch ( Exception ex )\n {\n setresult.result = ex.Message;\n }\n} // end using\n"
},
{
"answer_id": 272790,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 3,
"selected": true,
"text": "REM #\nREM # Delegate AD property set admin rights to named account\nREM # Based on: http://www.microsoft.com/technet/scriptcenter/topics/security/propset.mspx\nREM #\n\nConst TRUSTEE_ACCOUNT_SAM = \"ad\\ADStaffUpdates\"\n\nConst ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &H5\nConst ADS_RIGHT_DS_READ_PROP = &H10\nConst ADS_RIGHT_DS_WRITE_PROP = &H20\nConst ADS_FLAG_OBJECT_TYPE_PRESENT = &H1\nConst ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT = &H2\nConst ADS_ACEFLAG_INHERIT_ACE = &H2\n\nConst ADS_SCHEMA_ID_GUID_USER = \"{bf967aba-0de6-11d0-a285-00aa003049e2}\"\nConst ADS_SCHEMA_ID_GUID_PS_PERSONAL = \"{77b5b886-944a-11d1-aebd-0000f80367c1}\"\nConst ADS_SCHEMA_ID_GUID_PS_PUBLIC = \"{e48d0154-bcf8-11d1-8702-00c04fb96050}\"\n\nad_setUserDelegation \"OU=USERS, DC=AD, DC=COM\", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_USER\nad_setUserDelegation \"OU=USERS, DC=AD, DC=COM\", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_PERSONAL\nad_setUserDelegation \"OU=USERS, DC=AD, DC=COM\", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_PUBLIC\n\nFunction ad_setUserDelegation( _\n ByVal strOU _\n ,ByVal strTrusteeAccount _\n ,ByVal strSchema_GUID _\n )\n\n Set objSdUtil = GetObject( \"LDAP://\" & strOU )\n\n Set objSD = objSdUtil.Get( \"ntSecurityDescriptor\" )\n Set objDACL = objSD.DiscretionaryACL\n\n Set objAce = CreateObject( \"AccessControlEntry\" )\n\n objAce.Trustee = strTrusteeAccount\n objAce.AceFlags = ADS_ACEFLAG_INHERIT_ACE\n objAce.AceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT\n objAce.Flags = ADS_FLAG_OBJECT_TYPE_PRESENT OR ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT\n\n objAce.ObjectType = strSchema_GUID\n\n objACE.InheritedObjectType = ADS_SCHEMA_ID_GUID_USER\n objAce.AccessMask = ADS_RIGHT_DS_READ_PROP OR ADS_RIGHT_DS_WRITE_PROP\n objDacl.AddAce objAce\n\n objSD.DiscretionaryAcl = objDacl\n\n objSDUtil.Put \"ntSecurityDescriptor\", Array( objSD )\n objSDUtil.SetInfo\n\nEnd Function\n\n\nFunction ad_revokeUserDelegation( _\n ByVal strOU _\n ,ByVal strTrusteeAccount _\n )\n\n Set objSdUtil = GetObject( \"LDAP://\" & strOU )\n\n Set objSD = objSdUtil.Get( \"ntSecurityDescriptor\" )\n Set objDACL = objSD.DiscretionaryACL\n\n For Each objACE in objDACL\n If UCase(objACE.Trustee) = UCase(strTrusteeAccount) Then\n objDACL.RemoveAce objACE\n End If\n Next\n\n objSDUtil.Put \"ntSecurityDescriptor\", Array(objSD)\n objSDUtil.SetInfo\n\nEnd Function\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993/"
] |
272,783
|
<p>I have a delphi (Win32) web application that can run either as a CGI app, ISAPI or Apache DLL. I want to be able to generate a unique filename prefix (unique for all current requests at a given moment), and figure that the best way to do this would be to use processID (to handle CGI mode) as well as threadID (to handle dll mode).</p>
<p>How would I get a unique Process ID and Thread ID in Delphi?</p>
<p>Will these be unique in a Multi-Core/Multi-Processor situation (on a single webserver machine)?</p>
<p><em>Edit: please note that I was advised against this approach, and thus the accepted answer uses a different method to generate temporary filenames</em></p>
|
[
{
"answer_id": 272789,
"author": "Jamie",
"author_id": 922,
"author_profile": "https://Stackoverflow.com/users/922",
"pm_score": 2,
"selected": false,
"text": "CreateGuid\nGuidToString\n"
},
{
"answer_id": 272812,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 2,
"selected": false,
"text": "function _tempnam(const Dir: PChar, const Prefix: PChar): PChar; cdecl;\n external 'msvcrt.dll' name '_tempnam';\n"
},
{
"answer_id": 272919,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 4,
"selected": true,
"text": "function GetTemporaryFileName:string;\nvar\n Path, FileName: array[0..MAX_PATH] of Char;\nbegin\n Win32Check(GetTempPath(MAX_PATH, Path) <> 0);\n Win32Check(GetTempFileName(Path, '~EX', 0, FileName) <> 0);\n Result:=String(Filename);\nend;\n"
},
{
"answer_id": 274318,
"author": "Darian Miller",
"author_id": 35696,
"author_profile": "https://Stackoverflow.com/users/35696",
"pm_score": 2,
"selected": false,
"text": "implementation\nuses Windows;\n\nprocedure MySolution();\nvar\n myThreadID:Cardinal; \n myProcessID:Cardinal;\nbegin\n myThreadID := windows.GetCurrentThreadID;\n myProcessID := windows.GetCurrentProcessId;\nend;\n"
},
{
"answer_id": 274364,
"author": "Nick Hodges",
"author_id": 2044,
"author_profile": "https://Stackoverflow.com/users/2044",
"pm_score": 3,
"selected": false,
"text": "function CreateTempFileName(aPrefix: string): string;\nvar\n Buf: array[0..MAX_PATH] of Char;\n Temp: array[0..MAX_PATH] of Char;\nbegin\n GetTempPath(MAX_PATH, Buf);\n if GetTempFilename(Buf, PChar(aPrefix), 0, Temp) = 0 then\n begin\n raise Exception.CreateFmt(sWin32Error, [GetLastError, SysErrorMessage(GetLastError)]);\n end;\n Result := string(Temp);\nend;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11820/"
] |
272,791
|
<p>I'm not that familiar with WCF, but I thought I'll learn while trying to consume an existing service.</p>
<p>One of the REST APIs I thought of was the <a href="http://apiwiki.twitter.com/REST+API+Documentation" rel="noreferrer">Twitter API</a>. I thought of developing a WPF client that will just output to the screen the last 5 tweets by a certain Twitter user.</p>
<p>I was wondering if someone could please briefly outline the steps I need to take in Visual Studio to consume these services, using WCF (classes, wizards, proxies etc.).I already know how to just call them using a web request and parse the XML that returns - I really want to see the WCF part at work.</p>
<p>Thanks in advance to anyoine who helps further my education :)</p>
|
[
{
"answer_id": 274137,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 3,
"selected": false,
"text": "var client = new HttpClient();\nclient.DefaultHeaders.Authorization = Credential.CreateBasic(\"username\",\"password\");\nvar form = new HttpUrlEncodedForm();\nform.Add(\"status\",\"Test tweet using Microsoft.Http.HttpClient\");\nvar content = HttpContent.Create(form);\nvar resp = client.Post(\"http://www.twitter.com/statuses/update.xml\", content);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19856/"
] |
272,799
|
<p>Is there a (portable) way to rotate text in a HTML table cell by 90°?</p>
<p>(I have a table with many columns and much text for the headings, so I'd like to write it vertically to save space.)</p>
|
[
{
"answer_id": 272860,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 5,
"selected": false,
"text": "S \nO \nM \nE \n\nT \nE \nX \nT \n \"SOME TEXT\".split(\"\").join(\"\\n\")\n"
},
{
"answer_id": 2416032,
"author": "Álvaro González",
"author_id": 13508,
"author_profile": "https://Stackoverflow.com/users/13508",
"pm_score": 8,
"selected": true,
"text": ".box_rotate {\n -moz-transform: rotate(7.5deg); /* FF3.5+ */\n -o-transform: rotate(7.5deg); /* Opera 10.5 */\n -webkit-transform: rotate(7.5deg); /* Saf3.1+, Chrome */\n filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */\n -ms-filter: \"progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)\"; /* IE8 */\n } <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>\n<div class=\"box_rotate\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>\n<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div> transform .box_rotate {\n -webkit-transform: rotate(7.5deg); /* Chrome, Opera 15+, Safari 3.1+ */\n -ms-transform: rotate(7.5deg); /* IE 9 */\n transform: rotate(7.5deg); /* Firefox 16+, IE 10+, Opera */\n} <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>\n<div class=\"box_rotate\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>\n<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>"
},
{
"answer_id": 4809384,
"author": "Rob Pinion",
"author_id": 591246,
"author_profile": "https://Stackoverflow.com/users/591246",
"pm_score": 0,
"selected": false,
"text": "-moz-transform: rotate(7.5deg); /* FF3.5+ */\n-o-transform: rotate(7.5deg); /* Opera 10.5 */\n-webkit-transform: rotate(7.5deg); /* Saf3.1+, Chrome */\nfilter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); /* IE6,IE7 allows only 1, 2, 3 */\n-ms-filter: \"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)\"; /* IE8 allows only 1 2 or 3*/\n"
},
{
"answer_id": 10946566,
"author": "Cine",
"author_id": 264022,
"author_profile": "https://Stackoverflow.com/users/264022",
"pm_score": 2,
"selected": false,
"text": "public string RotateHtmltext(string innerHtml)\n{\n const string TRANSFORMTEXT = \"transform: rotate(90deg);\";\n const string EXTRASTYLECSS = \"<style type='text/css'>.r90 {\"\n + \"-webkit-\" + TRANSFORMTEXT\n + \"-moz-\" + TRANSFORMTEXT\n + \"-o-\" + TRANSFORMTEXT\n + \"-ms-\" + TRANSFORMTEXT\n + \"\" + TRANSFORMTEXT\n + \"width:1em;line-height:1ex}</style>\";\n const string WRAPPERDIV = \"<div style='display: table-cell; vertical-align: middle;'>\";\n\n var newinnerHtml = string.Join(\"</div>\"+WRAPPERDIV, Regex.Split(innerHtml, @\"<br */?>\").Reverse());\n\n newinnerHtml = Regex.Replace(newinnerHtml, @\"((?:<[^>]*>)|(?:[^<]+))\",\n match => match.Groups[1].Value.StartsWith(\"<\")\n ? match.Groups[1].Value\n : string.Join(\"\", match.Groups[1].Value.ToCharArray().Select(x=>\"<div class='r90'>\"+x+\"</div>\")),\n RegexOptions.Singleline);\n return EXTRASTYLECSS + WRAPPERDIV + newinnerHtml + \"</div>\";\n}\n <style type=\"text/css\">.r90 {\n-webkit-transform: rotate(90deg);\n-moz-transform: rotate(90deg);\n-o-transform: rotate(90deg);\n-ms-transform: rotate(90deg);\ntransform: rotate(90deg);\nwidth: 1em;\nline-height: 1ex; \n}</style>\n<div style=\"display: table-cell; vertical-align: middle;\">\n<div class=\"r90\">p</div>\n<div class=\"r90\">o</div>\n<div class=\"r90\">s</div>\n</div><div style=\"display: table-cell; vertical-align: middle;\">\n<div class=\"r90\">(</div>\n<div class=\"r90\">A</div>\n<div class=\"r90\">b</div>\n<div class=\"r90\">s</div>\n<div class=\"r90\">)</div>\n</div>\n"
},
{
"answer_id": 12969105,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 2,
"selected": false,
"text": " filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */\n -ms-filter: \"progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)\"; /* IE8 */\n Imports System.Web\nImports System.Web.Services\n\n\nPublic Class GenerateImage\n Implements System.Web.IHttpHandler\n\n\n Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest\n 'context.Response.ContentType = \"text/plain\"\n 'context.Response.Write(\"Hello World!\")\n context.Response.ContentType = \"image/png\"\n\n Dim strText As String = context.Request.QueryString(\"text\")\n Dim strRotate As String = context.Request.QueryString(\"rotate\")\n Dim strBGcolor As String = context.Request.QueryString(\"bgcolor\")\n\n Dim bRotate As Boolean = True\n\n If String.IsNullOrEmpty(strText) Then\n strText = \"No Text\"\n End If\n\n\n Try\n If Not String.IsNullOrEmpty(strRotate) Then\n bRotate = System.Convert.ToBoolean(strRotate)\n End If\n Catch ex As Exception\n\n End Try\n\n\n 'Dim img As System.Drawing.Image = GenerateImage(strText, \"Arial\", bRotate)\n 'Dim img As System.Drawing.Image = CreateBitmapImage(strText, bRotate)\n\n ' Generic error in GDI+\n 'img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)\n\n 'Dim bm As System.Drawing.Bitmap = New System.Drawing.Bitmap(img)\n 'bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)\n\n Using msTempOutputStream As New System.IO.MemoryStream\n 'Dim img As System.Drawing.Image = GenerateImage(strText, \"Arial\", bRotate)\n Using img As System.Drawing.Image = CreateBitmapImage(strText, bRotate, strBGcolor)\n img.Save(msTempOutputStream, System.Drawing.Imaging.ImageFormat.Png)\n msTempOutputStream.Flush()\n\n context.Response.Buffer = True\n context.Response.ContentType = \"image/png\"\n context.Response.BinaryWrite(msTempOutputStream.ToArray())\n End Using ' img\n\n End Using ' msTempOutputStream\n\n End Sub ' ProcessRequest\n\n\n Private Function CreateBitmapImage(strImageText As String) As System.Drawing.Image\n Return CreateBitmapImage(strImageText, True)\n End Function ' CreateBitmapImage\n\n\n Private Function CreateBitmapImage(strImageText As String, bRotate As Boolean) As System.Drawing.Image\n Return CreateBitmapImage(strImageText, bRotate, Nothing)\n End Function\n\n\n Private Function InvertMeAColour(ColourToInvert As System.Drawing.Color) As System.Drawing.Color\n Const RGBMAX As Integer = 255\n Return System.Drawing.Color.FromArgb(RGBMAX - ColourToInvert.R, RGBMAX - ColourToInvert.G, RGBMAX - ColourToInvert.B)\n End Function\n\n\n\n Private Function CreateBitmapImage(strImageText As String, bRotate As Boolean, strBackgroundColor As String) As System.Drawing.Image\n Dim bmpEndImage As System.Drawing.Bitmap = Nothing\n\n If String.IsNullOrEmpty(strBackgroundColor) Then\n strBackgroundColor = \"#E0E0E0\"\n End If\n\n Dim intWidth As Integer = 0\n Dim intHeight As Integer = 0\n\n\n Dim bgColor As System.Drawing.Color = System.Drawing.Color.LemonChiffon ' LightGray\n bgColor = System.Drawing.ColorTranslator.FromHtml(strBackgroundColor)\n\n Dim TextColor As System.Drawing.Color = System.Drawing.Color.Black\n TextColor = InvertMeAColour(bgColor)\n\n 'TextColor = Color.FromArgb(102, 102, 102)\n\n\n\n ' Create the Font object for the image text drawing.\n Using fntThisFont As New System.Drawing.Font(\"Arial\", 11, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel)\n\n ' Create a graphics object to measure the text's width and height.\n Using bmpInitialImage As New System.Drawing.Bitmap(1, 1)\n\n Using gStringMeasureGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpInitialImage)\n ' This is where the bitmap size is determined.\n intWidth = CInt(gStringMeasureGraphics.MeasureString(strImageText, fntThisFont).Width)\n intHeight = CInt(gStringMeasureGraphics.MeasureString(strImageText, fntThisFont).Height)\n\n ' Create the bmpImage again with the correct size for the text and font.\n bmpEndImage = New System.Drawing.Bitmap(bmpInitialImage, New System.Drawing.Size(intWidth, intHeight))\n\n ' Add the colors to the new bitmap.\n Using gNewGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpEndImage)\n ' Set Background color\n 'gNewGraphics.Clear(Color.White)\n gNewGraphics.Clear(bgColor)\n gNewGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias\n gNewGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias\n\n\n ''''\n\n 'gNewGraphics.TranslateTransform(bmpEndImage.Width, bmpEndImage.Height)\n 'gNewGraphics.RotateTransform(180)\n 'gNewGraphics.RotateTransform(0)\n 'gNewGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault\n\n\n gNewGraphics.DrawString(strImageText, fntThisFont, New System.Drawing.SolidBrush(TextColor), 0, 0)\n\n gNewGraphics.Flush()\n\n If bRotate Then\n 'bmpEndImage = rotateImage(bmpEndImage, 90)\n 'bmpEndImage = RotateImage(bmpEndImage, New PointF(0, 0), 90)\n 'bmpEndImage.RotateFlip(RotateFlipType.Rotate90FlipNone)\n bmpEndImage.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone)\n End If ' bRotate\n\n End Using ' gNewGraphics\n\n End Using ' gStringMeasureGraphics\n\n End Using ' bmpInitialImage\n\n End Using ' fntThisFont\n\n Return bmpEndImage\n End Function ' CreateBitmapImage\n\n\n ' http://msdn.microsoft.com/en-us/library/3zxbwxch.aspx\n ' http://msdn.microsoft.com/en-us/library/7e1w5dhw.aspx\n ' http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=286\n ' http://road-blogs.blogspot.com/2011/01/rotate-text-in-ssrs.html\n Public Shared Function GenerateImage_CrappyOldReportingServiceVariant(ByVal strText As String, ByVal strFont As String, bRotate As Boolean) As System.Drawing.Image\n Dim bgColor As System.Drawing.Color = System.Drawing.Color.LemonChiffon ' LightGray\n bgColor = System.Drawing.ColorTranslator.FromHtml(\"#E0E0E0\")\n\n\n Dim TextColor As System.Drawing.Color = System.Drawing.Color.Black\n 'TextColor = System.Drawing.Color.FromArgb(255, 0, 0, 255)\n\n If String.IsNullOrEmpty(strFont) Then\n strFont = \"Arial\"\n Else\n If strFont.Trim().Equals(String.Empty) Then\n strFont = \"Arial\"\n End If\n End If\n\n\n 'Dim fsFontStyle As System.Drawing.FontStyle = System.Drawing.FontStyle.Regular\n Dim fsFontStyle As System.Drawing.FontStyle = System.Drawing.FontStyle.Bold\n Dim fontFamily As New System.Drawing.FontFamily(strFont)\n Dim iFontSize As Integer = 8 '//Change this as needed\n\n\n ' vice-versa, because 270° turn\n 'Dim height As Double = 2.25\n Dim height As Double = 4\n Dim width As Double = 1\n\n ' width = 10\n ' height = 10\n\n Dim bmpImage As New System.Drawing.Bitmap(1, 1)\n Dim iHeight As Integer = CInt(height * 0.393700787 * bmpImage.VerticalResolution) 'y DPI\n Dim iWidth As Integer = CInt(width * 0.393700787 * bmpImage.HorizontalResolution) 'x DPI\n\n bmpImage = New System.Drawing.Bitmap(bmpImage, New System.Drawing.Size(iWidth, iHeight))\n\n\n\n '// Create the Font object for the image text drawing.\n 'Dim MyFont As New System.Drawing.Font(\"Arial\", iFontSize, fsFontStyle, System.Drawing.GraphicsUnit.Point)\n '// Create a graphics object to measure the text's width and height.\n Dim MyGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpImage)\n MyGraphics.Clear(bgColor)\n\n\n Dim stringFormat As New System.Drawing.StringFormat()\n stringFormat.FormatFlags = System.Drawing.StringFormatFlags.DirectionVertical\n 'stringFormat.FormatFlags = System.Drawing.StringFormatFlags.DirectionVertical Or System.Drawing.StringFormatFlags.DirectionRightToLeft\n Dim solidBrush As New System.Drawing.SolidBrush(TextColor)\n Dim pointF As New System.Drawing.PointF(CSng(iWidth / 2 - iFontSize / 2 - 2), 5)\n Dim font As New System.Drawing.Font(fontFamily, iFontSize, fsFontStyle, System.Drawing.GraphicsUnit.Point)\n\n\n MyGraphics.TranslateTransform(bmpImage.Width, bmpImage.Height)\n MyGraphics.RotateTransform(180)\n MyGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault\n MyGraphics.DrawString(strText, font, solidBrush, pointF, stringFormat)\n MyGraphics.ResetTransform()\n\n MyGraphics.Flush()\n\n 'If Not bRotate Then\n 'bmpImage.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone)\n 'End If\n\n Return bmpImage\n End Function ' GenerateImage\n\n\n\n ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable\n Get\n Return False\n End Get\n End Property ' IsReusable\n\n\nEnd Class\n Using msTempOutputStream As New System.IO.MemoryStream\n 'Dim img As System.Drawing.Image = GenerateImage(strText, \"Arial\", bRotate)\n Using img As System.Drawing.Image = CreateBitmapImage(strText, bRotate, strBGcolor)\n img.Save(msTempOutputStream, System.Drawing.Imaging.ImageFormat.Png)\n msTempOutputStream.Flush()\n\n context.Response.Buffer = True\n context.Response.ContentType = \"image/png\"\n context.Response.BinaryWrite(msTempOutputStream.ToArray())\n End Using ' img\n\n End Using ' msTempOutputStream\n img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)\n <img alt=\"bla\" src=\"GenerateImage.ashx?no_cache=123&text=Hello%20World&rotate=true\" />\n"
},
{
"answer_id": 24110160,
"author": "Jeff Ancel",
"author_id": 72947,
"author_profile": "https://Stackoverflow.com/users/72947",
"pm_score": 1,
"selected": false,
"text": "<div class=\"fa fa-rotate-270\">\n My Test Text\n</div>\n"
},
{
"answer_id": 24139529,
"author": "James Nicholson",
"author_id": 1356819,
"author_profile": "https://Stackoverflow.com/users/1356819",
"pm_score": 1,
"selected": false,
"text": " .vertical-text-vibes{\n\n /* this is for shity \"non IE\" browsers\n that dosn't support writing-mode */\n -webkit-transform: translate(1.1em,0) rotate(90deg);\n -moz-transform: translate(1.1em,0) rotate(90deg);\n -o-transform: translate(1.1em,0) rotate(90deg);\n transform: translate(1.1em,0) rotate(90deg);\n -webkit-transform-origin: 0 0;\n -moz-transform-origin: 0 0;\n -o-transform-origin: 0 0;\n transform-origin: 0 0; \n /* IE9+ */ ms-transform: none; \n -ms-transform-origin: none; \n /* IE8+ */ -ms-writing-mode: tb-rl; \n /* IE7 and below */ *writing-mode: tb-rl;\n\n }\n"
},
{
"answer_id": 27258573,
"author": "omardiaze",
"author_id": 2984315,
"author_profile": "https://Stackoverflow.com/users/2984315",
"pm_score": 2,
"selected": false,
"text": "<div class=\"rotate\">text</div>\n .rotate {\n display:inline-block;\n filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);\n -webkit-transform: rotate(270deg);\n -ms-transform: rotate(270deg);\n transform: rotate(270deg);\n}\n"
},
{
"answer_id": 29625740,
"author": "arkod",
"author_id": 1506301,
"author_profile": "https://Stackoverflow.com/users/1506301",
"pm_score": 1,
"selected": false,
"text": "(function () {\n\n var make_rotated_text = function (text)\n {\n var can = document.createElement ('canvas');\n can.width = 10;\n can.height = 10;\n var ctx=can.getContext (\"2d\");\n ctx.font=\"20px Verdana\";\n var m = ctx.measureText(text);\n can.width = 20;\n can.height = m.width;\n ctx.font=\"20px Verdana\";\n ctx.fillStyle = \"#000000\";\n ctx.rotate(90 * (Math.PI / 180));\n ctx.fillText (text, 0, -2);\n return can;\n };\n\n var canvas = make_rotated_text (\"Hellooooo :D\");\n var body = document.getElementsByTagName ('body')[0];\n body.appendChild (canvas);\n\n}) ();\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23813/"
] |
272,803
|
<p>I have an interesting problem and would appreciate your thoughts for the best solution.
I need to parse a set of logs. The logs are produced by a multi-threaded program and a single process cycle produces several lines of logs.</p>
<p>When parsing these logs I need to pull out specific pieces of information from each process - naturally this information is across the multiple lines (I want to compress these pieces of data into a single line). Due to the application being multi-threaded, the block of lines belonging to a process can be fragmented as other processes at written to the same log file at the same time.</p>
<p>Fortunately, each line gives a process ID so I'm able to distinguish what logs belong to what process.</p>
<p>Now, there are already several parsers which all extend the same class but were designed to read logs from a single threaded application (no fragmentation - from original system) and use a readLine() method in the super class. These parsers will keep reading lines until all regular expressions have been matched for a block of lines (i.e. lines written in a single process cycle).</p>
<p>So, what can I do with the super class so that it can manage the fragmented logs, and ensure change to the existing implemented parsers is minimal?</p>
|
[
{
"answer_id": 272972,
"author": "Skip Head",
"author_id": 23271,
"author_profile": "https://Stackoverflow.com/users/23271",
"pm_score": 0,
"selected": false,
"text": "class Parser {\n String currentLine;\n Parser() {\n //Construct parser\n }\n synchronized String readLine(String processID) {\n if (currentLine == null)\n currentLine = readLinefromLog();\n\n while (currentline != null && ! getProcessIdFromLine(currentLine).equals(processId)\n wait();\n\n String line = currentLine;\n currentLine = readLinefromLog();\n notify();\n return line;\n }\n}\n\nclass ProcessParser extends Parser implements Runnable{\n String processId;\n ProcessParser(String processId) {\n super();\n this.processId = processId;\n }\n\n void startParser() {\n new Thread(this).start();\n }\n\n public void run() {\n String line = null;\n while ((line = readLine()) != null) {\n // process log line here\n }\n }\n\n String readLine() {\n String line = super.readLine(processId);\n return line;\n } \n"
},
{
"answer_id": 273001,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 3,
"selected": true,
"text": "abstract class Parser {\n public abstract void parse( ... );\n protected String readLine() { ... }\n}\n\nclass SpecialPurposeParser extends Parser {\n public void parse( ... ) { \n // ... special stuff\n readLine();\n // ... more stuff\n }\n}\n class SingleProcessReadingDecorator extends Parser {\n private Parser parser;\n private String processId;\n public SingleProcessReadingDecorator( Parser parser, String processId ) {\n this.parser = parser;\n this.processId = processId;\n }\n\n public void parse( ... ) { parser.parse( ... ); }\n\n public String readLine() {\n String text = super.readLine();\n if( /*text is for processId */ ) { \n return text; \n }\n else {\n //keep readLine'ing until you find the next line and then return it\n return this.readLine();\n }\n }\n //old way\nParser parser = new SpecialPurposeParser();\n//changes to\nParser parser = new SingleProcessReadingDecorator( new SpecialPurposeParser(), \"process1234\" );\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35033/"
] |
272,818
|
<p>Does anyone know how I can get a list of products belonging to a specific category from within a view file in <a href="http://www.magentocommerce.com/" rel="noreferrer">Magento</a>?</p>
|
[
{
"answer_id": 295987,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 3,
"selected": false,
"text": "<?php\n$_cat = $this->getCurrentCategory();\n$_parent = $_cat->getParentCategory();\n$_categories = $_parent->getChildren();\n\n/* @var $category Mage_Catalog_Model_Category */\n$collection = Mage::getModel('catalog/category')->getCollection();\n/* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */\n$collection->addAttributeToSelect('url_key')\n ->addAttributeToSelect('name')\n ->addAttributeToSelect('is_anchor')\n ->addAttributeToFilter('is_active', 1)\n ->addIdFilter($_categories)\n ->setOrder('position', 'ASC')\n ->joinUrlRewrite()\n ->load();\n\n$productCollection = Mage::getResourceModel('catalog/product_collection');\n$layer = Mage::getSingleton('catalog/layer');\n$layer->prepareProductCollection($productCollection);\n$productCollection->addCountToCategories($collection);\n// $productCollection should be ready here ;-)\n?>\n"
},
{
"answer_id": 5536921,
"author": "Mukesh Chapagain",
"author_id": 327862,
"author_profile": "https://Stackoverflow.com/users/327862",
"pm_score": 3,
"selected": false,
"text": "// if you want to display products from current category\n$category = Mage::registry('current_category'); \n\n// if you want to display products from any specific category\n$categoryId = 10;\n$category = Mage::getModel('catalog/category')->load($categoryId);\n\n$productCollection = Mage::getResourceModel('catalog/product_collection')\n ->addCategoryFilter($category);\n\n// printing products name\nforeach ($productCollection as $product) {\n echo $product->getName(); \n echo \"<br />\";\n}\n"
},
{
"answer_id": 5566694,
"author": "mivec",
"author_id": 377395,
"author_profile": "https://Stackoverflow.com/users/377395",
"pm_score": 4,
"selected": false,
"text": "$categoryId = 123; // a category id that you can get from admin\n$category = Mage::getModel('catalog/category')->load($categoryId);\n\n$products = Mage::getModel('catalog/product')\n ->getCollection()\n ->addCategoryFilter($category)\n ->load();\n\nprint_r($products);\n"
},
{
"answer_id": 11394926,
"author": "Raheel Hasan",
"author_id": 1093486,
"author_profile": "https://Stackoverflow.com/users/1093486",
"pm_score": 2,
"selected": false,
"text": "$prod_whole = array();\nif(!empty($_menu)) //$_menu = array of Categories with some basic info\nforeach($_menu as $v)\n{\n if($v['name']=='HOME')\n continue;\n\n $cat_id = $v['id'];\n\n #/ Setup Products\n $category = Mage::getModel('catalog/category')->load($cat_id);\n\n $collection = Mage::getModel('catalog/product')->getCollection()\n ->addAttributeToSelect('*') // select all attributes\n ->addCategoryFilter($category)\n ->setPageSize(8) // limit number of results returned\n ->setCurPage(0)\n ->load()\n ;\n\n\n $prod_collection = array();\n foreach ($collection as $product)\n {\n $prod_collection_1 = array();\n\n #/ Basic Info\n $prod_collection_1['id'] = $product->getId();\n $prod_collection_1['name'] = $product->getName();\n $prod_collection_1['price'] = (float) $product->getPrice();\n //$prod_collection_1['desc'] = $product->getDescription();\n //$prod_collection_1['short'] = $product->getShortDescription();\n $prod_collection_1['type'] = $product->getTypeId();\n $prod_collection_1['status'] = $product->getStatus();\n $prod_collection_1['special_price'] = $product->getSpecialPrice();\n $prod_collection_1['direct_url'] = $product->getProductUrl();\n\n\n #/ getCategoryIds(); returns an array of category IDs associated with the product\n foreach ($product->getCategoryIds() as $category_id)\n {\n $category = Mage::getModel('catalog/category')->load($category_id);\n $prod_collection_1['parent_category'] = $category->getParentCategory()->getName();\n $prod_collection_1['category'] = $category->getName();\n //$prod_collection_1['category_idx'] = preg_replace('/[\\s\\'\\\"]/i', '_', strtolower(trim($prod_collection_1['category'])));\n $prod_collection_1['category_id'] = $category->getId();\n }\n\n #/gets the image url of the product\n $prod_collection_1['img'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();\n\n\n $prod_collection[] = $prod_collection_1;\n\n }//end foreach.....\n\n $prod_whole[$cat_id] = $prod_collection;\n\n}//end foreach categories.......\n//var_dump('<pre>', $prod_whole);\n"
},
{
"answer_id": 16413619,
"author": "Chiragit007",
"author_id": 2010505,
"author_profile": "https://Stackoverflow.com/users/2010505",
"pm_score": 2,
"selected": false,
"text": "<?php\n\n $category_id = 10; // if you know static category then enter number\n\n$catagory_model = Mage::getModel('catalog/category')->load($category_id); //where $category_id is the id of the category\n\n\n\n $collection = Mage::getResourceModel('catalog/product_collection');\n\n $collection->addCategoryFilter($catagory_model); //category filter\n\n $collection->addAttributeToFilter('status',1); //only enabled product\n\n $collection->addAttributeToSelect(array('name','url','small_image')); //add product attribute to be fetched\n\n //$collection->getSelect()->order('rand()'); //uncomment to get products in random order \n\n $collection->addStoreFilter(); \n\n if(!empty($collection))\n\n {\n\n foreach ($collection as $_product):\n\n echo $_product->getName(); //get product name \n\n endforeach;\n\n }else\n\n {\n\n echo 'No products exists';\n\n } \n\n ?>\n"
},
{
"answer_id": 17717089,
"author": "Jatin Soni",
"author_id": 2594374,
"author_profile": "https://Stackoverflow.com/users/2594374",
"pm_score": 3,
"selected": false,
"text": "<?php\n$c_id = 2;\n$category = new Mage_Catalog_Model_Category();\n$category->load($c_id);\n$collection = $category->getProductCollection();\n$collection->addAttributeToSelect('*');\nforeach ($collection as $_product) { ?>\n<a href=\"<?php echo $_product->getProductUrl(); ?>\"><?php echo $_product->getName(); ?></a>\n<?php } ?>\n"
},
{
"answer_id": 49813389,
"author": "Shorabh",
"author_id": 4070360,
"author_profile": "https://Stackoverflow.com/users/4070360",
"pm_score": 0,
"selected": false,
"text": "<?php \nset_time_limit(0);\nini_set(\"memory_limit\",-1);\nini_set('max_execution_time','1800000000');\n\nrequire_once '../app/Mage.php';\nMage::app(); \n\n$category = Mage::getModel('catalog/category');\n$tree = $category->getTreeModel();\n$tree->load();\n\n$ids = $tree->getCollection()->getAllIds();\n$fp = fopen('category-product-export.csv', 'w');\n$field = array('Product SKU','Category Name'); \nfputcsv($fp, $field);\n\n$_productCollection = Mage::getModel('catalog/product')\n ->getCollection()\n ->addAttributeToSelect('*')\n ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)\n ->load();\n\nforeach ($_productCollection as $_product){\n $cats = $_product->getCategoryIds();\n $cnt = 0;\n $catName = '';\n foreach($cats as $id) {\n $category->load($id);\n $root = 'Root Catalog';\n $isRoot = strtolower($root);\n $categoryName = strtolower($category->getName());\n if($categoryName == $isRoot){\n continue;\n }\n $categories[$id]['name'] = $category->getName();\n $categories[$id]['path'] = $category->getPath();\n\n $path = explode('/', $categories[$id]['path']);\n $len = count($path);\n $string = '';\n if($id > 2){\n foreach ($path as $k=>$pathId)\n {\n $separator = '';\n if($pathId > 2){\n $category->load($pathId);\n if($k != $len-1){ $separator = ' || ';}\n $string.= $category->getName() . $separator;\n }\n\n }\n if($cnt > 0) {\n $catName.= ','.$string;\n } else {\n $catName = $string;\n }\n\n $cnt++;\n }\n }\n //echo $catName;\n $field = array($_product->getSku(),$catName); \n fputcsv($fp, $field); \n\n} \n\n?>\n<a href=\"category-product-export.csv\">Download</a>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,821
|
<p>What is the best way to get the application name (i.e MyApplication.exe) of the executing assembly from a referenced class library in C#?</p>
<p>I need to open the application's app.config to retrieve some appSettings variables for the referenced DLL.</p>
|
[
{
"answer_id": 272833,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 6,
"selected": false,
"text": "// Full-name, e.g. MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\nstring exeAssembly = Assembly.GetEntryAssembly().FullName;\n\n// or just the \"assembly name\" part (e.g. \"MyApplication\")\nstring exeAssemblyName = Assembly.GetEntryAssembly().GetName().Name;\n ConfigurationManager"
},
{
"answer_id": 272848,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 5,
"selected": true,
"text": "ConfigurationManager.AppSettings Assembly.GetExecutingAssembly().FullName ConfigurationManager"
},
{
"answer_id": 563382,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "ConfigurationManager.AppSettings NameValueCollection NameValueCollection //Library\npublic class MyComponent\n{\n //Constructor\n public MyComponent(NameValueCollection settings)\n {\n //do something with your settings now, like assign to a local collection\n }\n}\n\n//Consumer\nclass Program\n{\n static void Main(string[] args)\n {\n MyComponent component = new MyComponent(ConfigurationManager.AppSettings);\n }\n}\n"
},
{
"answer_id": 1127181,
"author": "Aoi Karasu",
"author_id": 138255,
"author_profile": "https://Stackoverflow.com/users/138255",
"pm_score": 3,
"selected": false,
"text": "string appName = Assembly.GetEntryAssembly().GetName().Name;\n"
},
{
"answer_id": 8832995,
"author": "A Reynaldos",
"author_id": 1145178,
"author_profile": "https://Stackoverflow.com/users/1145178",
"pm_score": 2,
"selected": false,
"text": " Assembly ass = System.Reflection.Assembly.GetExecutingAssembly();\n AssemblyName assname = ass.GetName();\n\n Version ver=assname.Version;\n this.Text = \"Your title Version \" + ver;\n"
},
{
"answer_id": 10524356,
"author": "Jaider",
"author_id": 480700,
"author_profile": "https://Stackoverflow.com/users/480700",
"pm_score": 3,
"selected": false,
"text": "typeof(MyClass).Assembly\n"
},
{
"answer_id": 29541533,
"author": "James Harcourt",
"author_id": 1461680,
"author_profile": "https://Stackoverflow.com/users/1461680",
"pm_score": 3,
"selected": false,
"text": "Assembly.GetEntryAssembly().GetName().Name\n"
},
{
"answer_id": 38708465,
"author": "Gerardo Aguero",
"author_id": 6665137,
"author_profile": "https://Stackoverflow.com/users/6665137",
"pm_score": 1,
"selected": false,
"text": "Me.GetType ().Assembly.GetName().Name\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
272,826
|
<p>I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP.</p>
<p>I've tried the following functions:</p>
<ul>
<li>system</li>
<li>passthru</li>
<li>exec</li>
<li>shell_exec</li>
</ul>
<p>example:</p>
<pre><code>system('mysql -u root -pxxxx db_name');
</code></pre>
<p>But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas?</p>
|
[
{
"answer_id": 272845,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 0,
"selected": false,
"text": "system('mysql -u root -pxxxx db_name < script.mysql');\n"
},
{
"answer_id": 272894,
"author": "TJ L",
"author_id": 12605,
"author_profile": "https://Stackoverflow.com/users/12605",
"pm_score": 0,
"selected": false,
"text": "-e $sql = \".....\";\nsystem(\"mysql -u root -pxxxx db_name -e \\\"$sql\\\"\");\n"
},
{
"answer_id": 273992,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 3,
"selected": true,
"text": "system(\"mysql -uroot -p db_name > `tty`\");\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261/"
] |
272,868
|
<p>I thought that it would be fun to present some classic CS problems and let people show their algorithm optimization skills. The hope is that we get to see some clever techniques to solve abstract problems that we may be able to implement in practice.</p>
<p>Ideally solutions would be presented in pseudo code with a big O classification. Proof of that classification is gravy. On to the problem:</p>
<p>There are N closed lockers and N students present. The first student opens each locker. The second student opens or closes every second locker. This continues where the nth student opens and closes every nth locker. After N students what lockers are open? How many lockers are open?</p>
|
[
{
"answer_id": 272934,
"author": "Erick",
"author_id": 12251,
"author_profile": "https://Stackoverflow.com/users/12251",
"pm_score": 0,
"selected": false,
"text": "delta=1\n\nfor(index=1;index < N;index+=delta) {\n print open locker = index;\n delta+=2;\n opencount++;\n};\n"
},
{
"answer_id": 1251643,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "use strict;\nuse warnings;\nuse 5.010;\n\nsub lockers{\n my($number_of_lockers) = @_;\n\n my $largest_sqrt = sqrt $number_of_lockers;\n\n my @list;\n\n for( my $index = 1; $index <= $largest_sqrt; ++$index ){\n push @list, $index**2;\n }\n\n return @list;\n}\n\nsay for lockers 100;\n use strict;\nuse warnings;\nuse 5.010;\n\nsub lockers{\n my($number_of_lockers) = @_;\n\n my @list;\n\n for(\n my($index,$sqr) = (1,1);\n $sqr <= $number_of_lockers;\n $sqr = (++$index)**2\n ){\n push @list, $sqr;\n }\n\n return @list;\n}\n\nsay for lockers 100;\n"
},
{
"answer_id": 2152113,
"author": "mike",
"author_id": 260615,
"author_profile": "https://Stackoverflow.com/users/260615",
"pm_score": 0,
"selected": false,
"text": "for(int i = 0; i < SIZE / 2; i++){\n for(int k = i; k < SIZE; k = k+i+1){\n if(lockers[k] == false)\n lockers[k] = true;\n else\n lockers[k] = false;\n }\n}\n"
},
{
"answer_id": 22377153,
"author": "kamalpluto",
"author_id": 3379238,
"author_profile": "https://Stackoverflow.com/users/3379238",
"pm_score": -1,
"selected": false,
"text": " int l, s;\n Scanner in = new Scanner(System.in);\n System.out.println(\"Enter the number of lockers\");\n l = in .nextInt();\n System.out.println(\"Enter the number of students\");\n s = in .nextInt();\n if (l\n\n boolean lockers[] = new boolean[l + 1]; \n boolean students[] = new boolean[s + 1]; lockers[0] = true; students[0] = true;\n for (int i = 1; i <= l; i++) {\nlockers[i] = false;\n }\n\n for (int j = 1; j <= s; j++) {\nfor (int h = 1; h <= l; h++) {\n if (h % j == 0) {\n if (lockers[h] == true) lockers[h] = false;\n else lockers[h] = true;\n }\n\n}\n }\n System.out.println(\"the lockers which are open are \");\n for (int k = 1; k <= l; k++) {\n if (lockers[k] == true) {\n System.out.print(\" \" + k);\n }\n }\n"
},
{
"answer_id": 28383458,
"author": "moazzam ali",
"author_id": 4254928,
"author_profile": "https://Stackoverflow.com/users/4254928",
"pm_score": 0,
"selected": false,
"text": " public class CH3 {\n for(int i=0;i<100;i++){\n lockers[i]=true;\n }\n\n for(int s=2;s<100;s++){\n for(int y=s; y<100;y=y+s){\n if(lockers[y]==true){\n lockers[y]=false;\n }\n else{\n lockers[y]=true;\n }\n }\n }\nSystem.out.println(\"open lockers are:\");\nfor(int i=0;i<100;i++){\nif(lockers[i]==true){\n\n\nSystem.out.print(i+\" \");\n}\n} \n"
},
{
"answer_id": 41853120,
"author": "Darren McGuirk",
"author_id": 7469265,
"author_profile": "https://Stackoverflow.com/users/7469265",
"pm_score": 2,
"selected": false,
"text": "for (int locker = 1; locker <= lockerTotal; locker++ ){ // locker loop\n cout << \"\\n\\n\\nLocker no.\" << locker << endl;\n cout << \" is visited by student(s) \";\n visit = 0;\n for (int student = 1 ; student <= studentTotal; student++) { // student loop\n\n if( locker % student == 0) {\n cout << student << \", \";\n visit++;}\n\n }//end of locker loop\n\n cout << \"\\nTotal number of visits: \" << visit;\n if (visit % 2 == 0){\n cout << \" the locker will stay closed.\";\n totalClosed++;}\n else { cout << \" the locker will be opened.\";\n totalOpened++;}\n\n} //end of student loop\n\nif (lockerTotal == totalOpened + totalClosed) {\n cout << \"\\n\\n\\nOf total lockers (\" << lockerTotal << \"), \" << totalOpened << \" will be left open.\" << \"(\" << totalClosed << \") \" << \"will be closed.\" << endl;\n }else cout << \"Error!!\";\n\n\n\nreturn 0;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12251/"
] |
272,876
|
<blockquote>
<p>char *strtok(char *s1, const char *s2)</p>
<p>repeated calls to this function break string s1 into "tokens"--that is
the string is broken into substrings,
each terminating with a '\0', where
the '\0' replaces any characters
contained in string s2. The first call
uses the string to be tokenized as s1;
subsequent calls use NULL as the first
argument. A pointer to the beginning
of the current token is returned; NULL
is returned if there are no more
tokens.</p>
</blockquote>
<p>Hi, </p>
<p>I have been trying to use <code>strtok</code> just now and found out that if I pass in a <code>char*</code> into <code>s1</code>, I get a segmentation fault. If I pass in a <code>char[]</code>, <code>strtok</code> works fine. </p>
<p>Why is this?</p>
<p>I googled around and the reason seems to be something about how <code>char*</code> is read only and <code>char[]</code> is writeable. A more thorough explanation would be much appreciated.</p>
|
[
{
"answer_id": 272904,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 5,
"selected": true,
"text": "char * char *text = \"foobar\";\n char text[7] = \"foobar\";\n strtok null strtok"
},
{
"answer_id": 273347,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "char *s = \"abc\";\n const char *cs = \"abc\";\nchar *s = cs;\n"
},
{
"answer_id": 275077,
"author": "Jason L",
"author_id": 35616,
"author_profile": "https://Stackoverflow.com/users/35616",
"pm_score": 3,
"selected": false,
"text": "int x = 0; x x int 0 x x x = 15; char *name = \"Tom\"; name char NULL \"Tom\" char char * const char * char *"
},
{
"answer_id": 571863,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "char *s = \"HAPPY DAY\";\nprintf(\"\\n %s \", s);\n\ns = \"NEW YEAR\"; /* Valid */\nprintf(\"\\n %s \", s);\n\ns[0] = 'c'; /* Invalid */\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14520/"
] |
272,900
|
<p>Can anyone explain why following code won't compile? At least on g++ 4.2.4.</p>
<p>And more interesting, why it will compile when I cast MEMBER to int?</p>
<pre><code>#include <vector>
class Foo {
public:
static const int MEMBER = 1;
};
int main(){
vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
</code></pre>
|
[
{
"answer_id": 272965,
"author": "Drew Hall",
"author_id": 23934,
"author_profile": "https://Stackoverflow.com/users/23934",
"pm_score": 9,
"selected": true,
"text": "class Foo { /* ... */ };\n\nconst int Foo::MEMBER;\n\nint main() { /* ... */ }\n"
},
{
"answer_id": 272982,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 6,
"selected": false,
"text": "push_back void push_back(const T&)\n T #include <vector>\n\nclass Foo {\npublic:\n static const int MEMBER;\n};\n\nconst int Foo::MEMBER = 1; \n\nint main(){\n std::vector<int> v;\n v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'\n v.push_back( (int) Foo::MEMBER ); // OK \n return 0;\n}\n Foo::MEMBER #define MEMBER 1\n"
},
{
"answer_id": 272996,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 6,
"selected": false,
"text": "push_back unary + v.push_back( +Foo::MEMBER );\n"
},
{
"answer_id": 13698802,
"author": "iso9660",
"author_id": 1184922,
"author_profile": "https://Stackoverflow.com/users/1184922",
"pm_score": 3,
"selected": false,
"text": "class Aaa {\n\nprotected:\n\n static Aaa *defaultAaa;\n\n};\n // You must define an actual variable in your program for the static members of the classes\n\nstatic Aaa *Aaa::defaultAaa;\n"
},
{
"answer_id": 37916521,
"author": "starturtle",
"author_id": 1864036,
"author_profile": "https://Stackoverflow.com/users/1864036",
"pm_score": 1,
"selected": false,
"text": "class Foo {\npublic: \n static constexpr int MEMBER = 1; \n};\n constexpr"
},
{
"answer_id": 66569786,
"author": "Quimby",
"author_id": 7691729,
"author_profile": "https://Stackoverflow.com/users/7691729",
"pm_score": 3,
"selected": false,
"text": "inline struct Foo{\n inline static int member;\n};\n member"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35281/"
] |
272,908
|
<p>I'm trying to install RSpec as a gem after having it installed as a plugin. I've gone ahead and followed the directions found here <a href="http://github.com/dchelimsky/rspec-rails/wikis" rel="noreferrer">http://github.com/dchelimsky/rspec-rails/wikis</a> for the section titled <strong>rspec and rspec-rails gems</strong>. When I run <code>ruby script/generate rspec</code>, I get the error <code>Couldn't find 'rspec' generator</code>. Do only the plugins work? If so, why do they even offer the gems for rspec and rspec-rails? I'm running a frozen copy of Rails 2.1.2, and the version of rpsec and rspec-rails I'm using is the newest for today (Nov 7, 2008) 1.1.11.</p>
<p>EDIT Nov 12, 2008
I have both the rspec and rspec-rails gems installed. I've unpacked the gems into the vender/gems folder. Both are version 1.1.11.</p>
|
[
{
"answer_id": 273526,
"author": "Micah",
"author_id": 19964,
"author_profile": "https://Stackoverflow.com/users/19964",
"pm_score": 1,
"selected": false,
"text": "script/generate rspec_model mymodel\nscript/generate rspec_controller mycontroller\n"
},
{
"answer_id": 273936,
"author": "Raimonds Simanovskis",
"author_id": 16829,
"author_profile": "https://Stackoverflow.com/users/16829",
"pm_score": 3,
"selected": false,
"text": "script/generate rspec\n"
},
{
"answer_id": 405143,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 1,
"selected": false,
"text": "git submodule add git://github.com/dchelimsky/rspec.git vendor/plugins/rspec\ngit submodule add git://github.com/dchelimsky/rspec-rails.git vendor/plugins/rspec_on_rails\n"
},
{
"answer_id": 902009,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$ sudo gem install rspec\n\n$ sudo gem install rspec-rails \n $ ruby script/generate rspec\n"
},
{
"answer_id": 2445165,
"author": "makuchaku",
"author_id": 184078,
"author_profile": "https://Stackoverflow.com/users/184078",
"pm_score": -1,
"selected": false,
"text": "sudo gem install cucumber-rails\n"
},
{
"answer_id": 4767258,
"author": "Overbryd",
"author_id": 128351,
"author_profile": "https://Stackoverflow.com/users/128351",
"pm_score": 0,
"selected": false,
"text": "$ gem update bundler $ rails g source 'http://rubygems.org'\n\ngem 'rails', '3.0.3'\ngem 'sqlite3-ruby', :require => 'sqlite3'\n\ngroup :test, :development do\n gem 'capybara', '0.4.1.1'\n gem 'database_cleaner'\n gem 'cucumber-rails'\n gem 'rspec-rails', '~> 2.4'\n gem 'launchy'\nend\n :development"
},
{
"answer_id": 6189374,
"author": "Peter Nixey",
"author_id": 400790,
"author_profile": "https://Stackoverflow.com/users/400790",
"pm_score": 3,
"selected": false,
"text": " rails generate rspec_model mymodel\n $rails generate model mymodel\n invoke active_record\n create db/migrate/20110531144454_create_mymodels.rb\n create app/models/mymodel.rb\n invoke rspec\n create spec/models/mymodel_spec.rb\n"
},
{
"answer_id": 10449182,
"author": "Trip",
"author_id": 93311,
"author_profile": "https://Stackoverflow.com/users/93311",
"pm_score": -1,
"selected": false,
"text": "bundle exec rails g rspec:install\n"
},
{
"answer_id": 13426843,
"author": "Dan K.K.",
"author_id": 1040889,
"author_profile": "https://Stackoverflow.com/users/1040889",
"pm_score": 0,
"selected": false,
"text": "script/rails generate rspec:install Test::Unit"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35564/"
] |
272,910
|
<p>When does java let go of a connections to a URL? I don't see a close() method on either URL or URLConnection so does it free up the connection as soon as the request finishes? I'm mainly asking to see if I need to do any clean up in an exception handler.</p>
<pre><code>try {
URL url = new URL("http://foo.bar");
URLConnection conn = url.openConnection();
// use the connection
}
catch (Exception e) {
// any clean up here?
}
</code></pre>
|
[
{
"answer_id": 70305155,
"author": "Artem Mostyaev",
"author_id": 1219012,
"author_profile": "https://Stackoverflow.com/users/1219012",
"pm_score": 0,
"selected": false,
"text": "adb shell ps\n adb shell run-as YOUR_PACKAGE_NAME ls -l /proc/YOUR_PID/fd\n close"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14481/"
] |
272,927
|
<p>I have a pseudo-realtime data processing application where I would like to use <code>LazyInit<double></code> so I don't do calculations I don't need, but <code>LazyInit<T></code> restricts T to classes. I can work around it, but I'd obviously prefer not to.</p>
<p>Does anybody know why this is?</p>
|
[
{
"answer_id": 272937,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 0,
"selected": false,
"text": "LazyInit<double?>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797/"
] |
272,928
|
<p>I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.</p>
<p>How and where shoud I be doing this? Should I be doing it before Page_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?</p>
<pre><code> namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
</code></pre>
|
[
{
"answer_id": 272992,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 0,
"selected": false,
"text": "<asp:Button id=\"btnCommand\" runat=\"server\" onClick=\"b_Command\" text=\"Submit\" />\n"
},
{
"answer_id": 273093,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 0,
"selected": false,
"text": "EnableViewState = false protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n // Execute heavy search 1 to generate buttons\n ButtonTexts = new ButtonState[] { \n new ButtonState() { ID = \"Btn1\", Text = \"Selection 1\" } \n };\n }\n AddButtons();\n }\n\n void b_Command(object sender, CommandEventArgs e)\n {\n TextBox1.Text = ((Button)sender).Text;\n\n // Execute heavy search 2 to generate new buttons\n ButtonTexts = new ButtonState[] { \n new ButtonState() { ID = \"Btn1\", Text = \"Selection 1\" }, \n new ButtonState() { ID = \"Btn2\", Text = \"Selection 2\" } \n };\n AddButtons();\n }\n\n private void AddButtons()\n {\n Panel1.Controls.Clear();\n foreach (ButtonState buttonState in this.ButtonTexts)\n {\n Button b = new Button();\n b.EnableViewState = false;\n b.ID = buttonState.ID;\n b.Text = buttonState.Text;\n b.Command += new CommandEventHandler(b_Command);\n Panel1.Controls.Add(b);\n }\n }\n\n private ButtonState[] ButtonTexts\n {\n get\n {\n ButtonState[] list = ViewState[\"ButtonTexts\"] as ButtonState[];\n if (list == null)\n ButtonTexts = new ButtonState[0];\n return list;\n }\n set { ViewState[\"ButtonTexts\"] = value; }\n }\n\n [Serializable]\n class ButtonState\n {\n public string ID { get; set; }\n public string Text { get; set; }\n }\n"
},
{
"answer_id": 276224,
"author": "JohnIdol",
"author_id": 1311500,
"author_profile": "https://Stackoverflow.com/users/1311500",
"pm_score": 4,
"selected": true,
"text": "namespace CloudNavigation\n{\n public partial class Test : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n if (IsPostBack)\n {\n this.recreateButtons();\n }\n else\n {\n // Execute heavy search 1 to generate buttons\n Button b = new Button();\n b.Text = \"Selection 1\";\n b.Command += new CommandEventHandler(b_Command);\n Panel1.Controls.Add(b);\n //store this stuff in ViewState for the very first time\n }\n }\n\n void b_Command(object sender, CommandEventArgs e)\n {\n //Execute heavy search 2 to generate new buttons\n //TODO: store data into ViewState or Session\n //and maybe create some new buttons\n }\n\n void recreateButtons()\n {\n //retrieve data from ViewState or Session and create all the buttons\n //wiring them up to eventHandler\n }\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] |
272,941
|
<p>I've done development in both VB6 and VB.NET, and I've used ADODB objects in VB6 to handle recordset navigation (i.e. the MoveFirst, MoveNext, etc. methods), and I have used ADO.NET to handle queries in a row-by-row nature (i.e For Each Row In Table.Rows ...)</p>
<p>But now I seem to have come to a dilemma. I am now building a program in VB.NET where I need to use the equivalent functionality of the Move commands of the old Recordset object. Does VB.NET have some sort of object that supports this functionality, or do I have to resort to using the old ADODB COM object?</p>
<p>Edit: Just for clarification, I want the user to be able to navigate through the query moving forwards or backwards. Looping through the rows is a simple task.</p>
|
[
{
"answer_id": 272968,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 3,
"selected": true,
"text": "Dim ds as DataSet\n\n'populate your DataSet'\n\nFor each dr as DataRow in ds.Tables(<tableIndex>).Rows\n 'Do something with the row'\n\nNext\n"
},
{
"answer_id": 272999,
"author": "steve",
"author_id": 32103,
"author_profile": "https://Stackoverflow.com/users/32103",
"pm_score": 0,
"selected": false,
"text": " Dim cmd As New OleDb.OleDbCommand(sql, Conn) 'You can also use command parameter here\n Dim dr As OleDb.OleDbDataReader\n dr = cmd.ExecuteReader\n\n While dr.Read\n\n ‘Do something with data\n ‘ access fields\n dr(\"fieldname\")\n ‘Check for null\n IsDBNull(dr(\"fieldname\"))\n\n End While\n\n dr.Close()\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29115/"
] |
272,964
|
<p>If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never answer.)</p>
<p>Elementary example:</p>
<pre><code>ReturnValue MyClass::FunctionThatAltersMembersAndNeverFails()
{
//Do stuff to members of MyClass that never fails
return successfulResultObject;
}
void MyClass::DoWork()
{
// Do some stuff
FunctionThatAltersMembersAndNeverFails();
// Do more stuff
}
</code></pre>
<p>In this case, will the <code>ReturnValue</code> object get copied at all? Does it even get constructed? (I know it probably depends on the compiler, but let's narrow this discussion down to the popular modern ones.)</p>
<p>EDIT: Let's simplify this a bit, since there doesn't seem to be a consensus in the general case. What if <code>ReturnValue</code> is an int, and we return 0 instead of <code>successfulResultObject</code>?</p>
|
[
{
"answer_id": 64436238,
"author": "Gukki5",
"author_id": 5689597,
"author_profile": "https://Stackoverflow.com/users/5689597",
"pm_score": 0,
"selected": false,
"text": "mov"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22724/"
] |
272,970
|
<p>It seems that all of the documentation I can find about OpenGL-ES says something to the effect of "OpenGL-ES is just like OpenGL, but without a lot of stuff. For example, there's no glBegin or glEnd."</p>
<p>Ok, that's great. So, what ELSE isn't there any of? Or is there a list of what's <em>in</em>? Or maybe a porting guide?</p>
<p>(Specifically, I'm trying to move an existing GL app to the iPhone, although I don't want to necessarily limit my Q to the iPhone.)</p>
|
[
{
"answer_id": 421839,
"author": "Patrick Hogan",
"author_id": 4065,
"author_profile": "https://Stackoverflow.com/users/4065",
"pm_score": 4,
"selected": false,
"text": "/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/\nSystem/Library/Frameworks/OpenGLES.framework/Headers/ES1/gl.h /Developer/SDKs/MacOSX10.5.sdk/\nSystem/Library/Frameworks/OpenGL.framework/Versions/A/Headers/gl.h void gluPerspective( GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar )\n{\n GLfloat xmin, xmax, ymin, ymax;\n\n ymax = zNear * tan(fovy * M_PI / 360.0);\n ymin = -ymax;\n xmin = ymin * aspect;\n xmax = ymax * aspect;\n\n glFrustumf( xmin, xmax, ymin, ymax, zNear, zFar );\n}\n void draw( short x, short y, short w, short h )\n{\n const GLshort t[8] = { 0, 0, 1, 0, 1, 1, 0, 1 };\n const GLshort v[8] = { x, y, x+w, y, x+w, y+h, x, y+h };\n\n glVertexPointer( 2, GL_SHORT, 0, v );\n glEnableClientState( GL_VERTEX_ARRAY );\n\n glTexCoordPointer( 2, GL_SHORT, 0, t );\n glEnableClientState( GL_TEXTURE_COORD_ARRAY );\n\n glDrawArrays( GL_TRIANGLE_FAN, 0, 4 );\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34820/"
] |
272,973
|
<p>I have a single form for editing an event, in which the user can (a) edit the details of the event (title, description, dates, etc.) in a FormView and (b) view and edit a ListView of contacts who are registered for the event. </p>
<p>Here's my LinqDataSource, which allows me to add and remove contacts to the event. </p>
<pre><code><asp:linqdatasource runat="server" id="ContactsDatasource" contexttypename="Db" tablename="ContactsCalendarEventsXtabs" autogeneratewhereclause="true" enabledelete="true" enableinsert="true">
<whereparameters>
<asp:querystringparameter name="CalendarEventID" querystringfield="id" type="Int32" />
</whereparameters>
<insertparameters>
<asp:querystringparameter name="CalendarEventID" querystringfield="id" type="Int32" />
</insertparameters>
</asp:linqdatasource>
</code></pre>
<p>This works fine, but of course it persists the changes to the database as they're made; and it only works when the event has already been created. Ideally, I'd like for my changes to the ListView to be persisted only once the FormView saves (so if someone makes some changes to the ListView and then cancels out of the FormView, the changes are discarded). Along the same lines, I'd like to be able to create a new event, enter its details, and sign some people up for it, all at once; when the FormView saves, it gets the new ID for the event, and then the ListView saves using that ID.</p>
<p>In the past (pre-Linq) I've accomplished this with my own extensively customized FormView and SqlDataSource objects, which take care of temporarily persisting the data changes, getting the event ID from the FormView, etc. Is there a more standard way of dealing with this scenario using the LinqDataSource? </p>
|
[
{
"answer_id": 276419,
"author": "Alexander Taran",
"author_id": 35954,
"author_profile": "https://Stackoverflow.com/users/35954",
"pm_score": 0,
"selected": false,
"text": "create all list items programmaticaly.\ncreate event proggramaticaly.\nevent myevent = new event();\nevent.someprop = zzxxx;\n\nlink them programmaticaly.\nthen use yourdatacontext.events.InsertOnSubmit(event);\n"
},
{
"answer_id": 555535,
"author": "Liam",
"author_id": 28594,
"author_profile": "https://Stackoverflow.com/users/28594",
"pm_score": 1,
"selected": false,
"text": "<FormView>...</FormView>\n<ListView>...</ListView>\n<LinqDataSource ID=\"dsEvent\" ...> </LinqDataSource>\n<LinqDataSource ID=\"dsContact\" ...> </LinqDataSource>\n<asp:Button ID=\"btnSubmit\" runat=\"server\" OnClick=\"btnSubmit_Click\" Text=\"Submit it All!\"/>\n protected void btnSubmit_Click(object sender, EventArgs e)\n{\n Event evt = null;\n Contact contact = null;\n\n dsEvent.Inserting += (o,ea) => { evt = (ea.NewObject as Event); ea.Cancel = true; };\n dsEvent.InsertItem(true);\n dsContact.Inserting += (o, ea) => { contact = (ea.NewObject as Contact); ea.Cancel = true; };\n dsContact.InsertItem(true);\n\n evt.Contacts.Add(contact);\n\n using (var dbContext = new ContactsCalendarEventsXtabs())\n {\n dbContext.Events.InsertOnSubmit(evt);\n dbContext.SubmitChanges();\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
272,987
|
<p>We have a pretty mature COM dll, which we test using DUnit. One of our recent tests creates a few threads, and tests the object from those threads. This test works fine when running the test using the gui front-end, but hangs when running as a console application. Here's a quick pseudo view of what we have in the test</p>
<pre><code>SetupTest;
fThreadRefCount := 0; //number of active threads
Thread1 := TMyThread.Create(True);
Inc(fThreadRefCount);
Thread1.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount
Thread3 := TMyThread.Create(True);
Inc(fThreadRefCount);
Thread2.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount
Thread3 := TMyThread.Create(True);
Inc(fThreadRefCount);
Thread3.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount
Thread1.Resume;
Thread2.Resume;
Thread3.Resume;
while fThreadRefCount > 0 do
Application.ProcessMessages;
</code></pre>
<p>I have tried doing nothing in the OnExecute, so I'm sure it's not the actual code I'm testing. In the console, fThreadRefCount never decrements, while if I run it as a gui app, it's fine!</p>
<p>As far as I can see, the OnTerminate event is just not called.</p>
|
[
{
"answer_id": 273236,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 4,
"selected": true,
"text": "OnTerminate Synchronize() CheckSynchronize() Application.ProcessMessages() Synchronize() uses Windows, SysUtils, Classes, Forms;\n\nvar\n threadCount: Integer;\n\ntype\n TMyThread = class(TThread)\n public\n procedure Execute; override;\n class procedure Go;\n class procedure HandleOnTerminate(Sender: TObject);\n end;\n \nprocedure TMyThread.Execute;\nbegin\nend;\n\nclass procedure TMyThread.Go;\n function MakeThread: TThread;\n begin\n Result := TMyThread.Create(True);\n Inc(threadCount);\n Result.OnTerminate := HandleOnTerminate;\n end;\nvar\n t1, t2, t3: TThread;\nbegin\n t1 := MakeThread;\n t2 := MakeThread;\n t3 := MakeThread;\n t1.Resume;\n t2.Resume;\n t3.Resume;\n while threadCount > 0 do\n Application.ProcessMessages;\nend;\n\nclass procedure TMyThread.HandleOnTerminate(Sender: TObject);\nbegin\n InterlockedDecrement(threadCount);\nend;\n\nbegin\n try\n TMyThread.Go;\n except\n on e: Exception do\n Writeln(e.Message);\n end;\nend.\n"
},
{
"answer_id": 275993,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 3,
"selected": false,
"text": "CheckSyncronize() Synchronize() Synchronize() OnTerminate Application.ProcessMessage() Application.ProcessMessages() CheckSynchronize() While fThreadRefCount > 0 do\nbegin\n Application.ProcessMessages;\n CheckSynchronize;\nend;\n WakeupMainThread WM_NULL CheckSynchronize() Synchronize() DoTerminate() Synchronize(CallOnTerminate) WaitForSingleObject(SyncProcPtr.Signal, Infinite); \n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22712/"
] |
272,993
|
<p>I have a rails template (.rhtml file) generating a Javascript object. It looks something like the following:</p>
<pre><code>var volumes = {
<% for volume in @volumes %>
<%= volume.id %> : <%= volume.data %>
<%= ',' unless volume === @volumes.last %>
<% end %>
};
</code></pre>
<p>Note the <code>unless</code> statement modifier to suppress printing the comma after the last element (to satisfy Internet Explorer, which incredibly doesn't support trailing commas in JSON properties declarations).</p>
<p>This appears to work, but as a matter of style, do people think it is reasonable to rely on <code><%= value unless condition %></code> in the template generating an appropriate <code>render</code> call?</p>
|
[
{
"answer_id": 273010,
"author": "Jim Puls",
"author_id": 6010,
"author_profile": "https://Stackoverflow.com/users/6010",
"pm_score": 4,
"selected": true,
"text": "join <%= @volumes.map {|v| \"#{v.id} : #{v.data}\"}.join \",\" %>\n"
},
{
"answer_id": 273472,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "<%= @volumes.map { |v| \"#{v.id} : #{v.data}\"}.to_sentence -%>\n"
},
{
"answer_id": 273892,
"author": "Raimonds Simanovskis",
"author_id": 16829,
"author_profile": "https://Stackoverflow.com/users/16829",
"pm_score": 2,
"selected": false,
"text": "var volumes = <%= @volumes.inject({}){|h,v| h.merge(v.id=>v.data)}.to_json %>;\n var volumes = <%= Hash[*@volumes.map{|v| [v.id, v.data]}.flatten].to_json %>;\n class Volume\n def self.to_hash(volumes)\n Hash[*volumes.map{|v| [v.id, v.data]}.flatten]\n end\nend\n var volumes = <%= Volume.to_hash(@volumes).to_json %>;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10026/"
] |
273,002
|
<p>First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value.</p>
<p>Here's some example code:</p>
<pre><code>#!/usr/bin/python
import SOAPpy
import MySQLdb
def getNEXTVAL():
cursor = db.cursor()
cursor.execute( "CALL my_stored_procedure()" ) # Returns a number
result=cursor.fetchall()
for record in result:
return record[0]
db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing")
server = SOAPpy.SOAPServer(("10.1.22.29", 8080))
server.registerFunction(getNEXTVAL)
server.serve_forever()
</code></pre>
<p>I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?</p>
|
[
{
"answer_id": 8336051,
"author": "user1064941",
"author_id": 1064941,
"author_profile": "https://Stackoverflow.com/users/1064941",
"pm_score": 1,
"selected": false,
"text": "def test_soappy():\n \"\"\"test for SOAPpy.SOAPServer\n \"\"\"\n #okay\n # it's good for SOAPpy.SOAPServer.\n # in a method,it can have morn than 2 ws server.\n server = SOAPProxy(\"http://localhost:8081/\")\n print server.sum(1,2)\n print server.div(10,2)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31319/"
] |
273,009
|
<p>I need to select a datetime column in a table. However, I want the select statement to return the datetime as a nvarchar with the format DD/MM/YYYY.</p>
|
[
{
"answer_id": 273020,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 1,
"selected": false,
"text": "select convert(nvarchar(10), datefield, 103)\n"
},
{
"answer_id": 273021,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": true,
"text": "SELECT CONVERT(nvarchar(10), getdate(), 103)\n"
},
{
"answer_id": 273022,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "select CONVERT (NVARCHAR, GETDATE(), 103)\n"
},
{
"answer_id": 41594976,
"author": "Ema.H",
"author_id": 2630447,
"author_profile": "https://Stackoverflow.com/users/2630447",
"pm_score": 2,
"selected": false,
"text": "CONVERT(NVARCHAR(10), YOUR_DATE_TIME, 103) => 15/09/2016\nCONVERT(NVARCHAR(10), YOUR_DATE_TIME, 3) => 15/09/16\n CONVERT('TheDataTypeYouWant', 'TheDateToConvert', 'TheCodeForFormating' * )\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] |
273,029
|
<p>In converting from short to a byte array I found the following solution on the web but could not quite understand the logic involved.</p>
<pre><code>//buffer is an array of bytes, bytes[]
buffer[position] = (byte)(sample & 0xff);
buffer[position+1] = (byte)((sample >> 8) & 0xff);
</code></pre>
<p>Can someone tell me why 0xff (256) is being anded to the sample which is a short? </p>
|
[
{
"answer_id": 273058,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "1110001100001111 sample\n0000000011111111 0xff\n0000000000001111 sample & 0xff => first byte`\n 0000000011100011 sample >> 8\n0000000011111111 0xff\n0000000011100011 (sample >> 8 ) & 0xff => second byte\n"
},
{
"answer_id": 273323,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "& 0xFF & 0xFF int buffer[position] = (byte) sample;\nbuffer[position+1] = (byte) (sample >>> 8);\n"
},
{
"answer_id": 5495400,
"author": "user633535",
"author_id": 633535,
"author_profile": "https://Stackoverflow.com/users/633535",
"pm_score": 1,
"selected": false,
"text": "buffer[position] = (byte)(sample & 0xff);\nbuffer[position+1] = (byte)((sample >> 8) & 0xff);\n buffer[position] = (byte)((sample >> 8) & 0xff);\nbuffer[position+1] = (byte)(sample & 0xff);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,039
|
<p>In Xcode, I can use <kbd>CMD</kbd>-<kbd>R</kbd> to run (or <kbd>CMD</kbd>-<kbd>Y</kbd> to debug), and my app will compile, install on the phone & start-up. (I've already prepped my phone & Xcode so this part works as expected.)</p>
<p>What I'd <strong><em>LIKE</em></strong> to do is type CMD-<something else> and have my program compile & install on the phone, but <em>NOT</em> start-up.</p>
<p>I realize that I can just <kbd>CMD</kbd>-<kbd>B</kbd> to build, then go through some rigamarole to deploy, but I'm hoping one of you smart-folk can tell me the lazy-man's shortcut for all of this.</p>
|
[
{
"answer_id": 273095,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 3,
"selected": true,
"text": "xcodebuild install -configuration Debug\n xcodebuild install -target iPhoneApp -configuration Debug\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34820/"
] |
273,043
|
<p>We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message: </p>
<blockquote>
<p>Python Fatal Error: GC Object already tracked</p>
</blockquote>
<p>which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.</p>
|
[
{
"answer_id": 273111,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 4,
"selected": true,
"text": "(gdb) print PyRun_SimpleString(\"import traceback; traceback.print_stack()\")\n File \"<string>\", line 1, in <module>\n File \"/var/tmp/foo.py\", line 2, in <module>\n i**2\n File \"<string>\", line 1, in <module>\n$1 = 0\n pystack valgrind"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29825/"
] |
273,048
|
<p>How can I calculate the last business day of the month in .NET?</p>
|
[
{
"answer_id": 273094,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 3,
"selected": false,
"text": "Day day = getLastDayOfMonth\nint days = getDaysInMonth\nfor i = days to 0\n if day is weekday\n if day is not holiday\n return day\n end if\n end if\n day = prevDay\n days--\nend for\n\nthrow exception because no business day was found in the month\n"
},
{
"answer_id": 273099,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 4,
"selected": false,
"text": "Function GetLastBusinessDay(ByVal Year As Integer, ByVal Month As Integer) As DateTime\n Dim LastOfMonth As DateTime\n Dim LastBusinessDay As DateTime\n\n LastOfMonth = New DateTime(Year, Month, DateTime.DaysInMonth(Year, Month))\n\n If LastOfMonth.DayOfWeek = DayOfWeek.Sunday Then \n LastBusinessDay = LastOfMonth.AddDays(-2)\n ElseIf LastOfMonth.DayOfWeek = DayOfWeek.Saturday Then\n LastBusinessDay = LastOfMonth.AddDays(-1)\n Else\n LastBusinessDay = LastOfMonth\n End If\n\n Return LastBusinessDay\n\nEnd Function\n"
},
{
"answer_id": 273162,
"author": "Middletone",
"author_id": 35331,
"author_profile": "https://Stackoverflow.com/users/35331",
"pm_score": 0,
"selected": false,
"text": "Function GetLastDay(ByVal month As Int32, ByVal year As Int32) As Date\n Dim D As New Date(year, month, Date.DaysInMonth(year, month))\n For i As Integer = 0 To Date.DaysInMonth(year, month)\n Select Case D.AddDays(-i).DayOfWeek\n Case DayOfWeek.Saturday, DayOfWeek.Sunday 'Not a weekday\n Case Else 'Is a weekday. Flag as first weekday found\n Return D.AddDays(-i)\n 'you can add other code here which could also do a check for holidays or ther stuff since you have a proper date value to look at in the loop\n End Select\n Next\nEnd Function\n"
},
{
"answer_id": 273182,
"author": "Thedric Walker",
"author_id": 26166,
"author_profile": "https://Stackoverflow.com/users/26166",
"pm_score": 5,
"selected": true,
"text": "var holidays = new List<DateTime>{/* list of observed holidays */};\nDateTime lastBusinessDay = new DateTime();\nvar i = DateTime.DaysInMonth(year, month);\nwhile (i > 0)\n{\n var dtCurrent = new DateTime(year, month, i);\n if(dtCurrent.DayOfWeek < DayOfWeek.Saturday && dtCurrent.DayOfWeek > DayOfWeek.Sunday && \n !holidays.Contains(dtCurrent))\n {\n lastBusinessDay = dtCurrent;\n i = 0;\n }\n else\n {\n i = i - 1;\n }\n}\n"
},
{
"answer_id": 8801826,
"author": "Arvind Sedha",
"author_id": 1045321,
"author_profile": "https://Stackoverflow.com/users/1045321",
"pm_score": 3,
"selected": false,
"text": "private DateTime GetLastBusinessDayOfCurrentMonth()\n{\n var lastDayOfCurrentMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));\n\n if(lastDayOfCurrentMonth.DayOfWeek == DayOfWeek.Sunday)\n lastDayOfCurrentMonth = lastDayOfCurrentMonth.AddDays(-2);\n else if(lastDayOfCurrentMonth.DayOfWeek == DayOfWeek.Saturday)\n lastDayOfCurrentMonth = lastDayOfCurrentMonth.AddDays(-1);\n\n return lastDayOfCurrentMonth;\n}\n"
},
{
"answer_id": 26368338,
"author": "rbianchi",
"author_id": 2347115,
"author_profile": "https://Stackoverflow.com/users/2347115",
"pm_score": 2,
"selected": false,
"text": " public static DateTime GetLastBussinessDayCurrentMonth(DateTime[] holidays)\n {\n DateTime todayDateTime = DateTime.Today;\n\n return\n Enumerable.Range(1, DateTime.DaysInMonth(todayDateTime.Year, todayDateTime.Month))\n .Select(day => new DateTime(todayDateTime.Year, todayDateTime.Month, day))\n .Where(\n dt =>\n dt.DayOfWeek != DayOfWeek.Sunday && dt.DayOfWeek != DayOfWeek.Saturday\n && (holidays == null || !holidays.Any(h => h.Equals(dt))))\n .Max(d => d.Date);\n }\n Enumerable.Range(1, DateTime.DaysInMonth(todayDateTime.Year, todayDateTime.Month))\n .Where(\n dt =>\n dt.DayOfWeek != DayOfWeek.Sunday && dt.DayOfWeek != DayOfWeek.Saturday\n && (holidays == null || !holidays.Any(h => h.Equals(dt))))\n .Select(day => new DateTime(todayDateTime.Year, todayDateTime.Month, day))\n\n .Max(d => d.Date);\n"
},
{
"answer_id": 30877297,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 1,
"selected": false,
"text": "public static DateTime LastBusinessDayInMonth(int year, int month, bool adjustForWeekend = true)\n{\n var lastDay = DateTime.DaysInMonth(year, month);\n return PreviousOrCurrentBusinessDay(new DateTime(year, month, lastDay), adjustForWeekend);\n}\n\npublic static DateTime PreviousOrCurrentBusinessDay(DateTime? beforeOrOnDate = null, bool adjustForWeekend = true)\n{\n var fromDate = beforeOrOnDate ?? DateTime.Today;\n var year = fromDate.Year;\n var month = fromDate.Month;\n var day = fromDate.Day;\n var holidays = UsHolidays(fromDate.Year, true).ToList(); // defined below\n var dtCurrent = new DateTime(year, month, day);\n\n while (!(dtCurrent.DayOfWeek < DayOfWeek.Saturday && dtCurrent.DayOfWeek > DayOfWeek.Sunday && !holidays.Contains(dtCurrent)))\n {\n dtCurrent = dtCurrent.AddDays(-1);\n }\n return dtCurrent;\n}\n public static IEnumerable<DateTime> UsHolidays(int year, bool adjustForWeekend)\n{\n return new List<DateTime>()\n {\n NewYears(year, adjustForWeekend),\n MlkDay(year),\n PresidentsDay(year),\n GoodFriday(year),\n MemorialDay(year),\n IndependenceDay(year, adjustForWeekend),\n LaborDay(year),\n Thanksgiving(year),\n Christmas(year, adjustForWeekend),\n };\n}\n\npublic static DateTime NewYears(int year, bool adjustForWeekend)\n{\n //NEW YEARS \n return adjustForWeekend ? AdjustForWeekendHoliday(new DateTime(year, 1, 1).Date) : new DateTime(year, 1, 1).Date;\n}\n\npublic static DateTime MemorialDay(int year)\n{\n //MEMORIAL DAY -- last monday in May \n var memorialDay = new DateTime(year, 5, 31);\n var dayOfWeek = memorialDay.DayOfWeek;\n while (dayOfWeek != DayOfWeek.Monday)\n {\n memorialDay = memorialDay.AddDays(-1);\n dayOfWeek = memorialDay.DayOfWeek;\n }\n return memorialDay.Date;\n}\n\npublic static DateTime IndependenceDay(int year, bool adjustForWeekend)\n{\n //INDEPENCENCE DAY \n return adjustForWeekend ? AdjustForWeekendHoliday(new DateTime(year, 7, 4).Date) : new DateTime(year, 7, 4).Date;\n}\n\npublic static DateTime LaborDay(int year)\n{\n //LABOR DAY -- 1st Monday in September \n var laborDay = new DateTime(year, 9, 1);\n var dayOfWeek = laborDay.DayOfWeek;\n while (dayOfWeek != DayOfWeek.Monday)\n {\n laborDay = laborDay.AddDays(1);\n dayOfWeek = laborDay.DayOfWeek;\n }\n return laborDay.Date;\n}\n\npublic static DateTime Thanksgiving(int year)\n{\n //THANKSGIVING DAY - 4th Thursday in November \n var thanksgiving = (from day in Enumerable.Range(1, 30)\n where new DateTime(year, 11, day).DayOfWeek == DayOfWeek.Thursday\n select day).ElementAt(3);\n var thanksgivingDay = new DateTime(year, 11, thanksgiving);\n return thanksgivingDay.Date;\n}\n\npublic static DateTime Christmas(int year, bool adjustForWeekend)\n{\n return adjustForWeekend ? AdjustForWeekendHoliday(new DateTime(year, 12, 25).Date) : new DateTime(year, 12, 25).Date;\n}\n\npublic static DateTime MlkDay(int year)\n{\n //Martin Luther King Day -- third monday in January\n var MLKDay = new DateTime(year, 1, 21);\n var dayOfWeek = MLKDay.DayOfWeek;\n while (dayOfWeek != DayOfWeek.Monday)\n {\n MLKDay = MLKDay.AddDays(-1);\n dayOfWeek = MLKDay.DayOfWeek;\n }\n return MLKDay.Date;\n}\n\npublic static DateTime PresidentsDay(int year)\n{\n //President's Day -- third monday in February\n var presDay = new DateTime(year, 2, 21);\n var dayOfWeek = presDay.DayOfWeek;\n while (dayOfWeek != DayOfWeek.Monday)\n {\n presDay = presDay.AddDays(-1);\n dayOfWeek = presDay.DayOfWeek;\n }\n return presDay.Date;\n}\n\npublic static DateTime EasterSunday(int year)\n{\n var g = year % 19;\n var c = year / 100;\n var h = (c - c / 4 - (8 * c + 13) / 25 + 19 * g + 15) % 30;\n var i = h - h / 28 * (1 - h / 28 * (29 / (h + 1)) * ((21 - g) / 11));\n\n var day = i - ((year + year / 4 + i + 2 - c + c / 4) % 7) + 28;\n var month = 3;\n\n if (day > 31)\n {\n month++;\n day -= 31;\n }\n\n return new DateTime(year, month, day);\n}\n\npublic static DateTime GoodFriday(int year)\n{\n return EasterSunday(year).AddDays(-2);\n}\n\npublic static DateTime AdjustForWeekendHoliday(DateTime holiday)\n{\n if (holiday.DayOfWeek == DayOfWeek.Saturday)\n {\n return holiday.AddDays(-1);\n }\n return holiday.DayOfWeek == DayOfWeek.Sunday ? holiday.AddDays(1) : holiday;\n}\n"
},
{
"answer_id": 34235887,
"author": "user5671127",
"author_id": 5671127,
"author_profile": "https://Stackoverflow.com/users/5671127",
"pm_score": -1,
"selected": false,
"text": "DateTime today = DateTime.Today;\nDateTime endOfMonth = new DateTime(today.Year,\n today.Month,\n DateTime.DaysInMonth(today.Year,\n today.Month));\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770/"
] |
273,054
|
<p>I'm building the HTML code within an XML DOM object to be used as the contents of the innerHTML of a div element using an XSL template. Traditionally we create a new XML DOM document and add the input parameters as XML Elements for the transform via javascript. This is all very time-consuming as we are basically hand picking the data from another XML document that represents our current account and copying the data into a transient XML DOM document. </p>
<p>What I'd like to do is clone the relevant node of the account document (i.e. customer info) and use it as the basis for the transform. I don't want to use the account document directly as I'd like to be able to add transform specific input, without making changes to the account object.</p>
<p>How efficient is using .cloneNode(true) for a desired node of about typically less than 200 elements from a document of typically 2000+ elements? The target platform is IE6 with no external tools (i.e. ActiveX).</p>
|
[
{
"answer_id": 273191,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "javascript:'<xmp>'+window.document.body.outerHTML+'</xmp>';\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2650/"
] |
273,067
|
<p>Sometimes, my UIWebView will have a grey box over part or all of the content. I can't make heads or tails of why it's happening. It happens regularly for certain content.</p>
<p>Thanks!</p>
<p>--Update--</p>
<p>It seems to occur when the webview is not immediately viewable on the screen -- ie i've got a scrollview, and the webview is below the fold.</p>
<p>--Update #2--</p>
<p>When I bring the content above the fold, it loads fine most of the time. There are still instances when the grey box is still showing up. The weird part is if i double-tap it, it finishes loading the content just fine. bizarre</p>
<p>--Update #3--</p>
<p>Okay, so it seems to be that if my uiwebview has a height greater than 1000px, a grey box appears on the rest of the content below 1000px. A double-tap reveals the actual content.</p>
|
[
{
"answer_id": 1798343,
"author": "user218755",
"author_id": 218755,
"author_profile": "https://Stackoverflow.com/users/218755",
"pm_score": 0,
"selected": false,
"text": "UIView\n UIScrollView\n UIImageView\n UIWebView\n UIView\n UIScrollView\n UIImageView\n UIWebView\n - (void)viewDidLoad\n{\n // set delegates\n self.scrollView.delegate = self;\n self.webView.delegate = self;\n\n // store original UIWebView position in ivar\n webViewPosY = self.webView.frame.origin.y;\n\n // load html into UIWebView\n [self.webView loadHTMLString:someHTML baseURL:nil];\n}\n\n- (void)webViewDidFinishLoad:(UIWebView *)webView\n{\n // get UIWebView size and store in ivar\n webSize = [self.webView sizeThatFits:CGSizeMake(1.0,1.0)];\n\n // set proper content height for UIScrollView\n CGSize contentSize = self.scrollView.contentSize;\n contentSize.height = webViewPosY + webSize.height;\n self.scrollView.contentSize = contentSize; \n\n // set UIWebView's frame height same as UIScrollView has\n CGRect wf = self.webView.frame;\n wf.size.height = self.scrollView.frame.size.height;\n self.webView.frame = wf;\n}\n\n// scrolling logic:\n// 1. if origin of UIWebView > 0 then move UIWebView itself\n// 2. if origin of UIWebView == 0 then scroll with javascript\n// 3. if origin is 0 and whole html is scrolled then move UIWebView again(this happens to support scroll \"bouncing\", or if you have some views below UIWebView\n- (void)scrollViewDidScroll:(UIScrollView *)scrollView\n{\n CGFloat scrollPosY = self.scrollView.contentOffset.y;\n\n // (1) and (2) ifs\n // how much to move UIWebView\n CGFloat scrollOriginY = (scrollPosY >= webViewPosY) ? webViewPosY : scrollPosY;\n // how much to scroll via JS\n CGFloat scrollJSY = scrollPosY - scrollOriginY;\n\n // (3) if\n if ( scrollPosY > (webSize.height - scrollViewSize.height + webViewPosY ) )\n scrollOriginY += scrollPosY - (webSize.height - scrollViewSize.height + webViewPosY);\n\n // scroll with JS\n [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@\"document.body.scrollTop = %f;\", scrollJSY]];\n\n // move UIWebView itself\n CGRect wf = self.webView.frame;\n wf.origin.y = webViewPosY - scrollOriginY;\n self.webView.frame = wf;\n}\n"
},
{
"answer_id": 3378453,
"author": "Padraig",
"author_id": 67369,
"author_profile": "https://Stackoverflow.com/users/67369",
"pm_score": 1,
"selected": false,
"text": "[UIScrollView *webScroller= [[webView subviews] lastObject]; \n[webScroller setContentOffset:CGPointMake(0,1) animated:NO];\n[webScroller setContentOffset:CGPointMake(0,0) animated:NO];\n"
},
{
"answer_id": 4110851,
"author": "smtlaissezfaire",
"author_id": 469291,
"author_profile": "https://Stackoverflow.com/users/469291",
"pm_score": 0,
"selected": false,
"text": "#define LAYER_FOR(ui) [(ui) layer]\n#define FRAME_FOR(ui) [LAYER_FOR((ui)) frame]\n#define SET_FRAME_FOR(ui, frame) [LAYER_FOR((ui)) setFrame: (frame)]\n\n+ (void) setHeightTo: (CGFloat *) height_ptr forView: (UIView *) a_view {\n CGFloat height = *height_ptr;\n\n CGRect existing_frame = [[a_view layer] frame];\n existing_frame.size.height = height;\n\n // need to reassign the same frame !?\n NSLog(@\"setting text view: %@ to height: %f\", a_view, (float) height);\n SET_FRAME_FOR(a_view, existing_frame);\n}\n\n+ (void) resizeWebView: (UIWebView *) webView {\n NSString *js = @\" \\\n var __html_element = document.getElementsByTagName('html')[0]; \\\n var __height_string = document.defaultView.getComputedStyle(__html_element, null).getPropertyValue('height'); \\\n __height_string.replace('px', ''); \\\n \";\n\n NSString *heightString = [webView stringByEvaluatingJavaScriptFromString: js];\n float height = [heightString floatValue];\n\n if (height != UI_VIEW_HEIGHT(webView)) {\n [self setHeightTo: &height forView: webView];\n\n // resize scrollView inside webview to the same height\n UIScrollView *webScroller = [[webView subviews] lastObject];\n [self setHeightTo: &height forView: webScroller];\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,081
|
<p>I have an application that needs to hit the ActiveDirectory to get user permission/roles on startup of the app, and persist throughout. </p>
<p>I don't want to hit AD on every form to recheck the user's permissions, so I'd like the user's role and possibly other data on the logged-in user to be globally available on any form within the application, so I can properly hide functionality, buttons, etc. where necessary.</p>
<p>Something like:</p>
<pre><code>if (UserProperties.Role == Roles.Admin)
{
btnDelete.Visible = false;
}
</code></pre>
<p>What are the best practices for storing static user data in a windows app? Solutions such as a Singleton, or global variables may work, but I was trying to avoid these.</p>
<p>Is a User object that gets passed around to each form's contructor just as bad?</p>
|
[
{
"answer_id": 273292,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": true,
"text": "if (Thread.CurrentPrincipal.IsInRole(Roles.Admin)) {\n btnDelete.Visible = false;\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,103
|
<p>I have a class that inherits from a base class and implements the following...</p>
<pre><code> Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
</code></pre>
<p>Now the base class it inherits from also implements this System.IComparable.CompareTo so I'm getting the following compiler warning:</p>
<p><em>Warning: 'System.IComparable.CompareTo' is already implemented by the base class. Re-implementation of function assumed.</em> </p>
<p>I'm fine with that so my question is how can I suppress this warning for just this function (i.e. not all such warnings).</p>
<p><strong>Clarifications:</strong> </p>
<ul>
<li>Here is a <a href="http://msdn.microsoft.com/en-us/library/dwwt4s94(VS.80).aspx" rel="noreferrer">link</a> to the error on MSDN. </li>
<li>I've already tried both Shadows and Overrides and neither eliminates the warning. </li>
<li>The warning isn't on the method itself (unless Shadows or Overrides are omitted), but rather it's on "Implements System.IComparable.CompareTo" specifically.</li>
<li>I am not looking to suppress all warnings of this type (if they crop up), just this one.</li>
</ul>
<p><strong>Solution:</strong><br>
I was hoping to use the System.Diagnostics.CodeAnalysis.SuppressMessage attribute or something like C#'s #pragma but looks like there's no way to suppress the warning for a single line. There is a way to turn this message off for this project though, without turning <em>all</em> warnings off.</p>
<p>I manually edited the .vbproj file and included 42015 in the node for Debug and Release compilations. Not ideal but better than always seeing the warning in the IDE.</p>
<p>If someone has a better solution please add it and I'll gladly try it flag the answer.</p>
|
[
{
"answer_id": 273137,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": -1,
"selected": false,
"text": "Public Shadows Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo\n"
},
{
"answer_id": 273143,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": -1,
"selected": false,
"text": "Public Overrides Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo\n Public Shadows Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo\n"
},
{
"answer_id": 2324880,
"author": "Topi",
"author_id": 280188,
"author_profile": "https://Stackoverflow.com/users/280188",
"pm_score": 4,
"selected": true,
"text": "Public Overridable Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo\n Public Overrides Function CompareTo(ByVal obj As Object) As Integer\n"
},
{
"answer_id": 17092972,
"author": "Chris",
"author_id": 2483199,
"author_profile": "https://Stackoverflow.com/users/2483199",
"pm_score": 0,
"selected": false,
"text": "<NoWarn>42015</NoWarn>"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12842/"
] |
273,126
|
<p>I am wondering how the HttpContext is maintained given that the request-response nature of the web is essentially stateless.</p>
<p>Is an identifier being for the HttpContext object being sent as part of the __EVENTTarget / __EVENTARGUMENTS hidden fields so that the HttpRuntime class can create the HttpContext class by reading this section from the request (HttpWorkerRequest)? I don't think</p>
<p>Please let me know as I am trying to fill some holes in my understanding of the http pipeline and I was unable to find any information about this.</p>
<p>I understand something like
HttpContext.Current.Session["myKey"] = Value;</p>
<p>just works but if I had to do something similar in a different language (say perl), I would have to use hidden fields for the same, wouldn't I?</p>
<p>Thanks
-Venu</p>
|
[
{
"answer_id": 273224,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": true,
"text": "class HttpSessionState {\n private static readonly Sessions = \n new Dictionary<string, Dictionary<string, object>>();\n\n public object this(string key) {\n get {\n return GetCurrentUserSession()[key]\n }\n set {\n GetCurrentUserSession()[key] = value;\n }\n }\n\n private Dictionary<string, object> GetCurrentUserSession() {\n var id = GetCurrentUserSessionId[]\n var d = Sessions[id];\n if (d == null) {\n d = new Dictionary<string, object>();\n Sessions[id] = d;\n }\n return d;\n }\n\n private string GetCurrentUserSessionId() {\n return HttpContext.Current.Request.Cookies[\"ASP.NET_SessionId\"].Value;\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35559/"
] |
273,141
|
<p>I haven't used regular expressions at all, so I'm having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions.</p>
<pre><code>string compare = "1234=4321";
Regex regex = new Regex(@"[\d]");
if (regex.IsMatch(compare))
{
//true
}
regex = new Regex("[0-9]");
if (regex.IsMatch(compare))
{
//true
}
</code></pre>
<p>In case it matters, I'm using C# and .NET2.0.</p>
|
[
{
"answer_id": 273144,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 10,
"selected": true,
"text": "Regex regex = new Regex(@\"^\\d$\");\n \"^\\d+$\" \"\\d\" [0-9] ٠١٢٣٤٥٦٧٨٩ \"^[0-9]+$\""
},
{
"answer_id": 273150,
"author": "kasperjj",
"author_id": 34240,
"author_profile": "https://Stackoverflow.com/users/34240",
"pm_score": 4,
"selected": false,
"text": "^\\d+$\n"
},
{
"answer_id": 273152,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 7,
"selected": false,
"text": "regex = new Regex(\"^[0-9]+$\");\n ^ $ +"
},
{
"answer_id": 5717007,
"author": "Andrew Chaa",
"author_id": 437961,
"author_profile": "https://Stackoverflow.com/users/437961",
"pm_score": 6,
"selected": false,
"text": "var regex = new Regex(@\"^-?[0-9][0-9,\\.]+$\");\n"
},
{
"answer_id": 10367753,
"author": "S.M.Mousavi",
"author_id": 1074799,
"author_profile": "https://Stackoverflow.com/users/1074799",
"pm_score": 3,
"selected": false,
"text": "Regex = new Regex(@\"^[\\p{N}]+$\");\n Regex = new Regex(@\"^[\\p{N}\\.]+$\");\n"
},
{
"answer_id": 21267370,
"author": "Rezo Megrelidze",
"author_id": 2204040,
"author_profile": "https://Stackoverflow.com/users/2204040",
"pm_score": 4,
"selected": false,
"text": " public static bool IsNumber(string s)\n {\n return s.All(char.IsDigit);\n }\n"
},
{
"answer_id": 22112198,
"author": "ultraklon",
"author_id": 680933,
"author_profile": "https://Stackoverflow.com/users/680933",
"pm_score": 5,
"selected": false,
"text": "\"^-?\\\\d*(\\\\.\\\\d+)?$\"\n 894\n923.21\n76876876\n.32\n-894\n-923.21\n-76876876\n-.32\n hello\n9bye\nhello9bye\n888,323\n5,434.3\n-8,336.09\n87078.\n"
},
{
"answer_id": 22858505,
"author": "fnc12",
"author_id": 1927176,
"author_profile": "https://Stackoverflow.com/users/1927176",
"pm_score": 4,
"selected": false,
"text": "[0-9]*\n [0-9]+\n"
},
{
"answer_id": 23798355,
"author": "Ujjal Suttra Dhar",
"author_id": 1591437,
"author_profile": "https://Stackoverflow.com/users/1591437",
"pm_score": 4,
"selected": false,
"text": "^[0-9]+$\n 1425\n0142\n0\n1\n 154a25\n1234=3254\n"
},
{
"answer_id": 33976065,
"author": "Marina",
"author_id": 5311928,
"author_profile": "https://Stackoverflow.com/users/5311928",
"pm_score": 4,
"selected": false,
"text": "^(-?[1-9]+\\\\d*([.]\\\\d+)?)$|^(-?0[.]\\\\d*[1-9]+)$|^0$\n string []goodNumbers={\"3\",\"-3\",\"0\",\"0.0\",\"1.0\",\"0.1\",\"0.0001\",\"-555\",\"94549870965\"};\n string []badNums={\"a\",\"\",\" \",\"-\",\"001\",\"-00.2\",\"000.5\",\".3\",\"3.\",\" -1\",\"--1\",\"-.1\",\"-0\"};\n"
},
{
"answer_id": 35545697,
"author": "Tagar",
"author_id": 470583,
"author_profile": "https://Stackoverflow.com/users/470583",
"pm_score": 3,
"selected": false,
"text": "^[+-]?\\d*\\.\\d+$|^[+-]?\\d+(\\.\\d*)?$\n"
},
{
"answer_id": 38222062,
"author": "lipika chakraborty",
"author_id": 6400165,
"author_profile": "https://Stackoverflow.com/users/6400165",
"pm_score": 3,
"selected": false,
"text": " Regex regex = new Regex(@\"^\\d$\");\n \"^\\d+$\""
},
{
"answer_id": 39266103,
"author": "Azur",
"author_id": 4700600,
"author_profile": "https://Stackoverflow.com/users/4700600",
"pm_score": 2,
"selected": false,
"text": "^([,|.]?[0-9])+$\n"
},
{
"answer_id": 39446526,
"author": "Daniele D.",
"author_id": 4454567,
"author_profile": "https://Stackoverflow.com/users/4454567",
"pm_score": 3,
"selected": false,
"text": "var pattern = @\"^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$|^0.0$\";\nreturn Regex.Match(value, pattern, RegexOptions.IgnoreCase).Success;\n \"3\",\n\"-3\",\n\"0\",\n\"0.0\",\n\"1.0\",\n\"0.7\",\n\"690.7\",\n\"0.0001\",\n\"-555\",\n\"945465464654\"\n \"a\",\n\"\",\n\" \",\n\".\",\n\"-\",\n\"001\",\n\"00.2\",\n\"000.5\",\n\".3\",\n\"3.\",\n\" -1\",\n\"--1\",\n\"-.1\",\n\"-0\",\n\"00099\",\n\"099\"\n"
},
{
"answer_id": 64798219,
"author": "Chathuranga Kasthuriarachchi",
"author_id": 12212419,
"author_profile": "https://Stackoverflow.com/users/12212419",
"pm_score": 2,
"selected": false,
"text": " console.log(/^(0|[1-9][0-9]*)$/.test(3000)) // true\n"
},
{
"answer_id": 67945746,
"author": "Programmer",
"author_id": 5714602,
"author_profile": "https://Stackoverflow.com/users/5714602",
"pm_score": 0,
"selected": false,
"text": "^((([0\\u0660\\u06F0]|([1-9\\u0661-\\u0669\\u06F1-\\u06F9][0\\u0660\\u06F0]*?)+)(\\.)[0-9\\u0660-\\u0669\\u06F0-\\u06F9]+)|(([0\\u0660\\u06F0]?|([1-9\\u0661-\\u0669\\u06F1-\\u06F9][0\\u0660\\u06F0]*?)+))|\\b)$\n 11\n1.2\n0.3\n۱۲\n۱.۳\n۰.۲\n۲.۷\n 3.\n.3\n0..3\n.۱۲\n"
},
{
"answer_id": 69031564,
"author": "Yawar Ali",
"author_id": 5951242,
"author_profile": "https://Stackoverflow.com/users/5951242",
"pm_score": 0,
"selected": false,
"text": "Regex rx = new Regex(@\"^([1-9]\\d*(\\.)\\d*|0?(\\.)\\d*[1-9]\\d*|[1-9]\\d*)$\");\nstring text = \"12.0\";\nvar result = rx.IsMatch(text);\nConsole.WriteLine(result);\n 123 => True\n123.1 => True\n0.123 => True\n.123 => True\n0.2 => True\n3452.434.43=> False\n2342f43.34 => False\nsvasad.324 => False\n3215.afa => False\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4660/"
] |
273,142
|
<p>I'm looking to patch a piece of abandonware with some code.</p>
<p>The software is carbon based, so I can not use an InputManager (at least, I do not think I can). My idea was to add a dylib reference to the mach-o header, and launch a new thread when the initialization routine is called.</p>
<p>I have mucked around with the mach-o header using a hexeditor to add the appropriate load command (LC_ LOAD_DYLIB). </p>
<p>otool reports what I expect to see, so I'm fairly confident that the file is correctly formatted.</p>
<pre>
Load command 63
cmd LC_LOAD_DYLIB
cmdsize 60
name @executable_path/libAltInput.dylib (offset 24)
time stamp 1183743291 Fri Jul 6 19:34:51 2007
current version 0.0.0
compatibility version 0.0.0
</pre>
<p>However, launching the binary gives me the following error</p>
<pre>
dyld: bad external relocation length
</pre>
<p>All I can guess this means is that I need to modify the LC_ SYMTAB or LC_ DYNSYMTAB sections...</p>
<p>Anyone have any ideas?</p>
|
[
{
"answer_id": 1990844,
"author": "caleb",
"author_id": 242160,
"author_profile": "https://Stackoverflow.com/users/242160",
"pm_score": 2,
"selected": false,
"text": "set DYLD_INSERT_LIBRARIES to /my/path/libAltInput.dylib\n symoff stroff"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,145
|
<p>A friend of mine downloaded some malware from Facebook, and I'm curious to see what it does without infecting myself. I know that you can't really decompile an .exe, but can I at least view it in Assembly or attach a debugger? </p>
<p>Edit to say it is not a .NET executable, no CLI header.</p>
|
[
{
"answer_id": 39520876,
"author": "BullyWiiPlaza",
"author_id": 3764804,
"author_profile": "https://Stackoverflow.com/users/3764804",
"pm_score": 4,
"selected": false,
"text": "x64dbg"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
273,148
|
<p>Has anyone tried using these new VS2008 MFC classes yet? I can't seem to find any examples anywhere. Even the VS2008 samples(1) don't mention these classes. (They use CToolTip.)</p>
<p><em>(1) Update: My mistake. I had downloaded the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=01AE159F-08CD-495B-8BF4-A48CC395AD7B&displaylang=en" rel="nofollow noreferrer">non-SP1 samples</a>. I see that the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9761bb57-f066-4b70-9318-3965c5e68aad&DisplayLang=en" rel="nofollow noreferrer">SP1 samples</a> have samples specifically for the 2008 Feature Pack, including the DlgToolTips and ToolTipDemo projects mentioned in an answer. Unfortunately, they don't address doc/view or CTooltipManager.</em></p>
<p>Specifically, I'm trying to display tooltips in a standard MFC view/document application where there are two side-by-side views whose parent is CSplitterWnd. I had this working pre-SP1, and I thought this'd be a good time to try the new Feature Pack tooltip classes.</p>
<p>Is there any way to make these things work without overriding PreTranslateMessage() and manually calling RelayEvent()? (I don't think I've seen anything in MFC as poorly designed as tooltips.)</p>
<p>It doesn't seem as simple as merely calling CTooltipManager::CreateToolTip() and then AddTool() on the created tip.</p>
|
[
{
"answer_id": 39520876,
"author": "BullyWiiPlaza",
"author_id": 3764804,
"author_profile": "https://Stackoverflow.com/users/3764804",
"pm_score": 4,
"selected": false,
"text": "x64dbg"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4858/"
] |
273,151
|
<p>I've used MS Word automation to save a .doc to a .htm. If there are bullet characters in the .doc file, they are saved fine to the .htm, but when I try to read the .htm file into a string (so I can subsequently send to a database for ultimate storage as a string, not a blob), the bullets are converted to question marks or other characters depending on the encoding used to load into a string.</p>
<p>I'm using this to read the text:</p>
<pre><code>string html = File.ReadAllText(myFileSpec);
</code></pre>
<p>I've also tried using StreamReader, but get the same results (maybe it's used internally by File.ReadAllText).</p>
<p>I've also tried specifying every type of Encoding in the second overload of File.ReadAllText:</p>
<pre><code>string html = File.ReadAllText(originalFile, Encoding.ASCII);
</code></pre>
<p>I've tried all the available enums for the Encoding type.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 273423,
"author": "Ian G",
"author_id": 31765,
"author_profile": "https://Stackoverflow.com/users/31765",
"pm_score": 0,
"selected": false,
"text": ".doc .html File.ReadAllText StreamReader File.ReadAllText <ul style='margin-top:0cm' type=disc> \n <li class=MsoNormal style='mso-list:l0 level1 lfo1;tab-stops:list 36.0pt'>\n <span lang=EN-GB style='mso-ansi-language:EN-GB'>Test 1</span>\n </li> \n <li class=MsoNormal style='mso-list:l0 level1 lfo1;tab-stops:list 36.0pt'>\n <span lang=EN-GB style='mso-ansi-language:EN-GB'>Test 2</span>\n </li> \n </ul>\n"
},
{
"answer_id": 273573,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 3,
"selected": true,
"text": "string html = File.ReadAllText(originalFile, Encoding.GetEncoding(1252));\n"
},
{
"answer_id": 273640,
"author": "Todd Price",
"author_id": 29107,
"author_profile": "https://Stackoverflow.com/users/29107",
"pm_score": 0,
"selected": false,
"text": "data = File.ReadAllText(tempFile, Encoding.Default);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29107/"
] |
273,159
|
<p>I'm trying to install a site under an alternative port on a server, but the port may be closed by a firewall. Is there a way to ping out or in, on a specific port, to see if it is open?</p>
|
[
{
"answer_id": 273188,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 11,
"selected": true,
"text": "netstat -an telnet host port telnet host:port"
},
{
"answer_id": 4658665,
"author": "Machtyn",
"author_id": 571380,
"author_profile": "https://Stackoverflow.com/users/571380",
"pm_score": 5,
"selected": false,
"text": "telnet"
},
{
"answer_id": 15952796,
"author": "J.Celmer",
"author_id": 2271021,
"author_profile": "https://Stackoverflow.com/users/2271021",
"pm_score": 8,
"selected": false,
"text": "netstat -na | findstr \"your_port\"\n LISTENING ESTABLISHED TCP"
},
{
"answer_id": 16361938,
"author": "Derbium",
"author_id": 704666,
"author_profile": "https://Stackoverflow.com/users/704666",
"pm_score": 3,
"selected": false,
"text": "netstat -an | where{$_.Contains(\"Yourport\")}\n"
},
{
"answer_id": 17429815,
"author": "Praveen Tiwari",
"author_id": 1624454,
"author_profile": "https://Stackoverflow.com/users/1624454",
"pm_score": 1,
"selected": false,
"text": "telnet"
},
{
"answer_id": 22224602,
"author": "Sarvar N",
"author_id": 2490074,
"author_profile": "https://Stackoverflow.com/users/2490074",
"pm_score": 5,
"selected": false,
"text": "netstat -an | find \"8080\" \n telnet 192.168.100.132 8080\n"
},
{
"answer_id": 23925865,
"author": "Gunjan Moghe",
"author_id": 2020879,
"author_profile": "https://Stackoverflow.com/users/2020879",
"pm_score": 5,
"selected": false,
"text": "portqry -n 11.22.33.44 -p tcp -e 80\n"
},
{
"answer_id": 24359423,
"author": "zehnaseeb",
"author_id": 3318016,
"author_profile": "https://Stackoverflow.com/users/3318016",
"pm_score": 4,
"selected": false,
"text": "netstat -an |find /i \"listening\"\n netstat -a\n"
},
{
"answer_id": 32437040,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 2,
"selected": false,
"text": "tcping host port"
},
{
"answer_id": 35624189,
"author": "knocte",
"author_id": 544947,
"author_profile": "https://Stackoverflow.com/users/544947",
"pm_score": 7,
"selected": false,
"text": "Test-NetConnection -Port 800 -ComputerName 192.168.0.1 -InformationLevel Detailed\n $PSVersionTable"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16794/"
] |
273,169
|
<p>How can I dynamically invoke a class method in PHP? The class method is not static. It appears that </p>
<pre><code>call_user_func(...)
</code></pre>
<p>only works with static functions?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 273175,
"author": "Neil Williams",
"author_id": 9617,
"author_profile": "https://Stackoverflow.com/users/9617",
"pm_score": 2,
"selected": false,
"text": "call_user_func(array($object, 'methodName'));\n"
},
{
"answer_id": 273176,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 8,
"selected": true,
"text": "// Non static call\ncall_user_func( array( $obj, 'method' ) );\n\n// Static calls\ncall_user_func( array( 'ClassName', 'method' ) );\ncall_user_func( 'ClassName::method' ); // (As of PHP 5.2.3)\n"
},
{
"answer_id": 273186,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": false,
"text": "<?php\n\nclass A {\n function test() {\n print 'test';\n }\n}\n\n$function = 'test';\n\n// method 1\nA::$function();\n\n// method 2\n$a = new A; \n$a->$function();\n\n?>\n"
},
{
"answer_id": 273930,
"author": "David",
"author_id": 9908,
"author_profile": "https://Stackoverflow.com/users/9908",
"pm_score": 5,
"selected": false,
"text": "// invoke an instance method\n$instance = new Instance();\n$instanceMethod = 'bar';\n$instance->$instanceMethod();\n\n// invoke a static method\n$class = 'NameOfTheClass';\n$staticMethod = 'blah';\n$class::$staticMethod();\n // invoke an instance method\n$instance = new Instance();\ncall_user_func( array( $instance, 'method' ) );\n\n// invoke a static method\n$class = 'NameOfTheClass';\ncall_user_func( array( $class, 'nameOfStaticMethod' ) );\ncall_user_func( 'NameOfTheClass::nameOfStaticMethod' ); // (As of PHP 5.2.3)\n mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] ) \n mixed call_user_func_array ( callable $callback , array $param_arr )\n"
},
{
"answer_id": 276913,
"author": "Bingy",
"author_id": 69518,
"author_profile": "https://Stackoverflow.com/users/69518",
"pm_score": 1,
"selected": false,
"text": "$bla = new Blahh_class();\n$bla->do_something();\n Blahh_class::do_something()\n class Blahh_class { \n public static function do_something(){\n echo 'I am doing something';\n }\n}\n class Blahh_class {\n $some_value;\n\n public function __construct($data) {\n $this->$some_value = $data;\n }\n\n public function do_something() {\n echo $this->some_value;\n }\n}\n $this"
},
{
"answer_id": 36996060,
"author": "user2288580",
"author_id": 2288580,
"author_profile": "https://Stackoverflow.com/users/2288580",
"pm_score": 0,
"selected": false,
"text": "class ReferenceContainer {\n\n function __construct(CallbackContainer $callbackContainer) {\n\n //Alternatively you can have no parameters in this constructor and create a new instance of CallbackContainer and invoke the callback in the same manner \n //var_dump($this->callbackContainer);\n $data = 'This is how you parse a class by reference';\n $callbackContainer->myCallback($data);\n\n }\n\n}\n\nclass CallbackContainer {\n\n function __construct() {}\n\n function myCallback($data) {\n\n echo $data.\"\\n\";\n\n }\n\n}\n\n$callbackContainer = new CallbackContainer();\n$doItContainer = new ReferenceContainer($callbackContainer);\n"
},
{
"answer_id": 57075994,
"author": "MAChitgarha",
"author_id": 4215651,
"author_profile": "https://Stackoverflow.com/users/4215651",
"pm_score": 3,
"selected": false,
"text": "// Static call only\n[TestClass::class, $methodName](...$args);\n\n// Dynamic call, static or non-static doesn't matter\n$instance = new TestClass();\n[$instance, $methodName](...$args);\n TestClass $methodName ...$args"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
273,192
|
<p>How do I check if the directory into which a file is going to be written does exist, and if it does not, create the directory using Python?</p>
|
[
{
"answer_id": 273206,
"author": "gone",
"author_id": 26880,
"author_profile": "https://Stackoverflow.com/users/26880",
"pm_score": 6,
"selected": false,
"text": "os.path.exists if not os.path.exists(dir):\n os.mkdir(dir)\n"
},
{
"answer_id": 273208,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 7,
"selected": false,
"text": "os.makedirs OSError exist_ok False OSError import os\ntry:\n os.makedirs('./path/to/somewhere')\nexcept OSError:\n pass\n"
},
{
"answer_id": 273227,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 14,
"selected": true,
"text": "pathlib.Path.mkdir from pathlib import Path\nPath(\"/my/directory\").mkdir(parents=True, exist_ok=True)\n os.path.exists os.makedirs import os\nif not os.path.exists(directory):\n os.makedirs(directory)\n os.path.exists os.makedirs os.makedirs OSError OSError OSError import os, errno\n\ntry:\n os.makedirs(directory)\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise\n os.path.exists FileExistsError try:\n os.makedirs(\"path/to/directory\")\nexcept FileExistsError:\n # directory already exists\n pass\n os.makedirs exist_ok os.makedirs(\"path/to/directory\", exist_ok=True) # succeeds even if directory exists.\n"
},
{
"answer_id": 273679,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 5,
"selected": false,
"text": "import os\n\ndirname = 'create/me'\n\ntry:\n os.makedirs(dirname)\nexcept OSError:\n if os.path.exists(dirname):\n # We are nearly safe\n pass\n else:\n # There was an error on creation, so make sure we know about it\n raise\n"
},
{
"answer_id": 444023,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "os.path.isdir() os.path.exists() >>> os.path.exists('/tmp/dirname')\nTrue\n>>> os.path.exists('/tmp/dirname/filename.etc')\nTrue\n>>> os.path.isdir('/tmp/dirname/filename.etc')\nFalse\n>>> os.path.isdir('/tmp/fakedirname')\nFalse\n >>> directory = raw_input(\":: \")\n :: /tmp/dirname/filename.etc\n filename.etc os.makedirs() os.path.exists()"
},
{
"answer_id": 5032238,
"author": "Heikki Toivonen",
"author_id": 62596,
"author_profile": "https://Stackoverflow.com/users/62596",
"pm_score": 9,
"selected": false,
"text": "import os\nimport errno\n\ndef make_sure_path_exists(path):\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n OSError errno.EACCES"
},
{
"answer_id": 14364249,
"author": "Asclepius",
"author_id": 832230,
"author_profile": "https://Stackoverflow.com/users/832230",
"pm_score": 11,
"selected": false,
"text": "import pathlib\npathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True) \n pathlib.Path.mkdir parents pathlib pathlib pathlib2 pathlib pathlib exist_ok mkdir os import os\nos.makedirs(path, exist_ok=True)\n os.makedirs exist_ok False pathlib pathlib pathlib2 pathlib os import os\ntry: \n os.makedirs(path)\nexcept OSError:\n if not os.path.isdir(path):\n raise\n os.path.isdir os.makedirs errno OSError: [Errno 17] File exists errno.EEXIST mkpath import distutils.dir_util\ndistutils.dir_util.mkpath(path)\n mkpath mkpath os.makedirs"
},
{
"answer_id": 24740135,
"author": "kavadias",
"author_id": 2258526,
"author_profile": "https://Stackoverflow.com/users/2258526",
"pm_score": 4,
"selected": false,
"text": "try:\n os.makedirs(path)\nexcept OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n else:\n print \"\\nBE CAREFUL! Directory %s already exists.\" % path\n if not os.path.exists(path):\n os.makedirs(path)\nelse:\n print \"\\nBE CAREFUL! Directory %s already exists.\" % path\n"
},
{
"answer_id": 28100717,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 5,
"selected": false,
"text": "if not os.path.exists(d):\n os.makedirs(d)\n import errno\ntry:\n os.makedirs(d)\nexcept OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n tempfile import tempfile\n\nd = tempfile.mkdtemp()\n mkdtemp(suffix='', prefix='tmp', dir=None)\n User-callable function to create and return a unique temporary\n directory. The return value is the pathname of the directory.\n\n The directory is readable, writable, and searchable only by the\n creating user.\n\n Caller is responsible for deleting the directory when done with it.\n pathlib.Path exist_ok Path mkdir from pathlib import Path\nimport tempfile\n os.path.join / directory = Path(tempfile.gettempdir()) / 'sodata'\n exist_ok directory.mkdir(exist_ok=True)\n exist_ok FileExistsError POSIX mkdir -p todays_file = directory / str(datetime.datetime.utcnow().date())\nif todays_file.exists():\n logger.info(\"todays_file exists: \" + str(todays_file))\n df = pd.read_json(str(todays_file))\n Path str str os.PathLike"
},
{
"answer_id": 28100757,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 6,
"selected": false,
"text": "filename = \"/my/directory/filename.txt\"\ndir = os.path.dirname(filename)\n dir filepath fullfilepath filename import os\nfilepath = '/my/directory/filename.txt'\ndirectory = os.path.dirname(filepath)\n if not os.path.exists(directory):\n os.makedirs(directory)\nf = file(filename)\n with open(filepath) as my_file:\n do_stuff(my_file)\n IOError errno.ENOENT import errno\ntry:\n with open(filepath) as my_file:\n do_stuff(my_file)\nexcept IOError as error:\n if error.errno == errno.ENOENT:\n print 'ignoring error because directory or file is not there'\n else:\n raise\n w a import os\nif not os.path.exists(directory):\n os.makedirs(directory)\nwith open(filepath, 'w') as my_file:\n do_stuff(my_file)\n makedirs import os\nimport errno\nif not os.path.exists(directory):\n try:\n os.makedirs(directory)\n except OSError as error:\n if error.errno != errno.EEXIST:\n raise\nwith open(filepath, 'w') as my_file:\n do_stuff(my_file)\n"
},
{
"answer_id": 28997083,
"author": "Antti Haapala -- Слава Україні",
"author_id": 918959,
"author_profile": "https://Stackoverflow.com/users/918959",
"pm_score": 5,
"selected": false,
"text": "pathlib from pathlib import Path\npath = Path(\"/my/directory/filename.txt\")\ntry:\n if not path.parent.exists():\n path.parent.mkdir(parents=True)\nexcept OSError:\n # handle error; you can also catch specific errors like\n # FileExistsError and so on.\n"
},
{
"answer_id": 35262209,
"author": "alissonmuller",
"author_id": 3051142,
"author_profile": "https://Stackoverflow.com/users/3051142",
"pm_score": 3,
"selected": false,
"text": "import os\nimport errno\n\ndef make_sure_path_exists(path):\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST or not os.path.isdir(path):\n raise\n"
},
{
"answer_id": 36289129,
"author": "tashuhka",
"author_id": 2039736,
"author_profile": "https://Stackoverflow.com/users/2039736",
"pm_score": 5,
"selected": false,
"text": "IPython.utils.path.ensure_dir_exists() from IPython.utils.path import ensure_dir_exists\nensure_dir_exists(dir)\n"
},
{
"answer_id": 37703074,
"author": "iPhynx",
"author_id": 5489173,
"author_profile": "https://Stackoverflow.com/users/5489173",
"pm_score": 3,
"selected": false,
"text": "os.listdir import os\nif 'dirName' in os.listdir('parentFolderPath')\n print('Directory Exists')\n"
},
{
"answer_id": 39479473,
"author": "Dennis Golomazov",
"author_id": 304209,
"author_profile": "https://Stackoverflow.com/users/304209",
"pm_score": 4,
"selected": false,
"text": "mkpath # Create a directory and any missing ancestor directories. \n# If the directory already exists, do nothing.\n\nfrom distutils.dir_util import mkpath\nmkpath(\"test\") \n"
},
{
"answer_id": 40949679,
"author": "Ralph Schwerdt",
"author_id": 4606792,
"author_profile": "https://Stackoverflow.com/users/4606792",
"pm_score": 3,
"selected": false,
"text": "os.path.isdir('/tmp/dirname')\n"
},
{
"answer_id": 41147087,
"author": "hiro protagonist",
"author_id": 4954037,
"author_profile": "https://Stackoverflow.com/users/4954037",
"pm_score": 7,
"selected": false,
"text": "pathlib.Path.mkdir exist_ok from pathlib import Path\npath = Path('/my/directory/filename.txt')\npath.parent.mkdir(parents=True, exist_ok=True) \n# path.parent ~ os.path.dirname(path)\n os.makedirs exist_ok os.makedirs(path, exist_ok=True) exist_ok"
},
{
"answer_id": 41453417,
"author": "euccas",
"author_id": 3109254,
"author_profile": "https://Stackoverflow.com/users/3109254",
"pm_score": 5,
"selected": false,
"text": "os.makedirs exist_ok False OSError exist_ok True OSError os.makedirs(path,exist_ok=True)\n os.makedirs exist_ok import os\nimport errno\n\ndef make_sure_path_exists(path):\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n"
},
{
"answer_id": 42127930,
"author": "Michael Strobel",
"author_id": 7424032,
"author_profile": "https://Stackoverflow.com/users/7424032",
"pm_score": 3,
"selected": false,
"text": "os.path.exists()"
},
{
"answer_id": 47842472,
"author": "Victoria Stuart",
"author_id": 1904943,
"author_profile": "https://Stackoverflow.com/users/1904943",
"pm_score": 4,
"selected": false,
"text": "└── output/ ## dir\n ├── corpus ## file\n ├── corpus2/ ## dir\n └── subdir/ ## dir\n # ----------------------------------------------------------------------------\n# [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist\n\nimport pathlib\n\n\"\"\" Notes:\n 1. Include a trailing slash at the end of the directory path\n (\"Method 1,\" below).\n 2. If a subdirectory in your intended path matches an existing file\n with same name, you will get the following error:\n \"NotADirectoryError: [Errno 20] Not a directory:\" ...\n\"\"\"\n# Uncomment and try each of these \"out_dir\" paths, singly:\n\n# ----------------------------------------------------------------------------\n# METHOD 1:\n# Re-running does not overwrite existing directories and files; no errors.\n\n# out_dir = 'output/corpus3' ## no error but no dir created (missing tailing /)\n# out_dir = 'output/corpus3/' ## works\n# out_dir = 'output/corpus3/doc1' ## no error but no dir created (missing tailing /)\n# out_dir = 'output/corpus3/doc1/' ## works\n# out_dir = 'output/corpus3/doc1/doc.txt' ## no error but no file created (os.makedirs creates dir, not files! ;-)\n# out_dir = 'output/corpus2/tfidf/' ## fails with \"Errno 20\" (existing file named \"corpus2\")\n# out_dir = 'output/corpus3/tfidf/' ## works\n# out_dir = 'output/corpus3/a/b/c/d/' ## works\n\n# [2] https://docs.python.org/3/library/os.html#os.makedirs\n\n# Uncomment these to run \"Method 1\":\n\n#directory = os.path.dirname(out_dir)\n#os.makedirs(directory, mode=0o777, exist_ok=True)\n\n# ----------------------------------------------------------------------------\n# METHOD 2:\n# Re-running does not overwrite existing directories and files; no errors.\n\n# out_dir = 'output/corpus3' ## works\n# out_dir = 'output/corpus3/' ## works\n# out_dir = 'output/corpus3/doc1' ## works\n# out_dir = 'output/corpus3/doc1/' ## works\n# out_dir = 'output/corpus3/doc1/doc.txt' ## no error but creates a .../doc.txt./ dir\n# out_dir = 'output/corpus2/tfidf/' ## fails with \"Errno 20\" (existing file named \"corpus2\")\n# out_dir = 'output/corpus3/tfidf/' ## works\n# out_dir = 'output/corpus3/a/b/c/d/' ## works\n\n# Uncomment these to run \"Method 2\":\n\n#import os, errno\n#try:\n# os.makedirs(out_dir)\n#except OSError as e:\n# if e.errno != errno.EEXIST:\n# raise\n# ----------------------------------------------------------------------------\n"
},
{
"answer_id": 49851755,
"author": "Manivannan Murugavel",
"author_id": 6559063,
"author_profile": "https://Stackoverflow.com/users/6559063",
"pm_score": 3,
"selected": false,
"text": " if not os.path.isdir(test_img_dir):\n os.mkdir(test_img_dir)\n"
},
{
"answer_id": 50078422,
"author": "Steffi Keran Rani J",
"author_id": 7245145,
"author_profile": "https://Stackoverflow.com/users/7245145",
"pm_score": 3,
"selected": false,
"text": "create_dir() import os\n\ndef create_dir(directory):\n if not os.path.exists(directory):\n print('Creating Directory '+directory)\n os.makedirs(directory)\n\ncreate_dir('Project directory')\n"
},
{
"answer_id": 52282050,
"author": "Geoff Paul Bremner",
"author_id": 4821206,
"author_profile": "https://Stackoverflow.com/users/4821206",
"pm_score": 3,
"selected": false,
"text": "mkdir -p from subprocess import call\ncall(['mkdir', '-p', 'path1/path2/path3'])\n from subprocess import check_call\ntry:\n check_call(['mkdir', '-p', 'path1/path2/path3'])\nexcept:\n handle...\n"
},
{
"answer_id": 56203876,
"author": "Hussam Kurd",
"author_id": 1627358,
"author_profile": "https://Stackoverflow.com/users/1627358",
"pm_score": 3,
"selected": false,
"text": "import os,sys,inspect\nimport pathlib\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nyour_folder = currentdir + \"/\" + \"your_folder\"\n\nif not os.path.exists(your_folder):\n pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)\n"
},
{
"answer_id": 64474894,
"author": "korakot",
"author_id": 6729010,
"author_profile": "https://Stackoverflow.com/users/6729010",
"pm_score": 2,
"selected": false,
"text": "fastcore path.mk_write(data) from fastcore.utils import Path\nPath('/dir/to/file.txt').mk_write('Hello World')\n"
},
{
"answer_id": 68821616,
"author": "Dominykas Mostauskis",
"author_id": 1714997,
"author_profile": "https://Stackoverflow.com/users/1714997",
"pm_score": 4,
"selected": false,
"text": "from pathlib import Path\n\npath_to_file = Path(\"zero/or/more/directories/file.ext\")\nparent_directory_of_file = path_to_file.parent\nparent_directory_of_file.mkdir(parents=True, exist_ok=True)\n path_to_file file.ext"
},
{
"answer_id": 71029280,
"author": "Devil",
"author_id": 9427260,
"author_profile": "https://Stackoverflow.com/users/9427260",
"pm_score": 5,
"selected": false,
"text": "#Devil\nimport os\ndirectory = \"./out_dir/subdir1/subdir2\"\nif not os.path.exists(directory):\n os.makedirs(directory)\n"
},
{
"answer_id": 71466038,
"author": "Simone",
"author_id": 8411609,
"author_profile": "https://Stackoverflow.com/users/8411609",
"pm_score": 5,
"selected": false,
"text": "from pathlib import Path\nPath(\"path/with/childs/.../\").mkdir(parents=True, exist_ok=True)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
273,199
|
<p>I'm trying to convert some Xaml to HTML using the .NET XslCompiledTransform and am running into difficulties getting the xslt to match Xaml tags. For instance with this Xaml input:</p>
<pre><code><FlowDocument PagePadding="5,0,5,0" AllowDrop="True" NumberSubstitution.CultureSource="User" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Paragraph>a</Paragraph>
</FlowDocument>
</code></pre>
<p>And this xslt:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match="FlowDocument">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="Paragraph" >
<p>
<xsl:apply-templates />
</p>
</xsl:template>
</code></pre>
<p>I get this output:</p>
<pre><code><html>
<body>
a
</body>
</html>
</code></pre>
<p>Rather than the expected:</p>
<pre><code><html>
<body>
<p>a</p>
</body>
</html>
</code></pre>
<p>Could this be a problem with the namespace? This is my first attempt at an xsl transform, so I'm at a loss.</p>
|
[
{
"answer_id": 273257,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 6,
"selected": true,
"text": "http://schemas.microsoft.com/winfx/2006/xaml/presentation <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" \n xmlns:p=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n exclude-result-prefixes=\"msxsl\"/>\n\n<xsl:output method=\"html\" indent=\"yes\"/>\n\n<xsl:template match=\"/\">\n <html>\n <body>\n <xsl:apply-templates />\n </body>\n </html>\n</xsl:template>\n\n<xsl:template match=\"p:FlowDocument\">\n <xsl:apply-templates />\n</xsl:template>\n\n<xsl:template match=\"p:Paragraph\" >\n <p>\n <xsl:apply-templates />\n </p>\n</xsl:template>\n"
},
{
"answer_id": 273300,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 0,
"selected": false,
"text": "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
] |
273,203
|
<p>I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create a second stored procedure that only returns the second result set of the first?</p>
|
[
{
"answer_id": 313665,
"author": "TJG",
"author_id": 40211,
"author_profile": "https://Stackoverflow.com/users/40211",
"pm_score": 4,
"selected": false,
"text": "nextset() \nimport pyodbc\n\ndb = pyodbc.connect (\"\")\nq = db.cursor ()\nq.execute (\"\"\"\nSELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES\nSELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS\n\"\"\")\ntables = q.fetchall ()\nq.nextset ()\ncolumns = q.fetchall ()\n\nassert len (tables) == 5\nassert len (columns) == 10\n\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,209
|
<p>Is it ever acceptable to have a <a href="http://en.wikipedia.org/wiki/Memory_leak" rel="noreferrer">memory leak</a> in your C or C++ application?</p>
<p>What if you allocate some memory and use it until the very last line of code in your application (for example, a global object's destructor)? As long as the memory consumption doesn't grow over time, is it OK to trust the OS to free your memory for you when your application terminates (on Windows, Mac, and Linux)? Would you even consider this a real memory leak if the memory was being used continuously until it was freed by the OS.</p>
<p>What if a third party library forced this situation on you? Would refuse to use that third party library no matter how great it otherwise might be?</p>
<p>I only see one practical disadvantage, and that is that these benign leaks will show up with memory leak detection tools as false positives.</p>
|
[
{
"answer_id": 273585,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 3,
"selected": false,
"text": "/proc/self/maps"
},
{
"answer_id": 274042,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 1,
"selected": false,
"text": "std::auto_ptr"
},
{
"answer_id": 274433,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 6,
"selected": false,
"text": "malloc() #define BLK ((size_t)1024)\nwhile(1){\n void * vp = malloc(BLK);\n}\n int main(){\n void * vp = malloc(LOTS);\n // Go do something useful\n return 0;\n}\n"
},
{
"answer_id": 275042,
"author": "Jason L",
"author_id": 35616,
"author_profile": "https://Stackoverflow.com/users/35616",
"pm_score": 4,
"selected": false,
"text": "malloc() free() malloc() free() free()"
},
{
"answer_id": 276806,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 5,
"selected": false,
"text": "malloc free() free() free() free() free()"
},
{
"answer_id": 434352,
"author": "Blaisorblade",
"author_id": 53974,
"author_profile": "https://Stackoverflow.com/users/53974",
"pm_score": 3,
"selected": false,
"text": "FILE"
},
{
"answer_id": 593625,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 0,
"selected": false,
"text": "main()"
},
{
"answer_id": 45521078,
"author": "mksteve",
"author_id": 5129715,
"author_profile": "https://Stackoverflow.com/users/5129715",
"pm_score": 2,
"selected": false,
"text": "C++ std::map close"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3175/"
] |
273,217
|
<p>Does anybody know what's going on here:</p>
<p>I run hibernate 3.2.6 against a PostgreSQL 8.3 (installed via fink) database on my Mac OS X. The setup works fine when I use Java 6 and the JDBC 4 driver (postgresql-8.3-603.jdbc4). However, I need this stuff to work with Java 5 and (hence) JDBC 3 (postgresql-8.3-603.jdbc3). When I change the jar in the classpath and switch to Java 5 (I do this in eclipse), I get the following error:</p>
<pre><code>Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
<Rows clipped for readability>
Caused by: java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getConnection(DriverManager.java:545)
at java.sql.DriverManager.getConnection(DriverManager.java:140)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423)
</code></pre>
<p>What's the problem here? I cannot see it. Here is my hibernate configuration:</p>
<pre><code><hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:postgresql:test</property>
<property name="connection.username">postgres</property>
<property name="connection.password">p</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<mapping resource="com/mydomain/MyClass.hbm.xml"/>
</session-factory>
</hibernate-configuration>
</code></pre>
<p><strong>EDIT:</strong> The longer, more usual form of the connection URL: <em>jdbc:postgresql://localhost/test</em> has the exact same behaviour.</p>
<p>The driver jar is definitely in the classpath, and I also do not manage to get any errors with this direct JDBC test code:</p>
<pre><code>public static void main(String[] args) throws Exception {
Class.forName("org.postgresql.Driver");
Connection con=DriverManager.getConnection("jdbc:postgresql://localhost/test","postgres", "p");
}
</code></pre>
|
[
{
"answer_id": 273391,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 1,
"selected": false,
"text": "<property name=\"connection.url\">jdbc:postgresql:test</property>\n <property name=\"connection.url\">jdbc:postgresql://localhost/test</property>\n"
},
{
"answer_id": 273634,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 3,
"selected": true,
"text": "<hibernate-configuration>\n <session-factory>\n .\n .\n <property name=\"connection.driver_class\">org.postgresql.Driver</property>\n .\n </session-factory>\n</hibernate-configuration>\n"
},
{
"answer_id": 4183311,
"author": "Solution",
"author_id": 508110,
"author_profile": "https://Stackoverflow.com/users/508110",
"pm_score": 1,
"selected": false,
"text": "Class driverClass = Class.forName(\"org.postgresql.Driver\");\nDriverManager.registerDriver((Driver) driverClass.newInstance());\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4110/"
] |
273,218
|
<p>In layman's terms, what's a RDF triple?</p>
|
[
{
"answer_id": 273251,
"author": "Adam Ness",
"author_id": 21973,
"author_profile": "https://Stackoverflow.com/users/21973",
"pm_score": 5,
"selected": false,
"text": "\"gcc\" \"Compiles\" \"c\" .\n\"gcc\" \"compiles\" \"Java\" . \n\"gcc\" \"compiles\" \"fortran\" .\n\"gcc\" \"has a website at\" <http://gcc.gnu.org/> .\n\"gcc\" \"has a mailing list at\" <mailto:gcc-help@gcc.gnu.org> .\n\"c\" \"is a\" \"programming language\" .\n\"c\" \"is documented in\" <http://www.amazon.com/Programming-Language-Prentice-Hall-Software/dp/0131103628/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1226085111&sr=8-1> .\n"
},
{
"answer_id": 1122451,
"author": "Nico Adams",
"author_id": 137730,
"author_profile": "https://Stackoverflow.com/users/137730",
"pm_score": 6,
"selected": false,
"text": "uri://people#MikeSmith12 http://xmlns.com/foaf/0.1/knows uri://people#JohnDoe45\n"
},
{
"answer_id": 30900130,
"author": "Kingsley Uyi Idehen",
"author_id": 213503,
"author_profile": "https://Stackoverflow.com/users/213503",
"pm_score": 3,
"selected": false,
"text": "{\n <#this> a schema:WebPage .\n <#this> schema:about dbpedia:Resource_Description_Framework .\n <#this> skos:related <https://stackoverflow.com/questions/30742747/convert-a-statement-with-adjective-in-rdf-triple/30836089#30836089> . \n}\n #"
},
{
"answer_id": 32305453,
"author": "Batman22",
"author_id": 2322576,
"author_profile": "https://Stackoverflow.com/users/2322576",
"pm_score": 2,
"selected": false,
"text": "http://www.w3.org/TR/2004/REC-rdf-concepts-20040210/#dfn-URI-reference http://www.w3.org/TR/2004/REC-rdf-concepts-20040210/#dfn-blank-node"
},
{
"answer_id": 49066324,
"author": "jschnasse",
"author_id": 1485527,
"author_profile": "https://Stackoverflow.com/users/1485527",
"pm_score": 1,
"selected": false,
"text": "<question:45> <dc:creator> <user:485527>\n<question:44> <dc:creator> <user:485527>\n<question:40> <dc:creator> <user:485528>\n triple <Subject> <Predicate> <Object> <https://stackoverflow.com/a/49066324/1485527> \n<http://purl.org/dc/terms/creator> \n<https://stackoverflow.com/users/1485527>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35588/"
] |
273,220
|
<p>I want to create a library with a modified version of printf and then call LD_PRELOAD so when my program calls printf it uses my version. Can someone explain to me how to use LD_PRELOAD and if there is a something special I need to do in my code or my library? </p>
|
[
{
"answer_id": 273259,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": -1,
"selected": false,
"text": "printf"
},
{
"answer_id": 273277,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 3,
"selected": false,
"text": "LD_PRELOAD LD_PRELOAD"
},
{
"answer_id": 765135,
"author": "Maciej Piechotka",
"author_id": 49107,
"author_profile": "https://Stackoverflow.com/users/49107",
"pm_score": 2,
"selected": false,
"text": "LD_PRELOAD g_malloc"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,238
|
<p>How do I get:</p>
<pre><code>id Name Value
1 A 4
1 B 8
2 C 9
</code></pre>
<p>to</p>
<pre><code>id Column
1 A:4, B:8
2 C:9
</code></pre>
|
[
{
"answer_id": 273319,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "------------------------------\n-- Setup\n------------------------------\n\nDECLARE @Source TABLE\n(\n id int,\n Name varchar(30),\n Value int\n)\n\nDECLARE @Target TABLE\n(\n id int,\n Result varchar(max) \n)\n\n\nINSERT INTO @Source(id, Name, Value) SELECT 1, 'A', 4\nINSERT INTO @Source(id, Name, Value) SELECT 1, 'B', 8\nINSERT INTO @Source(id, Name, Value) SELECT 2, 'C', 9\n\n\n------------------------------\n-- Technique\n------------------------------\n\nINSERT INTO @Target (id)\nSELECT id\nFROM @Source\nGROUP BY id\n\nDECLARE @id int, @Result varchar(max)\nSET @id = (SELECT MIN(id) FROM @Target)\n\nWHILE @id is not null\nBEGIN\n SET @Result = null\n\n SELECT @Result =\n CASE\n WHEN @Result is null\n THEN ''\n ELSE @Result + ', '\n END + s.Name + ':' + convert(varchar(30),s.Value)\n FROM @Source s\n WHERE id = @id\n\n UPDATE @Target\n SET Result = @Result\n WHERE id = @id\n\n SET @id = (SELECT MIN(id) FROM @Target WHERE @id < id)\nEND\n\nSELECT *\nFROM @Target\n"
},
{
"answer_id": 273330,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 10,
"selected": true,
"text": "CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)\n\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'A',4)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',8)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)\n\nSELECT \n [ID],\n STUFF((\n SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) \n FROM #YourTable \n WHERE (ID = Results.ID) \n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,1,2,'') AS NameValues\nFROM #YourTable Results\nGROUP BY ID\n\nDROP TABLE #YourTable\n"
},
{
"answer_id": 3013557,
"author": "cyberkiwi",
"author_id": 363337,
"author_profile": "https://Stackoverflow.com/users/363337",
"pm_score": 5,
"selected": false,
"text": "---- test data\ndeclare @t table (OUTPUTID int, SCHME varchar(10), DESCR varchar(10))\ninsert @t select 1125439 ,'CKT','Approved'\ninsert @t select 1125439 ,'RENO','Approved'\ninsert @t select 1134691 ,'CKT','Approved'\ninsert @t select 1134691 ,'RENO','Approved'\ninsert @t select 1134691 ,'pn','Approved'\n\n---- actual query\n;with cte(outputid,combined,rn)\nas\n(\n select outputid, SCHME + ' ('+DESCR+')', rn=ROW_NUMBER() over (PARTITION by outputid order by schme, descr)\n from @t\n)\n,cte2(outputid,finalstatus,rn)\nas\n(\nselect OUTPUTID, convert(varchar(max),combined), 1 from cte where rn=1\nunion all\nselect cte2.outputid, convert(varchar(max),cte2.finalstatus+', '+cte.combined), cte2.rn+1\nfrom cte2\ninner join cte on cte.OUTPUTID = cte2.outputid and cte.rn=cte2.rn+1\n)\nselect outputid, MAX(finalstatus) from cte2 group by outputid\n"
},
{
"answer_id": 5939601,
"author": "Phillip",
"author_id": 571814,
"author_profile": "https://Stackoverflow.com/users/571814",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE #YourTable ( [ID] INT, [Name] CHAR(1), [Value] INT ) \n\nINSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (1, 'A', 4) \nINSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (1, 'B', 8) \nINSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (2, 'C', 9) \n\nSELECT [ID], \n REPLACE(REPLACE(REPLACE(\n (SELECT [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) as A \n FROM #YourTable \n WHERE ( ID = Results.ID ) \n FOR XML PATH (''))\n , '</A><A>', ', ')\n ,'<A>','')\n ,'</A>','') AS NameValues \nFROM #YourTable Results \nGROUP BY ID \n\nDROP TABLE #YourTable \n"
},
{
"answer_id": 7806049,
"author": "Jonathan Sayce",
"author_id": 13153,
"author_profile": "https://Stackoverflow.com/users/13153",
"pm_score": 5,
"selected": false,
"text": "& < > CREATE TABLE #YourTable ([ID] INT, [Name] VARCHAR(MAX), [Value] INT)\n\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'Oranges & Lemons',4)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'1 < 2',8)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)\n\nSELECT [ID],\n STUFF((\n SELECT ', ' + CAST([Name] AS VARCHAR(MAX))\n FROM #YourTable WHERE (ID = Results.ID) \n FOR XML PATH(''),TYPE \n /* Use .value to uncomment XML entities e.g. > < etc*/\n ).value('.','VARCHAR(MAX)') \n ,1,2,'') as NameValues\nFROM #YourTable Results\nGROUP BY ID\n\nDROP TABLE #YourTable\n STUFF"
},
{
"answer_id": 8404473,
"author": "Allen",
"author_id": 1015072,
"author_profile": "https://Stackoverflow.com/users/1015072",
"pm_score": 6,
"selected": false,
"text": "<\" and \"> FOR XML PATH('')\n)\n FOR XML PATH(''),TYPE\n).value('(./text())[1]','VARCHAR(MAX)')\n NVARCHAR(MAX) SQL"
},
{
"answer_id": 14646419,
"author": "Michal B.",
"author_id": 989256,
"author_profile": "https://Stackoverflow.com/users/989256",
"pm_score": 3,
"selected": false,
"text": "name type\n------------\nname1 type1\nname2 type2\nname2 type3\n SELECT name, LISTAGG(type, '; ') WITHIN GROUP(ORDER BY name)\nFROM table\nGROUP BY name\n name type\n------------\nname1 type1\nname2 type2; type3\n"
},
{
"answer_id": 29356760,
"author": "Marquinho Peli",
"author_id": 2992192,
"author_profile": "https://Stackoverflow.com/users/2992192",
"pm_score": 2,
"selected": false,
"text": "SELECT stuff(\n (\n select ', ' + x from (SELECT 'xxx' x union select 'yyyy') tb \n FOR XML PATH('')\n )\n, 1, 2, '')\n select ', ' + x from (SELECT 'xxx' x union select 'yyyy') tb\n"
},
{
"answer_id": 31002733,
"author": "Eduard",
"author_id": 5040220,
"author_profile": "https://Stackoverflow.com/users/5040220",
"pm_score": 2,
"selected": false,
"text": "SELECT \n [ID],\n\nCASE WHEN MAX( [Name]) = MIN( [Name]) THEN \nMAX( [Name]) NameValues\nELSE\n\n STUFF((\n SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) \n FROM #YourTable \n WHERE (ID = Results.ID) \n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,1,2,'') AS NameValues\n\nEND\n\nFROM #YourTable Results\nGROUP BY ID\n"
},
{
"answer_id": 36097542,
"author": "Orlando Colamatteo",
"author_id": 222606,
"author_profile": "https://Stackoverflow.com/users/222606",
"pm_score": 4,
"selected": false,
"text": "CREATE TABLE foo\n(\n id INT,\n name CHAR(1),\n Value CHAR(1)\n);\n\nINSERT INTO dbo.foo\n (id, name, Value)\nVALUES (1, 'A', '4'),\n (1, 'B', '8'),\n (2, 'C', '9');\n\nSELECT id,\n dbo.GROUP_CONCAT(name + ':' + Value) AS [Column]\nFROM dbo.foo\nGROUP BY id;\n"
},
{
"answer_id": 42807061,
"author": "Mordechai",
"author_id": 1047231,
"author_profile": "https://Stackoverflow.com/users/1047231",
"pm_score": 2,
"selected": false,
"text": " select T.ID\n,MAX(X.cl) NameValues\n from #YourTable T\n CROSS APPLY \n (select STUFF((\n SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX))\n FROM #YourTable \n WHERE (ID = T.ID) \n FOR XML PATH(''))\n ,1,2,'') [cl]) X\n GROUP BY T.ID\n"
},
{
"answer_id": 43664415,
"author": "Kannan Kandasamy",
"author_id": 6466279,
"author_profile": "https://Stackoverflow.com/users/6466279",
"pm_score": 8,
"selected": false,
"text": "STRING_AGG SELECT id, STRING_AGG(CONCAT(name, ':', [value]), ', ')\nFROM #YourTable \nGROUP BY id\n"
},
{
"answer_id": 57726143,
"author": "Mahesh",
"author_id": 4790127,
"author_profile": "https://Stackoverflow.com/users/4790127",
"pm_score": 1,
"selected": false,
"text": "SELECT T3.DEPT, REPLACE(REPLACE(T3.ENAME,'{\"ENAME\":\"',''),'\"}','') AS ENAME_LIST\nFROM (\n SELECT DEPT, (SELECT ENAME AS [ENAME]\n FROM EMPLOYEE T2\n WHERE T2.DEPT=T1.DEPT\n FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) ENAME\n FROM EMPLOYEE T1\n GROUP BY DEPT) T3\n"
},
{
"answer_id": 64346774,
"author": "Syzako",
"author_id": 5725441,
"author_profile": "https://Stackoverflow.com/users/5725441",
"pm_score": 0,
"selected": false,
"text": "WITH t AS (\n SELECT 1 n, 1 g, 1 v\n UNION ALL \n SELECT 2 n, 1 g, 2 v\n UNION ALL \n SELECT 3 n, 2 g, 3 v\n)\nSELECT g\n , STUFF (\n (\n SELECT ', ' + CAST(v AS VARCHAR(MAX))\n FROM t sub_t\n WHERE sub_t.g = main_t.g\n FOR XML PATH('')\n )\n , 1, 2, ''\n ) cg\nFROM t main_t\nGROUP BY g\n ************************* -> *********************\n* n * g * v * * g * cg *\n* - * - * - * * - * - *\n* 1 * 1 * 1 * * 1 * 1, 2 *\n* 2 * 1 * 2 * * 2 * 3 *\n* 3 * 2 * 3 * *********************\n************************* \n"
},
{
"answer_id": 64901189,
"author": "CJurkus",
"author_id": 3813981,
"author_profile": "https://Stackoverflow.com/users/3813981",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)\n\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'A',4)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',8)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',5)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)\n\n-- retrieve each unique id and name columns and concatonate the values into one column\nSELECT \n [ID], \n STUFF((\n SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) -- CONCATONATES EACH APPLICATION : VALUE SET \n FROM #YourTable \n WHERE (ID = Results.ID and Name = results.[name] ) \n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,1,2,'') AS NameValues\nFROM #YourTable Results\nGROUP BY ID\n\n\nSELECT \n [ID],[Name] , --these are acting as the group by clause\n STUFF((\n SELECT ', '+ CAST([Value] AS VARCHAR(MAX)) -- CONCATONATES THE VALUES FOR EACH ID NAME COMBINATION \n FROM #YourTable \n WHERE (ID = Results.ID and Name = results.[name] ) \n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,1,2,'') AS NameValues\nFROM #YourTable Results\nGROUP BY ID, name\n\nDROP TABLE #YourTable\n"
},
{
"answer_id": 66463664,
"author": "Ken Lassesen",
"author_id": 5749406,
"author_profile": "https://Stackoverflow.com/users/5749406",
"pm_score": 0,
"selected": false,
"text": " Declare @IdxList as Table(id int, choices varchar(max),AisName varchar(255))\n Insert into @IdxLIst(id,choices,AisName)\n Select IdxId,''''+Max(Title)+'''',Max(Title) From [dbo].[dta_Alias] \n where IdxId is not null group by IdxId\n Update @IdxLIst\n set choices=choices +','''+Title+''''\n From @IdxLIst JOIN [dta_Alias] ON id=IdxId And Title <> AisName\n where IdxId is not null\n Select * from @IdxList where choices like '%,%'\n"
},
{
"answer_id": 67129566,
"author": "Aus_10",
"author_id": 4254538,
"author_profile": "https://Stackoverflow.com/users/4254538",
"pm_score": 0,
"selected": false,
"text": " \nSELECT\ns.NOTE_ID\n,STUFF ((\n SELECT\n [note_text] + ' ' \n FROM\n HNO_NOTE_TEXT s1\n WHERE\n (s1.NOTE_ID = s.NOTE_ID)\n ORDER BY [line] ASC\n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,\n 1,\n 2,\n '') AS NOTE_TEXT_CONCATINATED\nFROM\n HNO_NOTE_TEXT s\n GROUP BY NOTE_ID\n \n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] |
273,242
|
<p>Is there anything like Winsplit Revolution for Mac OS X?</p>
|
[
{
"answer_id": 2977827,
"author": "Adrian Anttila",
"author_id": 5988,
"author_profile": "https://Stackoverflow.com/users/5988",
"pm_score": 1,
"selected": false,
"text": "tell application \"System Events\"\n set _everyProcess to every process\n repeat with n from 1 to count of _everyProcess\n set _frontMost to frontmost of item n of _everyProcess\n if _frontMost is true then set _frontMostApp to process n\n end repeat\n\n set _windowOne to window 1 of _frontMostApp\n set position of _windowOne to {5, 0}\n set size of _windowOne to {1150, 735}\nend tell\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5988/"
] |
273,261
|
<p>I have an application where I accept a socket connection from a telnet client and put up a simple, keyboard driven character GUI.</p>
<p>The telnet client, at least on Linux, defaults into line-at-a-time mode, so I always have to do <code>^]mode char</code> manually.</p>
<p>A skim of the relevant RFCs suggests that if my application simply sent the characters <code>IAC DONT LINEMODE (\377\376\042)</code> as soon as the client connects, the client should be forced into character mode. However, it doesn't make any difference.</p>
<p>What's the simplest bit of code that would do the job? Ideally just a string to be sent. My application can absorb whatever junk the client sends back.</p>
|
[
{
"answer_id": 279271,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "// IAC WONT LINEMODE IAC WILL ECHO\n\nwrite(s,\"\\377\\375\\042\\377\\373\\001\",6);\n"
},
{
"answer_id": 1068894,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "IAC WILL ECHO IAC WILL SUPPRESS_GO_AHEAD IAC WONT LINEMODE\n255 251 1 255 251 3 255 252 34\n"
},
{
"answer_id": 37377884,
"author": "h2g2bob",
"author_id": 6368266,
"author_profile": "https://Stackoverflow.com/users/6368266",
"pm_score": 2,
"selected": false,
"text": "write(s,\"\\377\\375\\042\\377\\373\\001\",6);\n // IAC DO LINEMODE IAC WILL ECHO\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,262
|
<p>I want to deal with the command line input in Ruby:</p>
<pre><code>> cat input.txt | myprog.rb
> myprog.rb < input.txt
> myprog.rb arg1 arg2 arg3 ...
</code></pre>
<p>What is the best way to do it? In particular I want to deal with blank STDIN, and I hope for an elegant solution.</p>
<pre><code>#!/usr/bin/env ruby
STDIN.read.split("\n").each do |a|
puts a
end
ARGV.each do |b|
puts b
end
</code></pre>
|
[
{
"answer_id": 273415,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/env ruby\n\nuntil ARGV.empty? do\n puts \"From arguments: #{ARGV.shift}\"\nend\n\nwhile a = gets\n puts \"From stdin: #{a}\"\nend\n gets $ cat input.txt | ./myprog.rb\nFrom stdin: line 1\nFrom stdin: line 2\n\n$ ./myprog.rb arg1 arg2 arg3\nFrom arguments: arg1\nFrom arguments: arg2\nFrom arguments: arg3\nhi!\nFrom stdin: hi!\n"
},
{
"answer_id": 273605,
"author": "Magnus Holm",
"author_id": 8791,
"author_profile": "https://Stackoverflow.com/users/8791",
"pm_score": 4,
"selected": false,
"text": "#/usr/bin/env ruby\n\nif $stdin.tty?\n ARGV.each do |file|\n puts \"do something with this file: #{file}\"\n end\nelse\n $stdin.each_line do |line|\n puts \"do something with this line: #{line}\"\n end\nend\n > cat input.txt | ./myprog.rb\ndo something with this line: this\ndo something with this line: is\ndo something with this line: a\ndo something with this line: test\n> ./myprog.rb < input.txt \ndo something with this line: this\ndo something with this line: is\ndo something with this line: a\ndo something with this line: test\n> ./myprog.rb arg1 arg2 arg3\ndo something with this file: arg1\ndo something with this file: arg2\ndo something with this file: arg3\n"
},
{
"answer_id": 273841,
"author": "Jonke",
"author_id": 15638,
"author_profile": "https://Stackoverflow.com/users/15638",
"pm_score": 9,
"selected": false,
"text": "cat #!/usr/bin/env ruby\nputs ARGF.read\n ARGF ARGF.each_with_index do |line, idx|\n print ARGF.filename, \":\", idx, \";\", line\nend\n\n# print all the lines in every file passed via command line that contains login\nARGF.each do |line|\n puts line if line =~ /login/\nend\n ARGF -i #!/usr/bin/env ruby -i\n\nHeader = DATA.read\n\nARGF.each_line do |e|\n puts Header if ARGF.pos - e.length == 0\n puts e\nend\n\n__END__\n#--\n# Copyright (C) 2007 Fancypants, Inc.\n#++\n"
},
{
"answer_id": 5176247,
"author": "Bill Caputo",
"author_id": 642305,
"author_profile": "https://Stackoverflow.com/users/642305",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/env ruby -n\n\n#example.rb\n\nputs \"hello: #{$_}\" #prepend 'hello:' to each line from STDIN\n\n#these will all work:\n# ./example.rb < input.txt\n# cat input.txt | ./example.rb\n# ./example.rb input.txt\n"
},
{
"answer_id": 11403762,
"author": "SwiftMango",
"author_id": 1270003,
"author_profile": "https://Stackoverflow.com/users/1270003",
"pm_score": 4,
"selected": false,
"text": "while STDIN.gets\n puts $_\nend\n\nwhile ARGF.gets\n puts $_\nend\n while(<STDIN>){\n print \"$_\\n\"\n}\n"
},
{
"answer_id": 34906353,
"author": "Richard Nienaber",
"author_id": 9539,
"author_profile": "https://Stackoverflow.com/users/9539",
"pm_score": 1,
"selected": false,
"text": "ARGF ARGV ARGF.each ARGF ARGV File.open(ARGV[0], 'w') do |file|\n ARGV.clear\n\n ARGF.each do |line|\n puts line\n file.write(line)\n end\nend\n"
},
{
"answer_id": 36330607,
"author": "wired00",
"author_id": 629222,
"author_profile": "https://Stackoverflow.com/users/629222",
"pm_score": 1,
"selected": false,
"text": "all_lines = \"\"\nARGV.each do |line|\n all_lines << line + \"\\n\"\nend\nputs all_lines\n"
},
{
"answer_id": 39999281,
"author": "Howard Barina",
"author_id": 4738062,
"author_profile": "https://Stackoverflow.com/users/4738062",
"pm_score": 0,
"selected": false,
"text": "$ cat tstarg.rb\n\nwhile a=(ARGV.shift or (!STDIN.tty? and STDIN.gets) )\n puts a\nend\n $ cat numbers \n1\n2\n3\n4\n5\n$ ./tstarg.rb a b c < numbers\na\nb\nc\n1\n2\n3\n4\n5\n"
},
{
"answer_id": 40547608,
"author": "Jose Alban",
"author_id": 2600638,
"author_profile": "https://Stackoverflow.com/users/2600638",
"pm_score": 2,
"selected": false,
"text": "STDIN.gets.chomp == 'YES'"
},
{
"answer_id": 62784122,
"author": "Dorian",
"author_id": 12544391,
"author_profile": "https://Stackoverflow.com/users/12544391",
"pm_score": 2,
"selected": false,
"text": "STDIN.each_line STDIN.each_line.to_a STDIN.each_line do |line|\n puts line\nend\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35580/"
] |
273,273
|
<p>I'm looking for a small and fast library implementing an HTTP server in .NET</p>
<p>My general requirements are:</p>
<ul>
<li>Supports multiple simultaneous connections</li>
<li>Only needs to support static content (no server side processing)</li>
<li>HTTP only, HTTPS not needed</li>
<li>Preferably be able to serve a page from an in memory source. I want to integrate it into another app to be able to make changing data available via a browser, but I don't want to have to write it to a file on disk first. For example, just pass it a C# string to use as the current page content.</li>
<li>Preferably open source so I can modify it if needed</li>
<li><em>Definitely</em> needs to be free... it's for a personal project with no budget other than my own time. I also want to be able to release the final product that would use this library freely (even if that means complying to the particular OSS license of that library.</li>
</ul>
<p>Edit: To clarify some more, what I need can be REALLY simple. I need to be able to serve essentially 2 documents, which I would like to be served directly from memory. And that's it. Yes, I could write my own, but I wanted to make sure I wasn't doing something that was already available.</p>
|
[
{
"answer_id": 72867512,
"author": "Javid",
"author_id": 492352,
"author_profile": "https://Stackoverflow.com/users/492352",
"pm_score": 0,
"selected": false,
"text": "HttpListener"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
273,275
|
<p>Rails has an awesome way of looking up column names and expected datatypes from the DB, alleviating a lot of programming.</p>
<p>I'm trying to build something like this in C#.NET, because we have large tables that are ever changing. I'll be adding parameters like so:</p>
<pre><code>SqlParameter param = new SqlParameter("parametername", *SqlDbType.Int*);
param.Direction = ParameterDirection.Input;
param.Value = 0;
comm.Parameters.Add(param);
</code></pre>
<p>Notice the SqlDbType. How can I get that? If I get DataColumns from the DataSet, all I can get is System types like System.string.</p>
|
[
{
"answer_id": 273305,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 2,
"selected": false,
"text": "SqlParameter param = new SqlParameter(\"parametername\", value);\n comm.Parameters.Add(new SqlParameter(\"parametername\",value));\n"
},
{
"answer_id": 273317,
"author": "Tinister",
"author_id": 34715,
"author_profile": "https://Stackoverflow.com/users/34715",
"pm_score": 1,
"selected": false,
"text": "INFORMATION_SCHEMA DATA_TYPE INFORMATION_SCHEMA.COLUMNS Enum.Parse"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25538/"
] |
273,283
|
<p>I just added printing capability to a web site using a style sheet (ie. @media print, etc.) and was wondering if I could use a similar method for adding support for mobile devices.</p>
<p>If not, how do I detect a mobile device? My pages are C# (.aspx) and I'd like to scale back the pages for ease of use on a mobile device.</p>
<p>Any advice for me?</p>
<p>EDIT: My wife has a BlackBerry, so at a miminum I'd like to enable our company's web site for that.</p>
|
[
{
"answer_id": 273289,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 4,
"selected": true,
"text": "<style type=\"text/css\">\n @media handheld\n {\n /* handheld styles */\n }\n</style>\n"
},
{
"answer_id": 273291,
"author": "Mat Nadrofsky",
"author_id": 26853,
"author_profile": "https://Stackoverflow.com/users/26853",
"pm_score": 1,
"selected": false,
"text": "public static bool IsMobile(string userAgent)\n{\n userAgent = userAgent.ToLower();\n\n return userAgent.Contains(\"iphone\") |\n userAgent.Contains(\"ppc\") |\n userAgent.Contains(\"windows ce\") |\n userAgent.Contains(\"blackberry\") |\n userAgent.Contains(\"opera mini\") |\n userAgent.Contains(\"mobile\") |\n userAgent.Contains(\"palm\") |\n userAgent.Contains(\"portable\");\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20848/"
] |
273,297
|
<p>Few of us would deny the awesomeness of debuggers, but to make it more useful, some tricks can be used. </p>
<p>For example in Python, you can use <strong><em>pass</em></strong> to do absolutely nothing except to leave you room to put a break point and allow you to observe the values in the Watch window. </p>
<p>In C#, I used to do <strong><em>GC.Collect()</em></strong>, but now I use <strong><em>if (false){}</em></strong></p>
<p>What's your most playful dummy line?</p>
|
[
{
"answer_id": 273303,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "System.Diagnostics.Debugger.Break();\n"
},
{
"answer_id": 273322,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 2,
"selected": false,
"text": "assert(\"breakpoint\");\n __asm__(\"nop\");\n"
},
{
"answer_id": 273457,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 3,
"selected": false,
"text": "volatile int e = 9;\n"
},
{
"answer_id": 273471,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 0,
"selected": false,
"text": "bool bp;\n\nbp = true; //whereever I need to break.\n"
},
{
"answer_id": 273557,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 1,
"selected": false,
"text": ":"
},
{
"answer_id": 273577,
"author": "Rossini",
"author_id": 28281,
"author_profile": "https://Stackoverflow.com/users/28281",
"pm_score": 2,
"selected": false,
"text": "int x = 0;\n"
},
{
"answer_id": 1270087,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Sleep(0) \n i = i;\n"
},
{
"answer_id": 1270093,
"author": "Noon Silk",
"author_id": 154152,
"author_profile": "https://Stackoverflow.com/users/154152",
"pm_score": 2,
"selected": false,
"text": "int moot;\n"
},
{
"answer_id": 3927024,
"author": "Glenn Slayden",
"author_id": 147511,
"author_profile": "https://Stackoverflow.com/users/147511",
"pm_score": 1,
"selected": false,
"text": "public static class Nop { public static void X() { } };\n"
},
{
"answer_id": 4543717,
"author": "greatwolf",
"author_id": 234175,
"author_profile": "https://Stackoverflow.com/users/234175",
"pm_score": 2,
"selected": false,
"text": "__asm int 3;\n"
},
{
"answer_id": 13511182,
"author": "Colonel Panic",
"author_id": 284795,
"author_profile": "https://Stackoverflow.com/users/284795",
"pm_score": 4,
"selected": false,
"text": "{}\n ;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10088/"
] |
273,307
|
<p>I've got a very small standalone vb.net app that gets run automatically. Every now and then it hits an error condition that I want to log and then keep processing. But, this is far too minor a thing to store in the system's main log - I really just want to append a line to a text file.</p>
<p>What's the least stress way to append a line of text to a file (and have it create the file if it's not there) under .net?</p>
|
[
{
"answer_id": 273340,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": " void logMessage(string message)\n {\n string logFileName = \"log.file\";\n\n File.AppendAllText(logFileName,message);\n }\n"
},
{
"answer_id": 273359,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 2,
"selected": false,
"text": "Private Const LOG_FILE As String = \"C:\\Your\\Log.file\"\n\nPrivate Sub AppendMessageToLog(ByVal message As String)\n If Not File.Exists(LOG_FILE) Then\n File.Create(LOG_FILE)\n End If\n\n Using writer As StreamWriter = File.AppendText(LOG_FILE)\n writer.WriteLine(message)\n End Using\nEnd Sub\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.