qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
222,161
|
<p>What interop signature would you use for the following COM method? I am interested particularly in the final two parameters, and whether to try to use <code>MarshalAs</code> with a <code>SizeParamIndex</code> or not.</p>
<pre><code>HRESULT GetOutputSetting(
DWORD dwOutputNum,
LPCWSTR pszName,
WMT_ATTR_DATATYPE* pType,
BYTE* pValue,
WORD* pcbLength
);
</code></pre>
<p>Documentation states:</p>
<blockquote>
<p><strong>pValue</strong> [out] Pointer to a byte buffer containing the value. Pass NULL
to retrieve the length of the buffer
required.</p>
<p><strong>pcbLength</strong> [in, out] On input, pointer to a variable containing the
length of pValue. On output, the
variable contains the number of bytes
in pValue used.</p>
</blockquote>
|
[
{
"answer_id": 222259,
"author": "EFrank",
"author_id": 28572,
"author_profile": "https://Stackoverflow.com/users/28572",
"pm_score": 1,
"selected": false,
"text": "byte[] pValue,\nref ushort pcbLength\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7532/"
] |
222,175
|
<p>I expected <code>A::~A()</code> to be called in this program, but it isn't:</p>
<pre><code>#include <iostream>
struct A {
~A() { std::cout << "~A()" << std::endl; }
};
void f() {
A a;
throw "spam";
}
int main() { f(); }
</code></pre>
<p>However, if I change last line to </p>
<pre><code>int main() try { f(); } catch (...) { throw; }
</code></pre>
<p>then <code>A::~A()</code> <em>is</em> called.</p>
<p>I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is <code>cl /EHa my.cpp</code>.</p>
<p>Is compiler right as usual? What does standard say on this matter?</p>
|
[
{
"answer_id": 37164776,
"author": "light_keeper",
"author_id": 1243244,
"author_profile": "https://Stackoverflow.com/users/1243244",
"pm_score": 2,
"selected": false,
"text": "extern \"C\""
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310/"
] |
222,187
|
<p>What's the best way to determine if the version of the JRE installed on a machine is high enough for the application which the user wants to run? Is there a way of doing it using java-only stuff? I'd like the solution to work on Windows/Linux/MacOSX - if the JRE version is too low a message should be displayed. Currently I'm getting an exception if i try to run it on Java 1.5 (the app is built for Java 1.6). If there's no universal solution, what's the best way to do it on Windows?</p>
|
[
{
"answer_id": 222372,
"author": "jim",
"author_id": 27628,
"author_profile": "https://Stackoverflow.com/users/27628",
"pm_score": 1,
"selected": false,
"text": "Properties sProp = java.lang.System.getProperties();\nString sVersion = sProp.getProperty(\"java.version\");\nsVersion = sVersion.substring(0, 3);\nFloat f = Float.valueOf(sVersion);\nif (f.floatValue() < (float) 1.4) {\n System.out.println(\"Java version too low ....\");\n System.exit(1);\n}\n...\n"
},
{
"answer_id": 222868,
"author": "TREE",
"author_id": 6973,
"author_profile": "https://Stackoverflow.com/users/6973",
"pm_score": 4,
"selected": false,
"text": "System.getProperty(\"java.version\")"
},
{
"answer_id": 225835,
"author": "Mnementh",
"author_id": 21005,
"author_profile": "https://Stackoverflow.com/users/21005",
"pm_score": 3,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<!--\n###############################################################################\n#\n# @(#)draw.jnlp 1.6 02/09/11\n#\n# JNLP File for Draw Demo Application\n#\n###############################################################################\n -->\n\n\n<jnlp spec=\"0.2 1.0\"\n codebase=\"http://java.sun.com/javase/technologies/desktop/javawebstart/apps\"\n href=\"draw.jnlp\">\n <information> \n <title>Draw 4 App</title> \n <vendor>Sun Microsystems, Inc.</vendor>\n <homepage href=\"http://java.sun.com/javase/technologies/desktop/javawebstart/demos.html\"/>\n <description>A minimalist drawing application along the lines of Illustrator</description>\n <description kind=\"short\">Draw Demo Short Description</description>\n <icon href=\"images/draw.jpg\"/>\n <offline-allowed/> \n </information> \n <resources>\n <j2se version=\"1.3+\" href=\"http://java.sun.com/products/autodl/j2se\"/>\n <j2se version=\"1.3+\"/>\n <jar href=\"draw.jar\" main=\"true\" download=\"eager\"/>\n </resources>\n <application-desc main-class=\"Draw\"/>\n</jnlp> \n"
},
{
"answer_id": 1255682,
"author": "lucrussell",
"author_id": 126142,
"author_profile": "https://Stackoverflow.com/users/126142",
"pm_score": 2,
"selected": false,
"text": "java -version:1.6* com.me.MyClass"
},
{
"answer_id": 5662316,
"author": "utpal",
"author_id": 707818,
"author_profile": "https://Stackoverflow.com/users/707818",
"pm_score": 1,
"selected": false,
"text": "var list = deployJava.getJREs();\nvar result = \"\";\nresult = list[0];\nfor (var i=1; i<list.length; i++)\n{\n result += \", \" + list[i];\n} \ndocument.write(\"jre version : \"+result);\n"
},
{
"answer_id": 15312414,
"author": "Alexander Paul Wansiedler",
"author_id": 2015826,
"author_profile": "https://Stackoverflow.com/users/2015826",
"pm_score": 0,
"selected": false,
"text": "Properties props = System.getProperties()\nprops.list(System.out)\n //full list of possible props you can see if u run code above\nString props = System.getProperty(prop)\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7337/"
] |
222,188
|
<p>They are specially annoying when I need to upload to the server a web solution.</p>
<p>Is there a way of configuring SVN to create the _svn folders outside my working directory?
If not, what is the best way to deal with them when you need to copy only the code?</p>
<p><strong>Update:</strong> Using "svn export" command is problematic because there are files that are not under source control but necessary like .dll's, xml data files or database files and they will not be exported. Therefore it would be required to manually copy them in there different subdirectories from the working copy each time.</p>
|
[
{
"answer_id": 222341,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "robocopy {source} {dest} /MIR /XD _svn /XD .svn\n"
},
{
"answer_id": 222350,
"author": "jdecuyper",
"author_id": 296,
"author_profile": "https://Stackoverflow.com/users/296",
"pm_score": 0,
"selected": false,
"text": " <exec>\n <executable>C:\\Archivos de programa\\Windows Resource Kits\\Tools\\robocopy.exe</executable>\n <buildArgs>E:\\CruiseControl\\yourproject\\Code\\trunk\\ E:\\wwwroot\\yourproject *.* /E /XX /XA:H /XO /NDL /NC /NS /NP /XF \"*.cache\" \"*.designer.cs\" \"*.sln\" \"*.msbuild\" \"*.csproj\" \"*.PDB\" \"*.user\" \"*.designer\" /XD .svn App_Code obj Properties</buildArgs>\n <buildTimeoutSeconds>60</buildTimeoutSeconds>\n <successExitCodes>1,0</successExitCodes>\n </exec>\n"
},
{
"answer_id": 13552621,
"author": "visar_uruqi",
"author_id": 1668866,
"author_profile": "https://Stackoverflow.com/users/1668866",
"pm_score": 0,
"selected": false,
"text": "for /f \"tokens=* delims=\" %%i in ('dir /s /b /a:d *.svn') do (\nrd /s /q \"%%i\"\n)\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
] |
222,195
|
<p>I have this piece of code (summarized)...</p>
<pre><code>AnsiString working(AnsiString format,...)
{
va_list argptr;
AnsiString buff;
va_start(argptr, format);
buff.vprintf(format.c_str(), argptr);
va_end(argptr);
return buff;
}
</code></pre>
<p>And, on the basis that pass by reference is preferred where possible, I changed it thusly.</p>
<pre><code>AnsiString broken(const AnsiString &format,...)
{
... the rest, totally identical ...
}
</code></pre>
<p>My calling code is like this:-</p>
<pre><code>AnsiString s1, s2;
s1 = working("Hello %s", "World");
s2 = broken("Hello %s", "World");
</code></pre>
<p>But, s1 contains "Hello World", while s2 has "Hello (null)". I think this is due to the way va_start works, but I'm not exactly sure what's going on.</p>
|
[
{
"answer_id": 222288,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 6,
"selected": true,
"text": "va_start(argptr, format); \n argptr = (va_list) (&format+1);\n AnsiString working_ptr(const AnsiString *format,...)\n{\n ASSERT(format != NULL);\n va_list argptr;\n AnsiString buff;\n\n va_start(argptr, format);\n buff.vprintf(format->c_str(), argptr);\n\n va_end(argptr);\n return buff;\n}\n\n...\n\nAnsiString format = \"Hello %s\";\ns1 = working_ptr(&format, \"World\");\n AnsiString working_dummy(const AnsiString &format, int dummy, ...)\n{\n va_list argptr;\n AnsiString buff;\n\n va_start(argptr, dummy);\n buff.vprintf(format.c_str(), argptr);\n\n va_end(argptr);\n return buff;\n}\n\n...\n\ns1 = working_dummy(\"Hello %s\", 0, \"World\");\n"
},
{
"answer_id": 222314,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "va_start() va_start() <stdarg.h> parmN ... parmN"
},
{
"answer_id": 222918,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 0,
"selected": false,
"text": "alloca(sizeof(class));\nmemcpy(stack, &instance, sizeof(class);\n"
},
{
"answer_id": 17182179,
"author": "York",
"author_id": 671728,
"author_profile": "https://Stackoverflow.com/users/671728",
"pm_score": 1,
"selected": false,
"text": "void not_broken(const string& format,...)\n{\n va_list argptr;\n _asm {\n lea eax, [format];\n add eax, 4;\n mov [argptr], eax;\n }\n\n vprintf(format.c_str(), argptr);\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
222,214
|
<p>In some of our projects, there's an class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to 30 parameters, 28 of which are just being passed into the super constructor.</p>
<p>I'll acknowledge that using automated DI through something like Guice would be nice, but because of some technical reasons, these specific projects are constrained to Java. </p>
<p>A convention of organizing the arguments alphabetically by type doesn't work because if a type is refactored (the Circle you were passing in for argument 2 is now a Shape) it can suddenly be out of order.</p>
<p>This question might be to specific and fraught with "If that's your problem, you're doing it wrong at a design level" criticisms, but I'm just looking for any viewpoints.</p>
|
[
{
"answer_id": 222246,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 4,
"selected": false,
"text": "MyObject obj = new MyObjectBuilder().setXxx(myXxx)\n .setYyy(myYyy)\n .setZzz(myZzz)\n // ... etc.\n .build();\n"
},
{
"answer_id": 222295,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 9,
"selected": true,
"text": "public class StudentBuilder\n{\n private String _name;\n private int _age = 14; // this has a default\n private String _motto = \"\"; // most students don't have one\n\n public StudentBuilder() { }\n\n public Student buildStudent()\n {\n return new Student(_name, _age, _motto);\n }\n\n public StudentBuilder name(String _name)\n {\n this._name = _name;\n return this;\n }\n\n public StudentBuilder age(int _age)\n {\n this._age = _age;\n return this;\n }\n\n public StudentBuilder motto(String _motto)\n {\n this._motto = _motto;\n return this;\n }\n}\n Student s1 = new StudentBuilder().name(\"Eli\").buildStudent();\nStudent s2 = new StudentBuilder()\n .name(\"Spicoli\")\n .age(16)\n .motto(\"Aloha, Mr Hand\")\n .buildStudent();\n"
},
{
"answer_id": 222296,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 5,
"selected": false,
"text": "\nMyClass(String house, String street, String town, String postcode, String country, int foo, double bar) {\n super(String house, String street, String town, String postcode, String country);\n this.foo = foo;\n this.bar = bar;\n \nMyClass(Address homeAddress, int foo, double bar) {\n super(homeAddress);\n this.foo = foo;\n this.bar = bar;\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28038/"
] |
222,217
|
<p>I am currently using...</p>
<pre><code>select Table_Name, Column_name, data_type, is_Nullable
from information_Schema.Columns
</code></pre>
<p>...to determine information about columns in a given database for the purposes of generating a DataAccess Layer.</p>
<p><strong>From where can I retrieve information about if these columns are participants in the primary key of their table?</strong></p>
|
[
{
"answer_id": 222224,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 7,
"selected": true,
"text": "SELECT K.TABLE_NAME ,\n K.COLUMN_NAME ,\n K.CONSTRAINT_NAME\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C\n JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME\n AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG\n AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA\n AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME\nWHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'\n AND K.COLUMN_NAME = 'keycol';\n"
},
{
"answer_id": 222256,
"author": "CindyH",
"author_id": 12897,
"author_profile": "https://Stackoverflow.com/users/12897",
"pm_score": 3,
"selected": false,
"text": "SELECT K.TABLE_NAME, C.CONSTRAINT_TYPE, K.COLUMN_NAME, K.CONSTRAINT_NAME\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C\nJOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K\nON C.TABLE_NAME = K.TABLE_NAME\nAND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG\nAND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA\nAND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME\nWHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'\nORDER BY K.TABLE_NAME, C.CONSTRAINT_TYPE, K.CONSTRAINT_NAME\n"
},
{
"answer_id": 26761701,
"author": "ttacompu",
"author_id": 1305915,
"author_profile": "https://Stackoverflow.com/users/1305915",
"pm_score": 2,
"selected": false,
"text": "select C.Table_Name, C.Column_name, data_type, is_Nullable, U.CONSTRAINT_NAME\nfrom information_Schema.Columns C FULL OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U ON C.COLUMN_NAME = U.COLUMN_NAME\nWHERE C.TABLE_NAME=@TABLENAME\n"
},
{
"answer_id": 56475358,
"author": "mehdi",
"author_id": 1831567,
"author_profile": "https://Stackoverflow.com/users/1831567",
"pm_score": 0,
"selected": false,
"text": "SELECT col.COLUMN_NAME ,\n col.DATA_TYPE ,\n col.CHARACTER_MAXIMUM_LENGTH ln ,\n CAST(ISNULL(j.is_primary, 0) AS BIT) is_primary\nFROM INFORMATION_SCHEMA.COLUMNS col\n LEFT JOIN ( SELECT K.TABLE_NAME ,\n K.COLUMN_NAME ,\n CASE WHEN K.CONSTRAINT_NAME IS NULL THEN 0\n WHEN K.CONSTRAINT_NAME IS NOT NULL THEN 1\n END is_primary\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C\n JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME\n AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG\n AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA\n AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME\n WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'\n AND C.TABLE_NAME = 'tablename'\n ) j ON col.COLUMN_NAME = j.COLUMN_NAME\nWHERE col.TABLE_NAME = 'tablename'\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] |
222,218
|
<p>I want to change a flash object enclosed within with jQuery after an onClick event. The code I wrote, essentially:</p>
<pre><code>$(enclosing div).html('');
$(enclosing div).html(<object>My New Object</object>);
</code></pre>
<p>works in Firefox but not in IE. I would appreciate pointers or suggestions on doing this. Thanks.</p>
|
[
{
"answer_id": 222290,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "empty() $('#mydiv').empty();\n replaceWith(content)"
},
{
"answer_id": 223564,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 0,
"selected": false,
"text": "$().remove()"
},
{
"answer_id": 223613,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 0,
"selected": false,
"text": "function removeObjectInIE(el) {\n var jbo = (typeof(el) == \"string\" ? getElementById(el) : el);\n if (jbo) {\n for (var i in jbo) {\n if (typeof jbo[i] == \"function\") {\n jbo[i] = null;\n }\n }\n jbo.parentNode.removeChild(jbo);\n }\n}\n\nfunction removeSWF(id) {\n var obj = (typeof(id) == \"string\" ? getElementById(id) : id);\n if(obj){\n if (obj.nodeName == \"OBJECT\" || obj.nodeName == \"EMBED\") {\n if (ua.ie && ua.win) {\n if (obj.readyState == 4) {\n removeObjectInIE(id);\n }\n else {\n $(document).ready(function() { removeObjectInIE(id); });\n }\n }\n else {\n obj.parentNode.removeChild(obj);\n }\n }else if(obj.childNodes && obj.childNodes.length > 0){\n for(var i=0;i<obj.childNodes.length;i++){\n removeSWF(obj.childNodes[i]);\n }\n }\n }\n} \n removeSWF(\"mydiv\"); $().ready()"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
222,220
|
<p>After using <a href="http://us.php.net/array_unique" rel="noreferrer"><code>array_unique</code></a>, an array without the duplicate values is removed. However, it appears that the keys are also removed, which leaves gaps in an array with numerical indexes (although is fine for an associative array). If I iterate using a for loop, I have to account for the missing indexes and just copy the keys to a new array, but that seems clumsy.</p>
|
[
{
"answer_id": 222225,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 6,
"selected": true,
"text": "$foo = array_values($foo);"
},
{
"answer_id": 222747,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 1,
"selected": false,
"text": "for ($i = 0; $i < $loopSize; $i++)\n{\nprocess($myArray[$i]);\n}\n foreach($myArray as $key=> $value)\n{\n process($value);\n /** or process($myArray[$key]); */\n}\n\nor even more simply\n\n\nforeach($myArray as $value)\n{\n process($value);\n}\n"
},
{
"answer_id": 3936040,
"author": "jon_darkstar",
"author_id": 475993,
"author_profile": "https://Stackoverflow.com/users/475993",
"pm_score": 0,
"selected": false,
"text": "foreach($myArray as $key=>$val)\n{\n myArray[$key] = myFunction(myArray[$key]);\n}\n $a = getA(); $b = getB();\nforeach($a as $key=>val)\n{\n $sql = \"INSERT INTO table (field1, field2) VALUES ($a[$key], $b[$key])\";\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
222,245
|
<p>Does anyone know a good date parser for different languages/locales. The built-in parser of Java (SimpleDateFormat) is very strict. It should complete missing parts with the current date. </p>
<p>For example </p>
<ul>
<li>if I do not enter the year (only day and month) then the current year should be used. </li>
<li>if the year is 08 then it should not parse 0008 because the current year pattern has 4 digits.</li>
</ul>
<p>Edit: I want to parse the input from a user. For example if the locale date format of the user is "dd.mm.yyyy" and the user type only "12.11." then the parser should accept this as a valid date with the value "12.11.2008". The target is a good usability.</p>
|
[
{
"answer_id": 222282,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 4,
"selected": false,
"text": "parseDate String Date"
},
{
"answer_id": 1268828,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 1,
"selected": false,
"text": "strtotime"
},
{
"answer_id": 50498871,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "java.time.format.DateTimeFormatterBuilder::parseDefaulting DateTimeFormatter DateTimeFormatter DateTimeFormatterBuilder DateTimeFormatter f =\n new DateTimeFormatterBuilder()\n .appendPattern( \"MM-dd\" )\n .parseDefaulting(\n ChronoField.YEAR ,\n ZonedDateTime.now( ZoneId.of( \"America/Montreal\" ) ).getYear()\n )\n .toFormatter() ;\n\nString input = \"01-23\" ;\nLocalDate ld = LocalDate.parse( input , f ) ;\n\nSystem.out.println( ld ) ;\n java.util.Date Calendar SimpleDateFormat java.sql.* Interval YearWeek YearQuarter"
},
{
"answer_id": 67992067,
"author": "Arvind Kumar Avinash",
"author_id": 10819573,
"author_profile": "https://Stackoverflow.com/users/10819573",
"pm_score": 2,
"selected": false,
"text": "DateTimeFormatter [.[uuuu][uu]] DateTimeFormatter import java.time.LocalDate;\nimport java.time.ZoneId;\nimport java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeFormatterBuilder;\nimport java.time.temporal.ChronoField;\nimport java.util.Locale;\nimport java.util.stream.Stream;\n\npublic class Main {\n public static void main(String[] args) {\n // Replace JVM's ZoneId, ZoneId.systemDefault() with the applicable one e.g.\n // ZoneId.of(\"Europe/Berlin\")\n int defaultYear = LocalDate.now(ZoneId.systemDefault()).getYear();\n\n DateTimeFormatter dtf = new DateTimeFormatterBuilder()\n .appendPattern(\"dd.MM[.[uuuu][uu]]\")\n .parseDefaulting(ChronoField.YEAR, defaultYear)\n .toFormatter(Locale.ENGLISH);\n \n // Test\n Stream.of(\n \"12.11\",\n \"12.11.21\",\n \"12.11.2021\"\n ).forEach(s -> System.out.println(LocalDate.parse(s, dtf))); \n }\n}\n 2021-11-12\n2021-11-12\n2021-11-12\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12631/"
] |
222,248
|
<p>When I run this code:</p>
<pre><code>MIXERLINE MixerLine;
memset( &MixerLine, 0, sizeof(MIXERLINE) );
MixerLine.cbStruct = sizeof(MIXERLINE);
MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT;
mmResult = mixerGetLineInfo( (HMIXEROBJ)m_dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE );
</code></pre>
<p>Under XP MixerLine.cChannels comes back as the number of channels that the sound card supports. Often 2, these days often many more.</p>
<p>Under Vista MixerLine.cChannels comes back as one.</p>
<p>I have been then getting a MIXERCONTROL_CONTROLTYPE_VOLUME control and setting the volume for each channel that is supported, and setting the volumne control to different levels on different channels so as to pan music back and forth between the speakers (left to right).</p>
<p>Obviously under Vista this approach isn't working since there is only one channel. I can set the volume and it is for both channels at the same time.</p>
<p>I tried to get a MIXERCONTROL_CONTROLTYPE_PAN for this device, but that was not a valid control.</p>
<p>So, the question for all you MMSystem experts is this: what type of control do I need to get to adjust the left/right balance? Alternately, is there a better way? I would like a solution that works with both XP and Vista.</p>
<p>Computer Details: Running Vista Ultimta 32 bit SP1 and all latest patches. Audio is provided by a Creative Audigy 2 ZS card with 4 speakers attached which can all be properly addressed (controlled) through Vista's sound panel. Driver is latest on Creative's site (SBAX_PCDRV_LB_2_18_0001). The Vista sound is not set to mono, and all channels are visable and controlable from the sound panel.</p>
<p>Running the program in "XP Compatibility Mode" does not change the behaviour of this problem.</p>
|
[
{
"answer_id": 226201,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 0,
"selected": false,
"text": "MIXERCONTROL_CONTROLTYPE_PAN"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17958/"
] |
222,266
|
<p>In an Open Source <a href="http://honeypot.net/project/pgdbf" rel="nofollow noreferrer">program I
wrote</a>, I'm reading binary data (written by another program) from a file and outputting ints, doubles,
and other assorted data types. One of the challenges is that it needs to
run on 32-bit and 64-bit machines of both endiannesses, which means that I
end up having to do quite a bit of low-level bit-twiddling. I know a (very)
little bit about type punning and strict aliasing and want to make sure I'm
doing things the right way.</p>
<p>Basically, it's easy to convert from a char* to an int of various sizes:</p>
<pre><code>int64_t snativeint64_t(const char *buf)
{
/* Interpret the first 8 bytes of buf as a 64-bit int */
return *(int64_t *) buf;
}
</code></pre>
<p>and I have a cast of support functions to swap byte orders as needed, such
as:</p>
<pre><code>int64_t swappedint64_t(const int64_t wrongend)
{
/* Change the endianness of a 64-bit integer */
return (((wrongend & 0xff00000000000000LL) >> 56) |
((wrongend & 0x00ff000000000000LL) >> 40) |
((wrongend & 0x0000ff0000000000LL) >> 24) |
((wrongend & 0x000000ff00000000LL) >> 8) |
((wrongend & 0x00000000ff000000LL) << 8) |
((wrongend & 0x0000000000ff0000LL) << 24) |
((wrongend & 0x000000000000ff00LL) << 40) |
((wrongend & 0x00000000000000ffLL) << 56));
}
</code></pre>
<p>At runtime, the program detects the endianness of the machine and assigns
one of the above to a function pointer:</p>
<pre><code>int64_t (*slittleint64_t)(const char *);
if(littleendian) {
slittleint64_t = snativeint64_t;
} else {
slittleint64_t = sswappedint64_t;
}
</code></pre>
<p>Now, the tricky part comes when I'm trying to cast a char* to a double. I'd
like to re-use the endian-swapping code like so:</p>
<pre><code>union
{
double d;
int64_t i;
} int64todouble;
int64todouble.i = slittleint64_t(bufoffset);
printf("%lf", int64todouble.d);
</code></pre>
<p>However, some compilers could optimize away the "int64todouble.i" assignment
and break the program. Is there a safer way to do this, while considering
that this program must stay optimized for performance, and also that I'd
prefer not to write a parallel set of transformations to cast char* to
double directly? If the union method of punning is safe, should I be
re-writing my functions like snativeint64_t to use it?</p>
<hr />
<p>I ended up using <a href="https://stackoverflow.com/users/13005/">Steve Jessop's</a> answer because the conversion functions re-written to use memcpy, like so:</p>
<pre><code>int64_t snativeint64_t(const char *buf)
{
/* Interpret the first 8 bytes of buf as a 64-bit int */
int64_t output;
memcpy(&output, buf, 8);
return output;
}
</code></pre>
<p>compiled into the exact same assembler as my original code:</p>
<pre><code>snativeint64_t:
movq (%rdi), %rax
ret
</code></pre>
<p>Of the two, the memcpy version more explicitly expresses what I'm trying to do and should work on even the most naive compilers.</p>
<p>Adam, your answer was also wonderful and I learned a lot from it. Thanks for posting!</p>
|
[
{
"answer_id": 222323,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "0xff (((wrongend & 0xff00000000000000LL) >> 56)\n ((wrongend >> 56) & 0xff)\n"
},
{
"answer_id": 222384,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": -1,
"selected": false,
"text": "double d = 3.1234;\nprintf(\"Double %f\\n\", d);\nint64_t i = *(int64_t *)&d;\n// Now i contains the double value as int\ndouble d2 = *(double *)&i;\nprintf(\"Double2 %f\\n\", d2);\n int64_t doubleToInt64(double d)\n{\n return *(int64_t *)&d;\n}\n\ndouble int64ToDouble(int64_t i)\n{\n return *(double *)&i;\n}\n int64_t * intPointer;\n:\n// Init intPointer somehow\n:\ndouble * doublePointer = (double *)intPointer;\n int64_t intValue = 12345;\ndouble doubleValue = int64ToDouble(intValue);\n// The statement below will not change the value of doubleValue!\n// Both are not pointing to the same memory location, both have their\n// own storage space on stack and are totally unreleated.\nintValue = 5678;\n int64_t doubleToInt64(double d)\n{\n return *(int64_t *)&d;\n}\n int64_t doubleToInt64(double d)\n{\n int64_t result;\n memcpy(&result, &d, sizeof(d));\n return result;\n}\n"
},
{
"answer_id": 222533,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 3,
"selected": true,
"text": "int64_t i = slittleint64_t(buffoffset);\ndouble d;\nmemcpy(&d,&i,8); /* might emit no code if you're lucky */\nprintf(\"%lf\", d);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32538/"
] |
222,304
|
<p>I have an ActiveRecord model that I would like to convert to xml, but I do not want all the properties rendered in xml. Is there a parameter I can pass into the render method to keep a property from being rendered in xml? </p>
<p>Below is an example of what I am talking about.</p>
<pre><code>def show
@person = Person.find(params[:id])
respond_to do |format|
format.xml { render :xml => @person }
end
end
</code></pre>
<p>produces the following xml</p>
<pre>
<person>
<name>Paul</name>
<age>25</age>
<phone>555.555.5555</phone>
</person>
</pre>
<p>However, I do not want the phone property to be shown. Is there some parameter in the render method that excludes properties from being rendered in xml? Kind of like the following example</p>
<pre><code>def show
@person = Person.find(params[:id])
respond_to do |format|
format.xml { render :xml => @person, :exclude_attribute => :phone }
end
end
</code></pre>
<p>which would render the following xml</p>
<pre>
<person>
<name>Paul</name>
<age>25</age>
</person>
</pre>
|
[
{
"answer_id": 222357,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 5,
"selected": true,
"text": ":only :except def show\n @person = Person.find(params[:id])\n respond_to do |format|\n format.xml { render :text => @person.to_xml, :except => [:phone] }\n end\nend\n"
},
{
"answer_id": 222636,
"author": "Paul",
"author_id": 215086,
"author_profile": "https://Stackoverflow.com/users/215086",
"pm_score": 2,
"selected": false,
"text": "def show\n @person = Person.find(params[:id])\n respond_to do |format|\n format.xml { render :text => @person.to_xml(:except => [:phone]) }\n end\nend\n"
},
{
"answer_id": 1759327,
"author": "efleming",
"author_id": 462052,
"author_profile": "https://Stackoverflow.com/users/462052",
"pm_score": 3,
"selected": false,
"text": "class Person < ActiveRecord::Base\n def to_xml\n super(:except => [:phone])\n end\n def to_json\n super(:except => [:phone])\n end\nend\n class PeopleController < ApplicationController\n # GET /people\n # GET /people.xml\n def index\n @people = Person.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @people }\n format.json { render :json => @people }\n end\n end\nend\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215086/"
] |
222,309
|
<p>If you provide <code>0</code> as the <code>dayValue</code> in <code>Date.setFullYear</code> you get the last day of the previous month:</p>
<pre><code>d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008
</code></pre>
<p>There is reference to this behaviour at <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setFullYear" rel="noreferrer">mozilla</a>. Is this a reliable cross-browser feature or should I look at alternative methods?</p>
|
[
{
"answer_id": 222329,
"author": "Gad",
"author_id": 25152,
"author_profile": "https://Stackoverflow.com/users/25152",
"pm_score": 6,
"selected": false,
"text": "int_d = new Date(2008, 11+1,1);\nd = new Date(int_d - 1);\n"
},
{
"answer_id": 222439,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 10,
"selected": true,
"text": "var month = 0; // January\nvar d = new Date(2008, month + 1, 0);\nconsole.log(d.toString()); // last day in January IE 6: Thu Jan 31 00:00:00 CST 2008\nIE 7: Thu Jan 31 00:00:00 CST 2008\nIE 8: Beta 2: Thu Jan 31 00:00:00 CST 2008\nOpera 8.54: Thu, 31 Jan 2008 00:00:00 GMT-0600\nOpera 9.27: Thu, 31 Jan 2008 00:00:00 GMT-0600\nOpera 9.60: Thu Jan 31 2008 00:00:00 GMT-0600\nFirefox 2.0.0.17: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)\nFirefox 3.0.3: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)\nGoogle Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)\nSafari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)\n toString()"
},
{
"answer_id": 5301829,
"author": "lebreeze",
"author_id": 658303,
"author_profile": "https://Stackoverflow.com/users/658303",
"pm_score": 5,
"selected": false,
"text": "function daysInMonth(iMonth, iYear)\n{\n return 32 - new Date(iYear, iMonth, 32).getDate();\n}\n"
},
{
"answer_id": 8601423,
"author": "Nigel",
"author_id": 698505,
"author_profile": "https://Stackoverflow.com/users/698505",
"pm_score": 4,
"selected": false,
"text": "function daysInMonth(iMonth, iYear)\n{\n return new Date(iYear, iMonth, 0).getDate();\n}\n"
},
{
"answer_id": 11753952,
"author": "artsylar",
"author_id": 665340,
"author_profile": "https://Stackoverflow.com/users/665340",
"pm_score": 3,
"selected": false,
"text": "lastDateofTheMonth = new Date(year, month, 0)\n new Date(2012, 8, 0)\n Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}\n"
},
{
"answer_id": 13773408,
"author": "orad",
"author_id": 450913,
"author_profile": "https://Stackoverflow.com/users/450913",
"pm_score": 7,
"selected": false,
"text": "var today = new Date();\nvar lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);\n"
},
{
"answer_id": 27947860,
"author": "Gone Coding",
"author_id": 201078,
"author_profile": "https://Stackoverflow.com/users/201078",
"pm_score": 5,
"selected": false,
"text": "new Date() regular expression m Jan=1 m y function getDaysInMonth(m, y) {\n return m===2 ? y & 3 || !(y%25) && y & 15 ? 28 : 29 : 30 + (m+(m>>3)&1);\n}\n m y (m+(m>>3)&1) (5546>>m&1) Jan = 1 = 0001 : 31 days\nFeb = 2 = 0010\nMar = 3 = 0011 : 31 days\nApr = 4 = 0100\nMay = 5 = 0101 : 31 days\nJun = 6 = 0110\nJul = 7 = 0111 : 31 days\nAug = 8 = 1000 : 31 days\nSep = 9 = 1001\nOct = 10 = 1010 : 31 days\nNov = 11 = 1011\nDec = 12 = 1100 : 31 days\n >> 3 ^ m 1 0 & 1 + ^ (m >> 3) + m"
},
{
"answer_id": 27962938,
"author": "Ashish",
"author_id": 303986,
"author_profile": "https://Stackoverflow.com/users/303986",
"pm_score": 0,
"selected": false,
"text": "function getLastDay(y, m) {\n return 30 + (m <= 7 ? ((m % 2) ? 1 : 0) : (!(m % 2) ? 1 : 0)) - (m == 2) - (m == 2 && y % 4 != 0 || !(y % 100 == 0 && y % 400 == 0)); \n}\n"
},
{
"answer_id": 35588684,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "var d = new Date(2012,02,0);\nvar n = d.getDate();\nalert(n);\n"
},
{
"answer_id": 37577289,
"author": "Josue",
"author_id": 3685611,
"author_profile": "https://Stackoverflow.com/users/3685611",
"pm_score": 2,
"selected": false,
"text": "Date.prototype.setToLastDateInMonth = function () {\n\n this.setDate(1);\n this.setMonth(this.getMonth() + 1);\n this.setDate(this.getDate() - 1);\n\n return this;\n}\n"
},
{
"answer_id": 40830796,
"author": "ahmed samra",
"author_id": 7213278,
"author_profile": "https://Stackoverflow.com/users/7213278",
"pm_score": 0,
"selected": false,
"text": "var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate();\nconsole.log(last);"
},
{
"answer_id": 43512796,
"author": "Rudi Strydom",
"author_id": 2080324,
"author_profile": "https://Stackoverflow.com/users/2080324",
"pm_score": 0,
"selected": false,
"text": "var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();\nconsole.log(lastDay);\n"
},
{
"answer_id": 48013274,
"author": "Sujay U N",
"author_id": 5078763,
"author_profile": "https://Stackoverflow.com/users/5078763",
"pm_score": 1,
"selected": false,
"text": "function getLstDayOfMonFnc(date) {\n return new Date(date.getFullYear(), date.getMonth(), 0).getDate()\n}\n\nconsole.log(getLstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 29\nconsole.log(getLstDayOfMonFnc(new Date(2017, 2, 15))) // Output : 28\nconsole.log(getLstDayOfMonFnc(new Date(2017, 11, 15))) // Output : 30\nconsole.log(getLstDayOfMonFnc(new Date(2017, 12, 15))) // Output : 31 function getFstDayOfMonFnc(date) {\n return new Date(date.getFullYear(), date.getMonth(), 1).getDate()\n}\n\nconsole.log(getFstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 1"
},
{
"answer_id": 49378027,
"author": "Himanshu kukreja",
"author_id": 2473318,
"author_profile": "https://Stackoverflow.com/users/2473318",
"pm_score": 2,
"selected": false,
"text": "var d = new Date();\nvar days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\nvar fistDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth(), 1).getDay())];\n var LastDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth() + 1, 0).getDay())]; \nconsole.log(\"First Day :\" + fistDayOfMonth); \nconsole.log(\"Last Day:\" + LastDayOfMonth);\nalert(\"First Day :\" + fistDayOfMonth); \nalert(\"Last Day:\" + LastDayOfMonth);"
},
{
"answer_id": 52229801,
"author": "Eric",
"author_id": 5480967,
"author_profile": "https://Stackoverflow.com/users/5480967",
"pm_score": 4,
"selected": false,
"text": "/**\n* Returns a date set to the begining of the month\n* \n* @param {Date} myDate \n* @returns {Date}\n*/\nfunction beginningOfMonth(myDate){ \n let date = new Date(myDate);\n date.setDate(1)\n date.setHours(0);\n date.setMinutes(0);\n date.setSeconds(0); \n return date; \n}\n\n/**\n * Returns a date set to the end of the month\n * \n * @param {Date} myDate \n * @returns {Date}\n */\nfunction endOfMonth(myDate){\n let date = new Date(myDate);\n date.setDate(1); // Avoids edge cases on the 31st day of some months\n date.setMonth(date.getMonth() +1);\n date.setDate(0);\n date.setHours(23);\n date.setMinutes(59);\n date.setSeconds(59);\n return date;\n}\n begninngOfMonth endOfMonth setDate(0) setMilliseconds()"
},
{
"answer_id": 56305707,
"author": "Yatin Darmwal",
"author_id": 8009021,
"author_profile": "https://Stackoverflow.com/users/8009021",
"pm_score": 2,
"selected": false,
"text": "function _getEndOfMonth(time_stamp) {\n let time = new Date(time_stamp * 1000);\n let month = time.getMonth() + 1;\n let year = time.getFullYear();\n let day = time.getDate();\n switch (month) {\n case 1:\n case 3:\n case 5:\n case 7:\n case 8:\n case 10:\n case 12:\n day = 31;\n break;\n case 4:\n case 6:\n case 9:\n case 11:\n day = 30;\n break;\n case 2:\n if (_leapyear(year))\n day = 29;\n else\n day = 28;\n break\n }\n let m = moment(`${year}-${month}-${day}`, 'YYYY-MM-DD')\n return m.unix() + constants.DAY - 1;\n}\n\nfunction _leapyear(year) {\n return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);\n}\n"
},
{
"answer_id": 57982399,
"author": "Tofandel",
"author_id": 2977175,
"author_profile": "https://Stackoverflow.com/users/2977175",
"pm_score": 1,
"selected": false,
"text": "var date = new Date();\n\nvar first_date = new Date(date); //Make a copy of the date we want the first and last days from\nfirst_date.setUTCDate(1); //Set the day as the first of the month\n\nvar last_date = new Date(first_date); //Make a copy of the calculated first day\nlast_date.setUTCMonth(last_date.getUTCMonth() + 1); //Add a month\nlast_date.setUTCDate(0); //Set the date to 0, this goes to the last day of the previous month\n\nconsole.log(first_date.toJSON().substring(0, 10), last_date.toJSON().substring(0, 10)); //Log the dates with the format yyyy-mm-dd"
},
{
"answer_id": 58690103,
"author": "chou",
"author_id": 3192627,
"author_profile": "https://Stackoverflow.com/users/3192627",
"pm_score": 1,
"selected": false,
"text": "const today = new Date();\n\nlet beginDate = new Date();\n\nlet endDate = new Date();\n\n// fist date of montg\n\nbeginDate = new Date(\n\n `${today.getFullYear()}-${today.getMonth() + 1}-01 00:00:00`\n\n);\n\n// end date of month \n\n// set next Month first Date\n\nendDate = new Date(\n\n `${today.getFullYear()}-${today.getMonth() + 2}-01 :23:59:59`\n\n);\n\n// deducting 1 day\n\nendDate.setDate(0);\n"
},
{
"answer_id": 61734878,
"author": "Gungnir",
"author_id": 1743073,
"author_profile": "https://Stackoverflow.com/users/1743073",
"pm_score": 0,
"selected": false,
"text": "d = new Date()\nconsole.log(d.toString())\nd.setDate(1)\nd.setHours(23, 59, 59, 999)\nd.setMonth(d.getMonth() + 1)\nd.setDate(d.getDate() - 1)\nconsole.log(d.toString())"
},
{
"answer_id": 63480910,
"author": "TIGER",
"author_id": 1564959,
"author_profile": "https://Stackoverflow.com/users/1564959",
"pm_score": 0,
"selected": false,
"text": "$( function() {\n $( \"#datepicker\" ).datepicker();\n $('#getLastDateOfMon').on('click', function(){\n var date = $('#datepicker').val();\n\n // Format 'mm/dd/yy' eg: 12/31/2018\n var parts = date.split(\"/\");\n\n var lastDateOfMonth = new Date();\n lastDateOfMonth.setFullYear(parts[2]);\n lastDateOfMonth.setMonth(parts[0]);\n lastDateOfMonth.setDate(0);\n\n alert(lastDateOfMonth.toLocaleDateString());\n });\n}); <!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n <link rel=\"stylesheet\" href=\"/resources/demos/style.css\">\n <script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n <script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n \n<p>Date: <input type=\"text\" id=\"datepicker\"></p>\n<button id=\"getLastDateOfMon\">Get Last Date of Month </button>\n \n \n</body>\n</html>"
},
{
"answer_id": 65215399,
"author": "Rinku Choudhary",
"author_id": 8897909,
"author_profile": "https://Stackoverflow.com/users/8897909",
"pm_score": 2,
"selected": false,
"text": "var dateNow = new Date(); \nvar firstDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), 1); \nvar lastDate = new Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0);\n var dateNow= new Date(); \nvar firstDate=moment(new Date(dateNow.getFullYear(),dateNow.getMonth(), 1)).format(\"DD-MM-YYYY\"); \nvar currentDate = moment(new Date()).format(\"DD-MM-YYYY\"); //to get the current date var lastDate = moment(new\n Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0)).format(\"DD-MM-YYYY\"); //month last date\n"
},
{
"answer_id": 66575167,
"author": "gshoanganh",
"author_id": 4423329,
"author_profile": "https://Stackoverflow.com/users/4423329",
"pm_score": 0,
"selected": false,
"text": "var date = new Date();\nconsole.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));\n"
},
{
"answer_id": 66805242,
"author": "SKM",
"author_id": 11310328,
"author_profile": "https://Stackoverflow.com/users/11310328",
"pm_score": 0,
"selected": false,
"text": "var d = new Date();\nconst year = d.getFullYear();\nconst month = d.getMonth();\n\nconst lastDay = new Date(year, month +1, 0).getDate();\nconsole.log(lastDay);\n"
},
{
"answer_id": 69096049,
"author": "Aaron Dunigan AtLee",
"author_id": 10332984,
"author_profile": "https://Stackoverflow.com/users/10332984",
"pm_score": 3,
"selected": false,
"text": "var last = new Date(date)\nlast.setMonth(last.getMonth() + 1) // This is the wrong way to do it.\nlast.setDate(0)\n date date 07/31/21 last.setMonth(last.getMonth() + 1) 31 08/31/21 09/01/21 last.setDate(0) 08/31/21 07/31/21"
},
{
"answer_id": 72694468,
"author": "Soulduck",
"author_id": 6657314,
"author_profile": "https://Stackoverflow.com/users/6657314",
"pm_score": 0,
"selected": false,
"text": "end_date = new Date(2018, 3, 1).toISOString().split('T')[0]\nconsole.log(end_date)"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
222,319
|
<p>I have a query which is starting to cause some concern in my application. I'm trying to understand this EXPLAIN statement better to understand where indexes are potentially missing:</p>
<pre>
+----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+
| 1 | SIMPLE | s | ref | client_id | client_id | 4 | const | 102 | Using temporary; Using filesort |
| 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | www_foo_com.s.user_id | 1 | |
| 1 | SIMPLE | a | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | Using index |
| 1 | SIMPLE | h | ref | email_id | email_id | 4 | www_foo_com.a.email_id | 10 | Using index |
| 1 | SIMPLE | ph | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | Using index |
| 1 | SIMPLE | em | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | |
| 1 | SIMPLE | pho | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | |
| 1 | SIMPLE | c | ALL | userfield | NULL | NULL | NULL | 1108 | |
+----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+
8 rows in set (0.00 sec)
</pre>
<p>I'm trying to understand where my indexes are missing by reading this EXPLAIN statement. Is it fair to say that one can understand how to optimize this query without seeing the query at all and just look at the results of the EXPLAIN?</p>
<p>It appears that the ALL scan against the 'c' table is the achilles heel. What's the best way to index this based on constant values as recommended on MySQL's documentation? |</p>
<p>Note, I also added an index to userfield in the cdr table and that hasn't done much good either.</p>
<p>Thanks.</p>
<p>--- edit ---</p>
<p>Here's the query, sorry -- don't know why I neglected to include it the first pass through.</p>
<pre><code>SELECT s.`session_id` id,
DATE_FORMAT(s.`created`,'%m/%d/%Y') date,
u.`name`,
COUNT(DISTINCT c.id) calls,
COUNT(DISTINCT h.id) emails,
SEC_TO_TIME(MAX(DISTINCT c.duration)) duration,
(COUNT(DISTINCT em.email_id) + COUNT(DISTINCT pho.phone_id) > 0) status
FROM `fa_sessions` s
LEFT JOIN `fa_users` u ON s.`user_id`=u.`user_id`
LEFT JOIN `fa_email_aliases` a ON a.session_id = s.session_id
LEFT JOIN `fa_email_headers` h ON h.email_id = a.email_id
LEFT JOIN `fa_phones` ph ON ph.session_id = s.session_id
LEFT JOIN `fa_email_aliases` em ON em.session_id = s.session_id AND em.status = 1
LEFT JOIN `fa_phones` pho ON pho.session_id = s.session_id AND pho.status = 1
LEFT JOIN `cdr` c ON c.userfield = ph.phone_id
WHERE s.`partner_id`=1
GROUP BY s.`session_id`
</code></pre>
|
[
{
"answer_id": 225976,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 1,
"selected": false,
"text": "sessions partner_id=1 partner_id, sessions users user_id sessions phones status=1 session_id status sessions phones session_id phone_id phones cdr userfield sessions email_aliases status=1 session_id status sessions email_aliases session_id email_id email_aliases email_headers email_id session_id phone_id email_id fa_sessions ( partner_id, session_id ) \nfa_users ( user_id ) \nfa_email_aliases ( session_id, email_id ) \nfa_email_headers ( email_id ) \nfa_email_aliases ( session_id, status ) \nfa_phones ( session_id, status, phone_id ) \ncdr ( userfield ) \n fa_email_aliases ( session_id, status, email_id )"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
222,339
|
<p>Is there any performance impact or any kind of issues?
The reason I am doing this is that we are doing some synchronization between two set of DBs with similar tables and we want to avoid duplicate PK errors when synchronizing data.</p>
|
[
{
"answer_id": 222351,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": "(CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT)\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25368/"
] |
222,348
|
<p>I have a list of about 600 jobs that I can't delete from the command line because they are attached to changelists. The only way I know how to detach them is via the GUI, but that would take forever. Does anyone know a better (i.e., faster) way?</p>
|
[
{
"answer_id": 222657,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 3,
"selected": true,
"text": "p4 fixes > tmp.txt\n job005519 fixed by change 3177 on 2007/11/06 by raven@raven1 (closed)\njob005552 fixed by change 3320 on 2007/12/11 by raven@raven1 (closed)\njob005552 fixed by change 3318 on 2007/12/10 by raven@raven1 (closed)\n...\n p4 fix -d -c 3177 job005519\np4 fix -d -c 3320 job005552\np4 fix -d -c 3318 job005552\n...\n p4 jobs > tmp.txt\n"
},
{
"answer_id": 256406,
"author": "Syeberman",
"author_id": 14576,
"author_profile": "https://Stackoverflow.com/users/14576",
"pm_score": 0,
"selected": false,
"text": "p4 fixes -c <changenum> | p4 -x - job -d\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
] |
222,370
|
<p>I'm preparing a class on Visual Basic 2005 targeting Visual Basic 6 programmers migrating to the .NET platform.<br /><br/>
I would like a word of advice about whether to recommend them to always enable <strong>Option Strict</strong> or not.<br /><br/>
I've worked exclusively with C-style programming languages, mostly Java and C#, so for me <strong>explicit casting</strong> is something I always expect I have to do, since it's never been an option.<br/>However I recognize the value of working with a language that has built-in support for <strong>late-binding</strong>, because not having to be excessively explicit about types in the code indeed saves time. This is further proved by the popular diffusion of <strong>dynamic typed languages</strong>, even on the .NET platform with the Dynamic Language Runtime.
<br><br/>
With this in mind, should someone who is approaching .NET for the first time using VB.NET and with a VB6 background be encouraged to get into the mindset of <strong>having to work with compile-time type checking</strong> because that's the "best practice" in the CLR? Or is it "OK" to continue enjoying the benefits of late-binding?</p>
|
[
{
"answer_id": 222458,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "Option Strict Option Strict Option Strict On Option Strict"
},
{
"answer_id": 222478,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": true,
"text": "Dim Function LEN() REPLACE() TRIM() oMyObject sMyString AndAlso OrElse CreateObject() IEnumeralbe(Of T) ArrayList"
},
{
"answer_id": 969317,
"author": "MarkJ",
"author_id": 15639,
"author_profile": "https://Stackoverflow.com/users/15639",
"pm_score": 2,
"selected": false,
"text": "Option Strict Option Strict Option Strict"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26396/"
] |
222,375
|
<p>I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the <a href="http://effbot.org/zone/element-xpath.htm" rel="noreferrer">Documentation</a></p>
<p>Here's some sample code</p>
<p><strong>XML</strong></p>
<pre><code><root>
<target name="1">
<a></a>
<b></b>
</target>
<target name="2">
<a></a>
<b></b>
</target>
</root>
</code></pre>
<p><strong>Python</strong></p>
<pre><code>def parse(document):
root = et.parse(document)
for target in root.findall("//target[@name='a']"):
print target._children
</code></pre>
<p>I am receiving the following Exception:</p>
<pre><code>expected path separator ([)
</code></pre>
|
[
{
"answer_id": 16105230,
"author": "Albert",
"author_id": 1812813,
"author_profile": "https://Stackoverflow.com/users/1812813",
"pm_score": 5,
"selected": false,
"text": "//target .//target //... @name key=value target[a] root.findall(\".//target\") root.findall(\".//target/a\") root.findall(\".//target[a]\") root.findall(\".//target[@name='1']\") root.findall(\".//target[a][@name='1']\") root.findall(\".//target[@name='1']/a\")"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
] |
222,376
|
<p>Using MVC with an observer pattern, if a user action requires polling a device (such as a camera) for data, should the polling be done in the Controller and the result passed off the Model or should a request be sent to the Model and the Model itself performs the polling.</p>
<p>This question is my attempt to reconcile everything I am reading that touts the "skinny Controllers" maxim with my gut intuition that the Model should only be acting on data not acquiring it.</p>
<p>(Note: This question <em>might</em> be subjective. I'm not entirely sure that there is a one-true-answer to this question. If not, feel free to retag as I will be very interested to hear opinions on the subject.)</p>
|
[
{
"answer_id": 16105230,
"author": "Albert",
"author_id": 1812813,
"author_profile": "https://Stackoverflow.com/users/1812813",
"pm_score": 5,
"selected": false,
"text": "//target .//target //... @name key=value target[a] root.findall(\".//target\") root.findall(\".//target/a\") root.findall(\".//target[a]\") root.findall(\".//target[@name='1']\") root.findall(\".//target[a][@name='1']\") root.findall(\".//target[@name='1']/a\")"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24608/"
] |
222,383
|
<p>Is there an open source or public domain framework that can document shell scripts similar to what JavaDoc produces? I don't need to limit this just to a specific flavor of shell script, ideally I would like a generic framework for documenting API or command line type commands on a web page that is easy to extend or even better is self documenting.</p>
|
[
{
"answer_id": 222506,
"author": "Steve",
"author_id": 27893,
"author_profile": "https://Stackoverflow.com/users/27893",
"pm_score": 2,
"selected": false,
"text": ": : <<=cut =cut podtest.sh #!/bin/dash\n\necho This is a plain shell script\necho Followed by POD documentation\n\n: <<=cut\n=pod\n=head1 NAME\n\n podtest.sh - Example shell script with embedded POD documentation\n No rights Reserved\n\n=cut\n pod2man podtest.sh >/usr/local/share/man/man1/podtest.sh.1\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14680/"
] |
222,385
|
<p>Does anyone know what the character entity for a tab is in xhtml?
(Um if there is one)...</p>
|
[
{
"answer_id": 222395,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 3,
"selected": false,
"text": "	"
},
{
"answer_id": 222407,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "term\n definition goes here\n\nterm\n definition goes here\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18149/"
] |
222,403
|
<p>I have the following interface:</p>
<pre><code>internal interface IRelativeTo<T> where T : IObject
{
T getRelativeTo();
void setRelativeTo(T relativeTo);
}
</code></pre>
<p>and a bunch of classes that (should) implement it, such as:</p>
<pre><code>public class AdminRateShift : IObject, IRelativeTo<AdminRateShift>
{
AdminRateShift getRelativeTo();
void setRelativeTo(AdminRateShift shift);
}
</code></pre>
<p>I realise that these three are not the same:</p>
<pre><code>IRelativeTo<>
IRelativeTo<AdminRateShift>
IRelativeTo<IObject>
</code></pre>
<p>but nonetheless, I need a way to work with all the different classes like AdminRateShift (and FXRateShift, DetRateShift) that should all implement IRelativeTo. Let's say I have a function which returns AdminRateShift as an Object:</p>
<pre><code>IRelativeTo<IObject> = getObjectThatImplementsRelativeTo(); // returns Object
</code></pre>
<p>By programming against the interface, I can do what I need to, but I can't actually cast the Object to IRelativeTo so I can use it.</p>
<p>It's a trivial example, but I hope it will clarify what I am trying to do.</p>
|
[
{
"answer_id": 222423,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 4,
"selected": false,
"text": "void MyFunction<T>(IRelativeTo<T> sth) where T : IObject\n{}\n"
},
{
"answer_id": 222426,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "internal interface IRelativeTo\n{\n object getRelativeTo(); // or maybe something else non-generic\n void setRelativeTo(object relativeTo);\n}\ninternal interface IRelativeTo<T> : IRelativeTo\n where T : IObject\n{\n new T getRelativeTo();\n new void setRelativeTo(T relativeTo);\n}\n void DoSomething<T>() where T : IObject\n{\n IRelativeTo<IObject> foo = // etc\n}\n IRelativeTo<T> DoSomething() DoSomething(foo);\n DoSomething<SomeType>(foo);\n"
},
{
"answer_id": 222546,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "interface IRelativeTo\n {\n IObject getRelativeTo();\n void setRelativeTo(IObject relativeTo)\n }\n abstract class RelativeTo<T> : IRelativeTo where T : IObject\n { \n public virtual T getRelativeTo() {return default(T);}\n\n public virtual void setRelativeTo(T relativeTo) {}\n\n IObject IRelativeTo.getRelativeTo() {return this.getRelativeTo(); }\n\n void IRelativeTo.setRelativeTo(IObject relativeTo) \n { this.setRelativeTo((T) relativeTo);\n }\n }\n\nclass AdminRateShift : RelativeTo<AdminRateShift>, IObject {}\n IRelativeTo irt = new AdminRateShift();\n IObject o = irt.getRelativeTo();\n irt.setRelativeTo(o);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3851/"
] |
222,413
|
<p>I have a undirected graph with about 100 nodes and about 200 edges. One node is labelled 'start', one is 'end', and there's about a dozen labelled 'mustpass'.</p>
<p>I need to find the shortest path through this graph that starts at 'start', ends at 'end', <strong>and passes through all of the 'mustpass' nodes (in any order).</strong></p>
<p>( <a href="http://3e.org/local/maize-graph.png" rel="noreferrer">http://3e.org/local/maize-graph.png</a> / <a href="http://3e.org/local/maize-graph.dot.txt" rel="noreferrer">http://3e.org/local/maize-graph.dot.txt</a> is the graph in question - it represents a corn maze in Lancaster, PA)</p>
|
[
{
"answer_id": 228248,
"author": "ShreevatsaR",
"author_id": 4958,
"author_profile": "https://Stackoverflow.com/users/4958",
"pm_score": 7,
"selected": true,
"text": "//Precomputation: Find all pairs shortest paths, e.g. using Floyd-Warshall\nn = number of nodes\nfor i=1 to n: for j=1 to n: d[i][j]=INF\nfor k=1 to n:\n for i=1 to n:\n for j=1 to n:\n d[i][j] = min(d[i][j], d[i][k] + d[k][j])\n//That *really* gives the shortest distance between every pair of nodes! :-)\n\n//Now try all permutations\nshortest = INF\nfor each permutation a[1],a[2],...a[k] of the 'mustpass' nodes:\n shortest = min(shortest, d['start'][a[1]]+d[a[1]][a[2]]+...+d[a[k]]['end'])\nprint shortest\n"
},
{
"answer_id": 63650370,
"author": "Hissaan Ali",
"author_id": 6737387,
"author_profile": "https://Stackoverflow.com/users/6737387",
"pm_score": 1,
"selected": false,
"text": "s k1 k2 k3 e dijkstras(s, k1) + dijkstras(k1, k2) + dijkstras(k2, k3) + dijkstras(k3, 3)"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30014/"
] |
222,414
|
<p>I've got a PHP script that needs to invoke a shell script but doesn't care at all about the output. The shell script makes a number of SOAP calls and is slow to complete, so I don't want to slow down the PHP request while it waits for a reply. In fact, the PHP request should be able to exit without terminating the shell process.</p>
<p>I've looked into the various <code>exec()</code>, <code>shell_exec()</code>, <code>pcntl_fork()</code>, etc. functions, but none of them seem to offer exactly what I want. (Or, if they do, it's not clear to me how.) Any suggestions?</p>
|
[
{
"answer_id": 222445,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 9,
"selected": true,
"text": "& exec \" > /dev/null 2>/dev/null &\"\n stdio > stderr 2> /dev/null \" &> /dev/null &\"\n"
},
{
"answer_id": 223745,
"author": "Czimi",
"author_id": 3906,
"author_profile": "https://Stackoverflow.com/users/3906",
"pm_score": 6,
"selected": false,
"text": "<?php\n `echo \"the command\"|at now`;\n?>\n"
},
{
"answer_id": 223770,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 5,
"selected": false,
"text": "$cmd = 'nohup nice -n 10 php -f php/file.php > log/file.log & printf \"%u\" $!';\n$pid = shell_exec($cmd);\n"
},
{
"answer_id": 223831,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 3,
"selected": false,
"text": "mycommand -someparam somevalue &\n start mycommand -someparam somevalue\n"
},
{
"answer_id": 271453,
"author": "Ronald Conco",
"author_id": 16092,
"author_profile": "https://Stackoverflow.com/users/16092",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/php -q"
},
{
"answer_id": 290428,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": " $pid=pcntl_fork();\n if($pid==0)\n {\n posix_setsid();\n pcntl_exec($cmd,$args,$_ENV);\n // child becomes the standalone detached process\n }\n\n // parent's stuff\n exit();\n"
},
{
"answer_id": 290487,
"author": "geocar",
"author_id": 37507,
"author_profile": "https://Stackoverflow.com/users/37507",
"pm_score": 1,
"selected": false,
"text": "#!/bin/sh\nmkfifo trigger\nwhile true; do\n read < trigger\n long_running_task\ndone\n PIPE_BUF write() $REPLY"
},
{
"answer_id": 3284765,
"author": "philfreo",
"author_id": 137067,
"author_profile": "https://Stackoverflow.com/users/137067",
"pm_score": 3,
"selected": false,
"text": "/** \n * Asynchronously execute/include a PHP file. Does not record the output of the file anywhere. \n * Relies on the PHP_PATH config constant.\n *\n * @param string $filename file to execute\n * @param string $options (optional) arguments to pass to file via the command line\n */ \nfunction asyncInclude($filename, $options = '') {\n exec(PHP_PATH . \" -f {$filename} {$options} >> /dev/null &\");\n}\n PHP_PATH define('PHP_PATH', '/opt/bin/php5')"
},
{
"answer_id": 9199031,
"author": "Gordon Forsythe",
"author_id": 478708,
"author_profile": "https://Stackoverflow.com/users/478708",
"pm_score": 2,
"selected": false,
"text": "shell_exec('./myscript.php | at now & disown')\n"
},
{
"answer_id": 40243588,
"author": "LucaM",
"author_id": 1412157,
"author_profile": "https://Stackoverflow.com/users/1412157",
"pm_score": 5,
"selected": false,
"text": "function execInBackground($cmd) {\n if (substr(php_uname(), 0, 7) == \"Windows\"){\n pclose(popen(\"start /B \". $cmd, \"r\")); \n }\n else {\n exec($cmd . \" > /dev/null &\"); \n }\n} \n"
},
{
"answer_id": 41260383,
"author": "LF00",
"author_id": 6521116,
"author_profile": "https://Stackoverflow.com/users/6521116",
"pm_score": 1,
"selected": false,
"text": "proc_open() $descriptorspec = array(\n 0 => array(\"pipe\", \"r\"),\n 1 => array(\"pipe\", \"w\"),\n 2 => array(\"pipe\", \"w\") //here curaengine log all the info into stderror\n );\n $command = 'ping stackoverflow.com';\n $process = proc_open($command, $descriptorspec, $pipes);\n"
},
{
"answer_id": 46677126,
"author": "Anton Pelykh",
"author_id": 5556633,
"author_profile": "https://Stackoverflow.com/users/5556633",
"pm_score": 3,
"selected": false,
"text": "use Symfony\\Component\\Process\\Process;\n\n$process = new Process('ls -lsa');\n// ... run process in background\n$process->start();\n\n// ... do other things\n\n// ... if you need to wait\n$process->wait();\n\n// ... do things after the process has finished\n"
},
{
"answer_id": 73696227,
"author": "Kamshory",
"author_id": 17131216,
"author_profile": "https://Stackoverflow.com/users/17131216",
"pm_score": 0,
"selected": false,
"text": " > /dev/null 2>/dev/null & proc_open \nfunction run_php_async($value, $is_windows)\n{\n if($is_windows)\n {\n $command = 'php -q '.$value.\" \";\n echo 'COMMAND '.$command.\"\\r\\n\";\n proc_open($command, [], $pipe); \n }\n else\n {\n $command = 'php -q '.$value.\" > /dev/null 2>/dev/null &\";\n echo 'COMMAND '.$command.\"\\r\\n\";\n shell_exec($command); \n }\n}\n$tasks = array();\n\n$tasks[] = 'f1.php';\n$tasks[] = 'f2.php';\n$tasks[] = 'f3.php';\n$tasks[] = 'f4.php';\n$tasks[] = 'f5.php';\n$tasks[] = 'f6.php';\n\n$is_windows = true;\n\nforeach($tasks as $key=>$value)\n{\n run_php_async($value, $is_windows);\n echo 'STARTED AT '.date('H:i:s').\"\\r\\n\";\n}\n\n <?php\nsleep(mt_rand(1, 10));\nfile_put_contents(__FILE__.\".txt\", time());\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103/"
] |
222,442
|
<p>I have a database table on a development server that is now fully populated after I set it running with an import routine for a CSV file containing 1.4 million rows.</p>
<p>I ran the Database Publishing Wizard on the table, and now I have a 286MB SQL script on my local machine. The problem is, I can't figure out how to run it. If I load it into SQL Server Management Studio Express I get an alert window that says "The operation could not be completed".</p>
<p>Any ideas on how I can get this SQL script to run?</p>
|
[
{
"answer_id": 222451,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 7,
"selected": false,
"text": "sqlcmd -S myServer\\instanceName -i C:\\myScript.sql\n"
},
{
"answer_id": 29824540,
"author": "PaloDravecky",
"author_id": 2366116,
"author_profile": "https://Stackoverflow.com/users/2366116",
"pm_score": 3,
"selected": false,
"text": "-f sqlcmd -S myServer\\instanceName -d databaseName -i C:\\myScript.sql -f 65001 -f 65001"
},
{
"answer_id": 57062759,
"author": "Kms",
"author_id": 3663495,
"author_profile": "https://Stackoverflow.com/users/3663495",
"pm_score": 1,
"selected": false,
"text": "bcp.exe [Source_DataBase_Name].[dbo].[TableName] OUT \"C:\\Temp\\TableName.bcp\" -S \"Computer Name\" -U \"SQL Server UserName\" -P \"SQL Server Password\" -n -q \n bcp.exe [Destination_DataBase_Name].[dbo].[TableName] IN \"C:\\Temp\\TableName.bcp\" -S \"Computer Name\" -U \"SQL Server UserName\" -P \"SQL Server Password\" -n -q \n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
222,450
|
<p>I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use <code>win32com.client.Dispatch</code>. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:</p>
<pre><code>import win32com.client
app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok
app2 = win32com.client.Dispatch( 'Word.Application' ) # ok
app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error
</code></pre>
<p>Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?</p>
|
[
{
"answer_id": 223002,
"author": "Dustin Wyatt",
"author_id": 23972,
"author_profile": "https://Stackoverflow.com/users/23972",
"pm_score": 2,
"selected": false,
"text": "import win32com.client\noAutoItX = win32com.client.Dispatch( \"AutoItX3.Control\" )\n\noAutoItX.Opt(\"WinTitleMatchMode\", 2) #Match text anywhere in a window title\n\nwidth = oAutoItX.WinGetClientSizeWidth(\"Firefox\")\nheight = oAutoItX.WinGetClientSizeHeight(\"Firefox\")\n\nprint width, height\n"
},
{
"answer_id": 223886,
"author": "ryan_s",
"author_id": 13728,
"author_profile": "https://Stackoverflow.com/users/13728",
"pm_score": 3,
"selected": true,
"text": ">>> import win32com.client\n>>> b = win32com.client.Dispatch('VisualStudio.DTE')\n>>> b\n<COMObject VisualStudio.DTE>\n>>> b.name\nu'Microsoft Visual Studio'\n>>> b.Version\nu'8.0'\n"
},
{
"answer_id": 982565,
"author": "minty",
"author_id": 4491,
"author_profile": "https://Stackoverflow.com/users/4491",
"pm_score": 2,
"selected": false,
"text": "import comtypes.client as client\n\nvs = client.CreateObject('VisualStudio.DTE')\n\ncommands = [command for command in vs.Commands if bool(command.Name) or bool(command.Bindings)]\ncommands.sort(key=lambda cmd : cmd.Name)\n\nf= open('bindings.csv','w')\n\nfor command in commands:\n f.write(command.Name+\",\" +\";\".join(command.Bindings)+ \"\\n\")\n\nf.close()\n"
},
{
"answer_id": 20095416,
"author": "Dzmitry Lahoda",
"author_id": 173073,
"author_profile": "https://Stackoverflow.com/users/173073",
"pm_score": 0,
"selected": false,
"text": "Visual Studio IronPython CLR COM \nimport clr\nimport System\n\nt = System.Type.GetTypeFromProgID(\"AutoItX3.Control\")\noAutoItX = System.Activator.CreateInstance(t)\n\noAutoItX.Opt(\"WinTitleMatchMode\", 2)\n\nwidth = oAutoItX.WinGetClientSizeWidth(\"IronPythonApplication1 - Microsoft Visual Studio (Administrator)\")\nheight = oAutoItX.WinGetClientSizeHeight(\"IronPythonApplication1 - Microsoft Visual Studio (Administrator)\")\n\nprint width, height\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] |
222,453
|
<p>I have a property on a domain object that is declared in a many-to-one element. The basic syntax of this property looks like this:</p>
<pre><code><many-to-one name="propertyName" class="propertyClass" fetch="select" not-found="ignore" lazy="proxy" />
</code></pre>
<p>Now, the idea is to have Hibernate NOT eagerly fetch this property. It may be null, so the not-found ignore is set.</p>
<p>But, Hibernate, upon loading the class containing this association, takes it upon itself to load the actual class (not even a proxy) instance when the parent class is loaded. Since some properties are over 1MB in size, they take up a lot of the heap space.</p>
<p>If, however, not-found is set to exception (or defaulted to exception), the parent classes which have this property do load a proxy!</p>
<p>How can I stop hibernate from not loading a proxy, while still allowing this property to be null?</p>
<p>I found lazy=no-proxy, but the documentation talks about some sort of bytecode modification and doesn't go into any details. Can someone help me out?</p>
<p>If it matters, it is the Java version of Hibernate, and it is at least version 3 (I can look up the actual version if it helps, but it is Hibernate 3+ for now).</p>
<p>I didn't specify earlier, but the Java version is 1.4. So, Java annotations aren't supported.</p>
|
[
{
"answer_id": 838676,
"author": "rudolfson",
"author_id": 60127,
"author_profile": "https://Stackoverflow.com/users/60127",
"pm_score": 0,
"selected": false,
"text": "constrained=\"true\" null <many-to-one name=\"haendler\" column=\"VERK_HAENDLOID\" lazy=\"proxy\" /> constrained=\"true\""
},
{
"answer_id": 1314748,
"author": "Civil Disobedient",
"author_id": 160472,
"author_profile": "https://Stackoverflow.com/users/160472",
"pm_score": 2,
"selected": false,
"text": "<property name=\"src\" value=\"/your/src/directory\"/><!-- path of the source files -->\n<property name=\"libs\" value=\"/your/libs/directory\"/><!-- path of your libraries -->\n<property name=\"destination\" value=\"/your/build/directory\"/><!-- path of your build directory -->\n\n<fileset id=\"applibs\" dir=\"${libs}\">\n <include name=\"hibernate3.jar\" />\n <!-- include any other libraries you'll need here -->\n</fileset>\n\n<target name=\"compile\">\n <javac srcdir=\"${src}\" destdir=\"${destination}\" debug=\"yes\">\n <classpath>\n <fileset refid=\"applibs\"/>\n </classpath>\n </javac>\n</target>\n\n<target name=\"instrument\" depends=\"compile\">\n <taskdef name=\"instrument\" classname=\"org.hibernate.tool.instrument.javassist.InstrumentTask\">\n <classpath>\n <fileset refid=\"applibs\"/>\n </classpath>\n </taskdef>\n\n <instrument verbose=\"true\">\n <fileset dir=\"${destination}\">\n <!-- substitute the package where you keep your domain objs -->\n <include name=\"/com/mycompany/domainobjects/*.class\"/>\n </fileset>\n </instrument>\n</target>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8026/"
] |
222,455
|
<p>Here's some background on what I'm trying to do:</p>
<ol>
<li>Open a serial port from a mobile device to a Bluetooth printer.</li>
<li>Send an EPL/2 form to the Bluetooth printer, so that it understands how to treat the data it is about to receive.</li>
<li>Once the form has been received, send some data to the printer which will be printed on label stock.</li>
<li>Repeat step 3 as many times as necessary for each label to be printed.</li>
</ol>
<p>Step 2 only happens the first time, since the form does not need to precede each label. My issue is that when I send the form, if I send the label data too quickly it will not print. Sometimes I get "Bluetooth Failure: Radio Non-Operational" printed on the label instead of the data I sent.</p>
<p>I have found a way around the issue by doing the following:</p>
<pre><code>for (int attempt = 0; attempt < 3; attempt++)
{
try
{
serialPort.Write(labelData);
break;
}
catch (TimeoutException ex)
{
// Log info or display info based on ex.Message
Thread.Sleep(3000);
}
}
</code></pre>
<p>So basically, I can catch a TimeoutException and retry the write method after waiting a certain amount of time (three seconds seems to work all the time, but any less and it seems to throw the exception every attempt). After three attempts I just assume the serial port has something wrong and let the user know.</p>
<p>This way seems to work ok, but I'm sure there's a better way to handle this. There are a few properties in the SerialPort class that I think I need to use, but I can't really find any good documentation or examples of how to use them. I've tried playing around with some of the properties, but none of them seem to do what I'm trying to achieve. </p>
<p>Here's a list of the properties I have played with:</p>
<ul>
<li>CDHolding </li>
<li>CtsHolding</li>
<li>DsrHolding</li>
<li>DtrEnable</li>
<li>Handshake</li>
<li>RtsEnable</li>
</ul>
<p>I'm sure some combination of these will handle what I'm trying to do more gracefully. </p>
<p>I'm using C# (2.0 framework), a Zebra QL 220+ Bluetooth printer and a windows Mobile 6 handheld device, if that makes any difference for solutions.</p>
<p>Any suggestions would be appreciated.</p>
<p>[UPDATE]</p>
<p>I should also note that the mobile device is using Bluetooth 2.0, whereas the printer is only at version 1.1. I'm assuming the speed difference is what's causing the printer to lag behind in receiving the data.</p>
|
[
{
"answer_id": 254011,
"author": "Jason Down",
"author_id": 9732,
"author_profile": "https://Stackoverflow.com/users/9732",
"pm_score": 3,
"selected": false,
"text": "serialPort.Handshake = Handshake.RequestToSendXOnXOff;\nserialPort.WriteTimeout = 10000; // Could use a lower value here.\n serialPort.Write(labelData);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9732/"
] |
222,456
|
<p>I have a Visual Studio solution with four C# projects in it. I want to step into the code of a supporting project in the solution from my main project, but when I use the "Step into" key, it just skips over the call into that other project. I've set breakpoints in the supporting project, and they're ignored, and I can't for the life of me get it to step into any references to that project.</p>
<p>Everything is set to compile as "Debug", and I've seen Visual Studio warn me that my breakpoints won't be hit before - it doesn't do that in this case. It's as though it looks as though my code will debug, but then at run-time, there's a setting somewhere that tells Visual Studio not to step through the code in that project. All the other projects in my solutions debug without problems.</p>
<p>What box have I checked to cause this behavior?</p>
<p><strong>UPDATE FOR CLARITY</strong>: The "Just my code" option is currently disabled. Also, since the code belongs to a project in my same solution, I don't think the "Just my code" option applies here. I thought it only applied to pre-compiled code that I didn't have the source for, but since I have the source in my project, I don't think this option has any effect.</p>
|
[
{
"answer_id": 29745800,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 2,
"selected": false,
"text": "Release Debug"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8114/"
] |
222,457
|
<p>The .NET standard of prefixing an interface name with an I seems to be becoming widespread and isn't just limited to .NET any more. I have come across a lot of Java code that uses this convention (so it wouldn't surprise me if Java used it before C# did). Also Flex uses it, and so on. The placing of an I at the start of the name smacks of Hungarian notation though and so I'm uncomfortable with using it.</p>
<p>So the question is, is there an alternative way of denoting that Something is an interface, rather than a class and is there any need to denote it like this anyway. Or is it a case its become a standard and so I should just accept it and stop trying to stir up "religious wars" by suggesting it be done differently?</p>
|
[
{
"answer_id": 222502,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "I I I"
},
{
"answer_id": 414375,
"author": "willcodejavaforfood",
"author_id": 51382,
"author_profile": "https://Stackoverflow.com/users/51382",
"pm_score": 0,
"selected": false,
"text": "public class CustomerImpl implements Customer\n"
},
{
"answer_id": 17996029,
"author": "BartoszKP",
"author_id": 2642204,
"author_profile": "https://Stackoverflow.com/users/2642204",
"pm_score": 1,
"selected": false,
"text": "public class StackOverflowAnswerGenerator { } public interface StackOverflowAnswerGenerator {} public class StupidStackOverflowAnswerGenerator : StackOverflowAnswerGenerator {} public class RandomStackOverflowAnswerGenerator : StackOverflowAnswerGenerator {} public class GoogleSearchStackoverflowAnswerGenerator : StackOverflowAnswerGenerator {} //... namespace StackOverflowAnswerMachine.Interfaces \n{\n public interface StackOverflowAnswerGenerator {}\n}\n\nnamespace StackOverflowAnswerMachine \n{ \n public class StackOverflowAnswerGenerator : Interfaces.StackOverflowAnswerGenerator\n{}\n\n}\n namespace StackOverflowAnswerMachine \n{\n public interface StackOverflowAnswerGenerator {}\n}\n\nnamespace StackOverflowAnswerMachine.Implementations \n{ \n public class StackOverflowAnswerGenerator : StackOverflowAnswerMachine.StackOverflowAnswerGenerator \n{}\n\n}\n using StackOverflowAnswerMachine;"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7122/"
] |
222,463
|
<p><strong>Java</strong> is the key here. I need to be able to delete files but users expect to be able to "undelete" from the recycle bin. As far as I can tell this isn't possible. Anyone know otherwise?</p>
|
[
{
"answer_id": 222554,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 6,
"selected": true,
"text": "SHFileOperation FO_DELETE SHFILEOPSTRUCT"
},
{
"answer_id": 44737354,
"author": "Damiano",
"author_id": 4060922,
"author_profile": "https://Stackoverflow.com/users/4060922",
"pm_score": 0,
"selected": false,
"text": "public class Trash {\n\n public void moveToTrash(File ... file) throws IOException {\n moveToTrash(false, file);\n }\n\n public void promptMoveToTrash(File ... file) throws IOException {\n moveToTrash(true, file);\n }\n\n private void moveToTrash(boolean withPrompt, File ... file) throws IOException {\n String fileList = Stream.of(file).map(File::getAbsolutePath).reduce((f1, f2)->f1+\" \"+f2).orElse(\"\");\n Runtime.getRuntime().exec(\"Recycle.exe \"+(withPrompt ? \"\" : \"-f \")+fileList);\n }\n\n}\n"
},
{
"answer_id": 48284057,
"author": "Holger",
"author_id": 2711488,
"author_profile": "https://Stackoverflow.com/users/2711488",
"pm_score": 5,
"selected": false,
"text": "java.awt.Desktop.moveToTrash(java.io.File) public boolean moveToTrash(File file) Desktop.isSupported(Desktop.Action.MOVE_TO_TRASH)"
},
{
"answer_id": 53388438,
"author": "Ahmad Sayeed",
"author_id": 4047341,
"author_profile": "https://Stackoverflow.com/users/4047341",
"pm_score": 2,
"selected": false,
"text": "static boolean moveToTrash(String filePath) {\n File file = new File(filePath);\n\n FileUtils fileUtils = FileUtils.getInstance();\n if (fileUtils.hasTrash()) {\n\n try {\n fileUtils.moveToTrash(new File[] { file });\n return true;\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n } else {\n System.out.println(\"No Trash\");\n return false;\n }\n }\n"
},
{
"answer_id": 57179503,
"author": "Christophe Moine",
"author_id": 5846877,
"author_profile": "https://Stackoverflow.com/users/5846877",
"pm_score": 0,
"selected": false,
"text": "FileUtils W32FileUtils"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5054/"
] |
222,464
|
<p>I am developing RoR application that works with legacy database and uses ActiveScaffold plugin for fancy CRUD interface.</p>
<p>However one of the tables of my legacy db has composite primary key. I tried using Composite Keys plugin to handle it, but it seems to have conflicts with ACtiveScaffold: I get the following error:</p>
<pre><code>ActionView::TemplateError (Could not find column contact,type) on line #3 of ven
dor/plugins/active_scaffold/frontends/default/views/_form.rhtml:
1: <ol class="form" <%= 'style="display: none;"' if columns.collapsed -%>>
2: <% columns.each :for => @record do |column| -%>
3: <% if is_subsection? column -%>
4: <li class="sub-section">
5: <h5><%= column.label %> (<%= link_to_visibility_toggle(:default_visible =
> !column.collapsed) -%>)</h5>
6: <%= render :partial => 'form', :locals => { :columns => column } %>
vendor/plugins/active_scaffold/lib/data_structures/sorting.rb:16:in `add'
</code></pre>
<p>while having in model code smth like:</p>
<pre><code>set_primary_keys :contact, :type
</code></pre>
<p>I highly appreciate any idea how I can get composite keys capability with ActiveScaffold.</p>
|
[
{
"answer_id": 12754707,
"author": "Ryan Barton",
"author_id": 204148,
"author_profile": "https://Stackoverflow.com/users/204148",
"pm_score": 0,
"selected": false,
"text": " class CPKReadonlyModel < ActiveRecord::Base\n set_primary_key :id_one # only half of it, but id overridden below...\n\n def id\n self.id_one.to_s + ',' + self.id_two.to_s\n end\n\n def readonly?\n true\n end\n\n def before_destroy\n raise ActiveRecord::ReadOnlyRecord\n end\n\n def delete\n raise ActiveRecord::ReadOnlyRecord\n end\n\n def self.delete_all\n raise ActiveRecord::ReadOnlyRecord\n end\n end\n config.actions.exclude :create, :update, :delete\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404206/"
] |
222,470
|
<p>I have to copy quite a lot of files from one folder to another. Currently I am doing it in this way:</p>
<pre><code>string[] files = Directory.GetFiles(rootFolder, "*.xml");
foreach (string file in files)
{
string otherFile = Path.Combine(otherFolder, Path.GetFileName(file));
File.Copy(file, otherFile);
}
</code></pre>
<p>Is that the most efficient way? Seems to take ages.</p>
<p>EDIT: I am really asking if there is a faster way to do a batch copy, instead of copying individual files, but I guess the answer is no.</p>
|
[
{
"answer_id": 222727,
"author": "JFV",
"author_id": 1391,
"author_profile": "https://Stackoverflow.com/users/1391",
"pm_score": 1,
"selected": false,
"text": "fsSource = New FileStream(backupPath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None, 1024, FileOptions.WriteThrough)\nfsDest = New FileStream(restorationPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, FileOptions.WriteThrough)\nTransferData(fsSource, fsDest, 1048576)\n\n Private Sub TransferData(ByVal FromStream As IO.Stream, ByVal ToStream As IO.Stream, ByVal BufferSize As Integer)\n Dim buffer(BufferSize - 1) As Byte\n\n Do While IsCancelled = False 'Do While True\n Dim bytesRead As Integer = FromStream.Read(buffer, 0, buffer.Length)\n If bytesRead = 0 Then Exit Do\n ToStream.Write(buffer, 0, bytesRead)\n sizeCopied += bytesRead\n Loop\n End Sub\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363/"
] |
222,471
|
<p>I recently started using Linux as my primary OS. What are the tools that I will need to set up a complete programming environment in Linux for C and C++?</p>
|
[
{
"answer_id": 222721,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 2,
"selected": false,
"text": "sudo apt-get install build-essential\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
222,472
|
<p>Hmm. I'm trying to deploy a web service to a new server and there is no ASP.NET tab. I've tried running <code>aspnet_regiis</code> from ASP.NET 2.0 directory but this doesn't seem to work. Any ideas anyone?</p>
|
[
{
"answer_id": 222487,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 3,
"selected": false,
"text": "aspnet_regiis -u\n aspnet_regiis -i\n"
},
{
"answer_id": 222523,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 4,
"selected": false,
"text": "%windir%\\system32\\inetsrv\\MetaBase.xml Enable32BitAppOnWin64=\"TRUE\" iisreset /start"
},
{
"answer_id": 222541,
"author": "Mike Marshall",
"author_id": 29798,
"author_profile": "https://Stackoverflow.com/users/29798",
"pm_score": 2,
"selected": false,
"text": "aspnet_regiis -u aspnet_regiis -i"
},
{
"answer_id": 11022849,
"author": "Aditya Bokade",
"author_id": 1132423,
"author_profile": "https://Stackoverflow.com/users/1132423",
"pm_score": 0,
"selected": false,
"text": "http://localhost\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116/"
] |
222,511
|
<p>These two methods exhibit repetition: </p>
<pre><code>public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
return f => new FooEditDto
{
PropertyA = f.PropertyA,
PropertyB = f.PropertyB,
PropertyC = f.PropertyC,
PropertyD = f.PropertyD,
PropertyE = f.PropertyE
};
}
public static Expression<Func<Foo, FooListDto>> ListDtoSelector()
{
return f => new FooDto
{
PropertyA = f.PropertyA,
PropertyB = f.PropertyB,
PropertyC = f.PropertyC
};
}
</code></pre>
<p>How can I refactor to eliminate this repetition?</p>
<p>UPDATE: Oops, I neglected to mention an important point. FooEditDto is a subclass of FooDto.</p>
|
[
{
"answer_id": 222550,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()\n{\n return f => MagicCopier<FooEditDto>.Copy(new { \n f.PropertyA, f.PropertyB, f.PropertyC, f.PropertyD, f.PropertyC\n });\n}\n /// <summary>\n/// Generic class which copies to its target type from a source\n/// type specified in the Copy method. The types are specified\n/// separately to take advantage of type inference on generic\n/// method arguments.\n/// </summary>\npublic static class PropertyCopy<TTarget> where TTarget : class, new()\n{\n /// <summary>\n /// Copies all readable properties from the source to a new instance\n /// of TTarget.\n /// </summary>\n public static TTarget CopyFrom<TSource>(TSource source) where TSource : class\n {\n return PropertyCopier<TSource>.Copy(source);\n }\n\n /// <summary>\n /// Static class to efficiently store the compiled delegate which can\n /// do the copying. We need a bit of work to ensure that exceptions are\n /// appropriately propagated, as the exception is generated at type initialization\n /// time, but we wish it to be thrown as an ArgumentException.\n /// </summary>\n private static class PropertyCopier<TSource> where TSource : class\n {\n private static readonly Func<TSource, TTarget> copier;\n private static readonly Exception initializationException;\n\n internal static TTarget Copy(TSource source)\n {\n if (initializationException != null)\n {\n throw initializationException;\n }\n if (source == null)\n {\n throw new ArgumentNullException(\"source\");\n }\n return copier(source);\n }\n\n static PropertyCopier()\n {\n try\n {\n copier = BuildCopier();\n initializationException = null;\n }\n catch (Exception e)\n {\n copier = null;\n initializationException = e;\n }\n }\n\n private static Func<TSource, TTarget> BuildCopier()\n {\n ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), \"source\");\n var bindings = new List<MemberBinding>();\n foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())\n {\n if (!sourceProperty.CanRead)\n {\n continue;\n }\n PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);\n if (targetProperty == null)\n {\n throw new ArgumentException(\"Property \" + sourceProperty.Name \n + \" is not present and accessible in \" + typeof(TTarget).FullName);\n }\n if (!targetProperty.CanWrite)\n {\n throw new ArgumentException(\"Property \" + sourceProperty.Name \n + \" is not writable in \" + typeof(TTarget).FullName);\n }\n if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))\n {\n throw new ArgumentException(\"Property \" + sourceProperty.Name\n + \" has an incompatible type in \" + typeof(TTarget).FullName);\n }\n bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));\n }\n Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);\n return Expression.Lambda<Func<TSource,TTarget>>(initializer, sourceParameter).Compile();\n }\n }\n TargetType target = PropertyCopy<TargetType>.CopyFrom(new { First=\"Foo\", Second=\"Bar\" });\n"
},
{
"answer_id": 222591,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "public static Expression<Func<Foo,T>> \n GetSelector<T>(Expression<Func<Foo,T>> f)\n { return f;\n }\n\n/* ... */\nvar expr = GetSelector(f => new{f.PropertyA,f.PropertyB,f.PropertyC});\n"
},
{
"answer_id": 222656,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": true,
"text": "FooEditDto FooDto class FooDto\n { public FooDto(Bar a, Bar b, Bar c) \n { PropertyA = a;\n PropertyB = b;\n PropertyC = c;\n }\n public Bar PropertyA {get;set;}\n public Bar PropertyB {get;set;}\n public Bar PropertyC {get;set;}\n }\n\nclass FooEditDto : FooDto\n { public FooEditDto(Bar a, Bar b, Bar c) : base(a,b,c)\n public Bar PropertyD {get;set;}\n public Bar PropertyE {get;set;}\n }\n\npublic static Expression<Func<Foo, FooEditDto>> EditDtoSelector()\n{\n return f => new FooEditDto(f.PropertyA,f.PropertyB,f.PropertyC)\n {\n PropertyD = f.PropertyD,\n PropertyE = f.PropertyE\n };\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29493/"
] |
222,520
|
<p>At the moment my code looks like this:</p>
<pre><code># Assign values for saving to the db
$data = array(
'table_of_contents' => $_POST['table_of_contents'],
'length' => $_POST['length']
);
# Check for fields that may not be set
if ( isset($_POST['lossless_copy']) )
{
$data = array(
'lossless_copy' => $_POST['lossless_copy']
);
}
// etc.
</code></pre>
<p>This would lead to endless if statements though... Even with the ternary syntax it's still messy. Is there a better way?</p>
|
[
{
"answer_id": 222633,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "foreach ($_POST as $key => $value) {\n $data[$key] = $value;\n}\n $fields = array();\n$table = 'Current_Table';\n\n// we are not using mysql_list_fields() as it is deprecated\n$query = \"SHOW COLUMNS from {$table}\";\n$result = mysql_query($query);\nwhile ($get = mysql_fetch_object($result) ) {\n $fields[] = $get->Field;\n}\n\nforeach($fields as $field) {\n if (isset($_POST[$field]) ) {\n $data[$field] = $_POST[$field];\n }\n}\n"
},
{
"answer_id": 222643,
"author": "ojrac",
"author_id": 20760,
"author_profile": "https://Stackoverflow.com/users/20760",
"pm_score": 2,
"selected": false,
"text": "$optional = array('lossless_copy', 'bossless_floppy', 'foo');\nforeach ($optional as $field) {\n if (isset($_POST[$field])) {\n $data[$field] = $_POST[$field];\n }\n}\n"
},
{
"answer_id": 222663,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$formfields = $_POST;\n$data = array();\nforeach(array_keys($formfields) as $fieldname){\n $data[$fieldname] = $_POST[$fieldname];\n}\n"
},
{
"answer_id": 222673,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 4,
"selected": true,
"text": "// this is an array of default values for the fields that could be in the POST\n$defaultValues = array(\n 'table_of_contents' => '',\n 'length' => 25,\n 'lossless_copy' => false,\n);\n$data = array_merge($defaultValues, $_POST);\n// $data is now the post with all the keys set\n array_merge() array_merge() foreach()"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
222,531
|
<p>I have something like the following in an ASP.NET MVC application:</p>
<pre><code>IEnumerable<string> list = GetTheValues();
var selectList = new SelectList(list, "SelectedValue");
</code></pre>
<p>And even thought the selected value is defined, it is not being selected on the view. I have this feeling I'm missing something here, so if anyone can put me out my misery!</p>
<p>I know I can use an annoymous type to supply the key and value, but I would rather not add the additional code if I didn't have to.</p>
<p>EDIT: This problem has been fixed by ASP.NET MVC RTM.</p>
|
[
{
"answer_id": 222584,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 4,
"selected": false,
"text": "IDictionary<string,string> list = GetTheValues();\nvar selectList = new SelectList(list, \"Key\", \"Value\", \"SelectedValue\");\n"
},
{
"answer_id": 9811148,
"author": "Alex",
"author_id": 265877,
"author_profile": "https://Stackoverflow.com/users/265877",
"pm_score": 4,
"selected": false,
"text": "IEnumerable<string> SelectList new SelectList(MyIEnumerablesStrings.Select(x=>new KeyValuePair<string,string>(x,x)), \"Key\", \"Value\");\n"
},
{
"answer_id": 39769462,
"author": "Jay Sheth",
"author_id": 5055592,
"author_profile": "https://Stackoverflow.com/users/5055592",
"pm_score": 2,
"selected": false,
"text": "ViewBag.Items = list.Select(x => new SelectListItem() \n {\n Text = x.ToString()\n });\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
] |
222,544
|
<p>When Xdebug is installed/enabled, standard PHP errors (when set to display in the browser) are replaced with more informative messages that include stack traces for each. Also, I've noticed that it also seems to improve output in other areas such as the var_dump() function, formatting/color-coding the output to make it more readable.</p>
<p>Are there any 3rd party packages that offer similar functionality? I tend to prefer using Zend Debugger for debugging and would love to find something like this that doesn't depend on Xdebug. Certainly I could write my own error handler, a custom var_dump() function, etc., but I would love to find something that transparently integrates itself into PHP the way Xdebug's functionality does.</p>
<p><strong>Edit:</strong> I should emphasize that I'm not looking for a debugger, but for the "extras" that Xdebug offers.</p>
|
[
{
"answer_id": 5487078,
"author": "raveren",
"author_id": 179104,
"author_profile": "https://Stackoverflow.com/users/179104",
"pm_score": 0,
"selected": false,
"text": "var_dump"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
222,551
|
<p>To use Google Analytics, you put some JavaScript code in your web page which will make an asynchronous request to Google when the page loads.</p>
<p>From what I have read, this shouldn't block or slow down page load times if you include it directly before the end of your HTML Body. To verify this, I want to make the request after some period of time. The user should be able to log into my site regardless of the time it takes for the request to Google or if it comes back at all (the tracking code is on the login page).</p>
<p>There is a 'pageTracker._trackPageview()' function call in the Google Tracking code. Is this where the request is sent to Google?</p>
<p>If so, should I just do:</p>
<pre><code>window.setTimeout(pageTracker._trackPageview(), 5000);
</code></pre>
<p>any help is appreciated, especially if you have worked with Google Analytics and have this same problem.</p>
|
[
{
"answer_id": 222571,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 0,
"selected": false,
"text": "window.setTimeout(\"pageTracker._trackPageview()\", 5000);\n"
},
{
"answer_id": 222603,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "window.setTimeout(pageTracker._trackPageview(), 5000); window.setTimeout(function() { pageTracker._trackPageview(); }, 5000);"
},
{
"answer_id": 222893,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 1,
"selected": false,
"text": "window.setTimeout(pageTracker._trackPageview, 5000);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16148/"
] |
222,557
|
<p>Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.</p>
|
[
{
"answer_id": 222577,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 3,
"selected": false,
"text": "std::vector<> std::vector<> objects vector<>"
},
{
"answer_id": 222578,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 10,
"selected": true,
"text": "char *buf = new char[sizeof(string)]; // pre-allocated buffer\nstring *p = new (buf) string(\"hi\"); // placement new\nstring *q = new string(\"hi\"); // ordinary heap allocation\n"
},
{
"answer_id": 222615,
"author": "Don Wakefield",
"author_id": 3778,
"author_profile": "https://Stackoverflow.com/users/3778",
"pm_score": 6,
"selected": false,
"text": "class Pool {\npublic:\n Pool() { /* implementation details irrelevant */ };\n virtual ~Pool() { /* ditto */ };\n\n virtual void *allocate(size_t);\n virtual void deallocate(void *);\n\n static Pool *Pool::misc_pool() { return misc_pool_p; /* global MiscPool for general use */ }\n};\n\nclass ClusterPool : public Pool { /* ... */ };\nclass FastPool : public Pool { /* ... */ };\nclass MapPool : public Pool { /* ... */ };\nclass MiscPool : public Pool { /* ... */ };\n\n// elsewhere...\n\nvoid *pnew_new(size_t size)\n{\n return Pool::misc_pool()->allocate(size);\n}\n\nvoid *pnew_new(size_t size, Pool *pool_p)\n{\n if (!pool_p) {\n return Pool::misc_pool()->allocate(size);\n }\n else {\n return pool_p->allocate(size);\n }\n}\n\nvoid pnew_delete(void *p)\n{\n Pool *hp = Pool::find_pool(p);\n // note: if p == 0, then Pool::find_pool(p) will return 0.\n if (hp) {\n hp->deallocate(p);\n }\n}\n\n// elsewhere...\n\nclass Obj {\npublic:\n // misc ctors, dtors, etc.\n\n // just a sampling of new/del operators\n void *operator new(size_t s) { return pnew_new(s); }\n void *operator new(size_t s, Pool *hp) { return pnew_new(s, hp); }\n void operator delete(void *dp) { pnew_delete(dp); }\n void operator delete(void *dp, Pool*) { pnew_delete(dp); }\n\n void *operator new[](size_t s) { return pnew_new(s); }\n void *operator new[](size_t s, Pool* hp) { return pnew_new(s, hp); }\n void operator delete[](void *dp) { pnew_delete(dp); }\n void operator delete[](void *dp, Pool*) { pnew_delete(dp); }\n};\n\n// elsewhere...\n\nClusterPool *cp = new ClusterPool(arg1, arg2, ...);\n\nObj *new_obj = new (cp) Obj(arg_a, arg_b, ...);\n"
},
{
"answer_id": 4809416,
"author": "Keith A. Lewis",
"author_id": 394744,
"author_profile": "https://Stackoverflow.com/users/394744",
"pm_score": 2,
"selected": false,
"text": "typedef struct _FP\n{\n unsigned short int rows;\n unsigned short int columns;\n double array[1]; /* Actually, array[rows][columns] */\n} FP;\n"
},
{
"answer_id": 15806136,
"author": "nimrodm",
"author_id": 23388,
"author_profile": "https://Stackoverflow.com/users/23388",
"pm_score": 3,
"selected": false,
"text": "memset() static Mystruct m;\n\n for(...) {\n // re-initialize the structure. Note the use of placement new\n // and the extra parenthesis after Mystruct to force initialization.\n new (&m) Mystruct();\n\n // do-some work that modifies m's content.\n }\n"
},
{
"answer_id": 48273778,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "unordered_map vector deque vector vector<Foo> vec;\n\n// Allocate memory for a thousand Foos:\nvec.reserve(1000);\n vector Foos std::allocator std::allocator placement new placement new Foo* foo = new(free_list.allocate()) Foo(...);\n...\nfoo->~Foo();\nfree_list.free(foo);\n"
},
{
"answer_id": 51586111,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "/* Quickly aligns the given pointer to a power of two boundary IN BYTES.\n@return An aligned pointer of typename T.\n@brief Algorithm is a 2's compliment trick that works by masking off\nthe desired number in 2's compliment and adding them to the\npointer.\n@param pointer The pointer to align.\n@param boundary_byte_count The boundary byte count that must be an even\npower of 2.\n@warning Function does not check if the boundary is a power of 2! */\ntemplate <typename T = char>\ninline T* AlignUp(void* pointer, uintptr_t boundary_byte_count) {\n uintptr_t value = reinterpret_cast<uintptr_t>(pointer);\n value += (((~value) + 1) & (boundary_byte_count - 1));\n return reinterpret_cast<T*>(value);\n}\n\nstruct Foo { Foo () {} };\nchar buffer[sizeof (Foo) + 64];\nFoo* foo = new (AlignUp<Foo> (buffer, 64)) Foo ();\n"
},
{
"answer_id": 63893849,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": -1,
"selected": false,
"text": "operator=() const memcpy() = operator=() memcpy() memcpy() = operator=() B = C; B.operator=(C); A = B = C; A.operator=(B.operator=(C)); operator=() operator=() operator=() = operator=() nc2 = nc1; error: use of deleted function ‘NonCopyable1& NonCopyable1::operator=(const NonCopyable1&)’\n #include <stdio.h>\n\nclass NonCopyable1\n{\npublic:\n int i = 5;\n\n // Delete the assignment operator to make this class non-copyable \n NonCopyable1& operator=(const NonCopyable1& other) = delete;\n};\n\nint main()\n{\n printf(\"Hello World\\n\");\n \n NonCopyable1 nc1;\n NonCopyable1 nc2;\n nc2 = nc1; // copy assignment; compile-time error!\n NonCopyable1 nc3 = nc1; // copy constructor; works fine!\n\n return 0;\n}\n const nc2 = nc1; error: use of deleted function ‘NonCopyable1& NonCopyable1::operator=(const NonCopyable1&)’\nnote: ‘NonCopyable1& NonCopyable1::operator=(const NonCopyable1&)’ is implicitly deleted because the default definition would be ill-formed:\nerror: non-static const member ‘const int NonCopyable1::i’, can’t use default assignment operator\n #include <stdio.h>\n\nclass NonCopyable1\n{\npublic:\n const int i = 5; // classes with `const` members are non-copyable by default\n};\n\nint main()\n{\n printf(\"Hello World\\n\");\n \n NonCopyable1 nc1;\n NonCopyable1 nc2;\n nc2 = nc1; // copy assignment; compile-time error!\n NonCopyable1 nc3 = nc1; // copy constructor; works fine!\n\n return 0;\n}\n outputData = data; #include <functional>\n\n#include <stdio.h>\n\nclass NonCopyable1\n{\npublic:\n const int i; // classes with `const` members are non-copyable by default\n\n // Constructor to custom-initialize `i`\n NonCopyable1(int val = 5) : i(val) \n {\n // nothing else to do \n }\n};\n\n// Some class which (perhaps asynchronously) processes data. You attach a \n// callback, which gets called later. \n// - Also, this may be a shared library over which you have no or little \n// control, so you cannot easily change the prototype of the callable/callback \n// function. \nclass ProcessData\n{\npublic:\n void attachCallback(std::function<void(void)> callable)\n {\n callback_ = callable;\n }\n \n void callCallback()\n {\n callback_();\n }\n\nprivate:\n std::function<void(void)> callback_;\n};\n\nint main()\n{\n printf(\"Hello World\\n\");\n \n NonCopyable1 outputData; // we need to receive back data through this object\n printf(\"outputData.i (before) = %i\\n\", outputData.i); // is 5\n \n ProcessData processData;\n // Attach a lambda function as a callback, capturing `outputData` by \n // reference so we can receive back the data from inside the callback via \n // this object even though the callable prototype returns `void` (is a \n // `void(void)` callable/function).\n processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n // NOT ALLOWED SINCE COPY OPERATOR (Assignment operator) WAS \n // AUTO-DELETED since the class has a `const` data member!\n outputData = data; \n });\n processData.callCallback();\n // verify we get 999 here, NOT 5!\n printf(\"outputData.i (after) = %i\\n\", outputData.i); \n\n return 0;\n}\n outputData std::memcpy std::ofstream::write() std::ifstream::read() memcpy() processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n // NOT ALLOWED SINCE COPY OPERATOR (Assignment operator) WAS \n // AUTO-DELETED since the class has a `const` data member!\n outputData = data; \n });\n memcpy() std::is_trivially_copyable memcpy() // (added to top)\n #include <cstring> // for `memcpy()`\n #include <type_traits> // for `std::is_trivially_copyable<>()`\n\n // Attach a lambda function as a callback, capturing `outputData` by \n // reference so we can receive back the data from inside the callback via \n // this object even though the callable prototype returns `void` (is a \n // `void(void)` callable/function).\n processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n static_assert(std::is_trivially_copyable<NonCopyable1>::value, \"NonCopyable1 must \"\n \"be a trivially-copyable type in order to guarantee that `memcpy()` is safe \"\n \"to use on it.\");\n memcpy(&outputData, &data, sizeof(data));\n });\n Hello World\noutputData.i (before) = 5\noutputData.i (after) = 999\n processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n static_assert(std::is_trivially_copyable<NonCopyable1>::value, \"NonCopyable1 must \"\n \"be a trivially-copyable type in order to guarantee that `memcpy()` is safe \"\n \"to use on it.\");\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n memcpy(&outputData, &data, sizeof(data));\n });\n static_assert() memcpy() data outputData new new alignof alignas outputData NonCopyable1 outputData; // Call`T`'s specified constructor below, constructing it as an object right into\n// the memory location pointed to by `ptr_to_buffer`. No dynamic memory allocation\n// whatsoever happens at this time. The object `T` is simply constructed into this\n// address in memory.\nT* ptr_to_T = new(ptr_to_buffer) T(optional_input_args_to_T's_constructor);\n NonCopyable1 // copy-construct `data` right into the address at `&outputData`, using placement new syntax\nnew(&outputData) NonCopyable1(data); \n attachCallback memcpy() processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n // copy-construct `data` right into the address at `&outputData`, using placement new syntax\n new(&outputData) NonCopyable1(data); \n\n // Assume that `data` will be further manipulated and used below now, but we needed\n // its state at this moment in time. \n\n // Note also that under the most trivial of cases, we could have also just called\n // out custom constructor right here too, like this. You can call whatever\n // constructor you want!\n // new(&outputData) NonCopyable1(999);\n\n // ...\n });\n vptr vtbl memcpy() memcpy() memcpy() static_assert(std::is_trivially_copyable<NonCopyable1>::value); memcpy() NonCopyable1 // Custom copy/assignment operator declaration:\nNonCopyable1& operator=(const NonCopyable1& other);\n\n// OR:\n\n// Custom copy/assignment operator definition:\nNonCopyable1& operator=(const NonCopyable1& other)\n{\n // Check for, **and don't allow**, self assignment! \n // ie: only copy the contents from the other object \n // to this object if it is not the same object (ie: if it is not \n // self-assignment)!\n if(this != &other) \n {\n // copy all non-const members manually here, if the class had any; ex:\n // j = other.j;\n // k = other.k;\n // etc.\n // Do deep copy of data via any member **pointers**, if such members exist\n }\n\n // the assignment function (`operator=()`) expects you to return the \n // contents of your own object (the left side), passed by reference, so \n // that constructs such as `test1 = test2 = test3;` are valid!\n // See this reference, from Stanford, p11, here!:\n // http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1084/cs106l/handouts/170_Copy_Constructor_Assignment_Operator.pdf\n // MyClass one, two, three;\n // three = two = one;\n return *this; \n}\n processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n static_assert(std::is_trivially_copyable<NonCopyable1>::value, \"NonCopyable1 must \"\n \"be a trivially-copyable type in order to guarantee that `memcpy()` is safe \"\n \"to use on it.\");\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n memcpy(&outputData, &data, sizeof(data));\n });\n main.cpp: In lambda function:\nmain.cpp:151:13: error: static assertion failed: NonCopyable1 must be a trivially-copyable type in order to guarantee that `memcpy()` is safe to use on it.\n static_assert(std::is_trivially_copyable<NonCopyable1>::value, \"NonCopyable1 must \"\n ^~~~~~~~~~~~~\n processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n // copy-construct `data` right into the address at `&outputData`, using placement new syntax\n new(&outputData) NonCopyable1(data); \n });\n NonCopyable1 outputData; // within any scope...\n{\n char buf[sizeof(T)]; // Statically allocate memory large enough for any object of\n // type `T`; it may be misaligned!\n // OR, to force proper alignment of your memory buffer for your object of type `T`, \n // you may specify memory alignment with `alignas()` like this instead:\n alignas(alignof(T)) char buf[sizeof(T)];\n T* tptr = new(buf) T; // Construct a `T` object, placing it directly into your \n // pre-allocated storage at memory address `buf`.\n tptr->~T(); // You must **manually** call the object's destructor.\n} // Leaving scope here auto-deallocates your statically-allocated \n // memory `buf`.\n // This constructs an actual object here, calling the `NonCopyable1` class's\n// default constructor.\nNonCopyable1 outputData; \n // This is just a statically-allocated memory pool. No constructor is called.\n// Statically allocate an output buffer properly aligned, and large enough,\n// to store 1 single `NonCopyable1` object.\nalignas(alignof(NonCopyable1)) uint8_t outputData[sizeof(NonCopyable1)];\nNonCopyable1* outputDataPtr = (NonCopyable1*)(&outputData[0]);\n outputData outputDataPtr NonCopyable1 outputData; uint8_t struct __attribute__((__cleanup__(my_variable))) NonCopyable1 data(someRandomData); memcpy() = operator=() memcpy() const std::optional<>::emplace() std::optional<> emplace() std::vector<T,Allocator>::emplace_back std::optional std::nullopt {} emplace() std::optional *this NonCopyable1 outputData; \n\n// OR\n\nalignas(alignof(NonCopyable1)) uint8_t outputData[sizeof(NonCopyable1)];\nNonCopyable1* outputDataPtr = (NonCopyable1*)(&outputData[0]);\n # include <optional>\n\nstd::optional<NonCopyable1> outputData = std::nullopt;\n processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n // copy-construct `data` right into the address at `&outputData`, using placement new syntax\n new(&outputData) NonCopyable1(data); \n });\n emplace() std::optional<>::emplace() processData.attachCallback([&outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n // emplace `data` right into the `outputData` object\n outputData.emplace(data);\n });\n outputData * .value() // verify we get 999 here!\nif (outputData.has_value())\n{\n printf(\"(*outputData).i (after) = %i\\n\", (*outputData).i);\n // OR \n printf(\"outputData.value().i (after) = %i\\n\", outputData.value().i);\n}\nelse \n{\n printf(\"outputData.has_value() is false!\");\n}\n Hello World\n(*outputData).i (after) = 999\noutputData.value().i (after) = 999\n Fred* f = new(place) Fred(); Fred::Fred() this Fred place std::optional<>"
},
{
"answer_id": 65422996,
"author": "CPPCPPCPPCPPCPPCPPCPPCPPCPPCPP",
"author_id": 14874226,
"author_profile": "https://Stackoverflow.com/users/14874226",
"pm_score": 1,
"selected": false,
"text": "#include <new>\n#include <cstdio>\n#include <cstdlib>\n\nint main() {\n struct A {\n A() {\n printf(\"A()\\n\");\n }\n ~A() {\n printf(\"~A()\\n\");\n }\n char data[1000000000000000000] = {}; // some very big number\n };\n\n try {\n A *result = new A();\n printf(\"new passed: %p\\n\", result);\n delete result;\n } catch (std::bad_alloc) {\n printf(\"new failed\\n\");\n }\n}\n #include <new>\n#include <cstdio>\n#include <cstdlib>\n\nint main() {\n struct A {\n A() {\n printf(\"A()\\n\");\n }\n ~A() {\n printf(\"~A()\\n\");\n }\n char data[1000000000000000000] = {}; // some very big number\n };\n\n void *buf = malloc(sizeof(A));\n if (buf != nullptr) {\n A *result = new(buf) A();\n printf(\"new passed: %p\\n\", result);\n result->~A();\n free(result);\n } else {\n printf(\"new failed\\n\");\n }\n}\n"
},
{
"answer_id": 65566298,
"author": "CPPCPPCPPCPPCPPCPPCPPCPPCPPCPP",
"author_id": 14874226,
"author_profile": "https://Stackoverflow.com/users/14874226",
"pm_score": 0,
"selected": false,
"text": "#include <cstddef>\n#include <cstdio>\n\nint main() {\n struct alignas(0x1000) A {\n char data[0x1000];\n };\n\n printf(\"max_align_t: %zu\\n\", alignof(max_align_t));\n\n A a;\n printf(\"a: %p\\n\", &a);\n\n A *ptr = new A;\n printf(\"ptr: %p\\n\", ptr);\n delete ptr;\n}\n max_align_t: 16\na: 0x7ffd45e6f000\nptr: 0x1fe3ec0\n ptr max_align_t: 16\na: 0x7ffc924f6000\nptr: 0x9f6000\n ptr max_align_t aligned_alloc #include <cstddef>\n#include <cstdlib>\n#include <cstdio>\n#include <new>\n\nint main() {\n struct alignas(0x1000) A {\n char data[0x1000];\n };\n\n printf(\"max_align_t: %zu\\n\", alignof(max_align_t));\n\n A a;\n printf(\"a: %p\\n\", &a);\n\n void *buf = aligned_alloc(alignof(A), sizeof(A));\n if (buf == nullptr) {\n printf(\"aligned_alloc() failed\\n\");\n exit(1);\n }\n A *ptr = new(buf) A();\n printf(\"ptr: %p\\n\", ptr);\n ptr->~A();\n free(ptr);\n}\n ptr max_align_t: 16\na: 0x7ffe56b57000\nptr: 0x2416000\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
222,561
|
<p>I have a few questions related:</p>
<p>1) Is possible to make my program change filetype association but only when is running? Do you see anything wrong with this behavior?</p>
<p>2) The other option that I'm seeing is to let users decide to open with my application or restore default association ... something like: "capture all .lala files" or "restore .lala association". How can I do this? What do you think that is the best approach?</p>
|
[
{
"answer_id": 222799,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "HKEY_CLASSES_ROOT HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes HKEY_CURRENT_USER\\SOFTWARE\\Classes"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
222,572
|
<p>I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me.</p>
<p>Edit: Folks, I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.</p>
|
[
{
"answer_id": 227944,
"author": "SaaS Developer",
"author_id": 7215,
"author_profile": "https://Stackoverflow.com/users/7215",
"pm_score": 4,
"selected": false,
"text": "List<string> items = GetItemsFromSomewhere();\nitems.Sort((x, y) => string.Compare(x, y));\nDropDownListId.DataSource = items;\nDropDownListId.DataBind();\n"
},
{
"answer_id": 227953,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": -1,
"selected": false,
"text": "Sort()"
},
{
"answer_id": 227961,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 6,
"selected": true,
"text": "DataView dvOptions = new DataView(DataTableWithOptions);\ndvOptions.Sort = \"Description\";\n\nddlOptions.DataSource = dvOptions;\nddlOptions.DataTextField = \"Description\";\nddlOptions.DataValueField = \"Id\";\nddlOptions.DataBind();\n"
},
{
"answer_id": 352522,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "function sortlist(mylist)\n{\n var lb = document.getElementById(mylist);\n arrTexts = new Array();\n arrValues = new Array();\n arrOldTexts = new Array();\n\n for(i=0; i<lb.length; i++)\n {\n arrTexts[i] = lb.options[i].text;\n arrValues[i] = lb.options[i].value;\n\n arrOldTexts[i] = lb.options[i].text;\n }\n\n arrTexts.sort();\n\n for(i=0; i<lb.length; i++)\n {\n lb.options[i].text = arrTexts[i];\n for(j=0; j<lb.length; j++)\n {\n if (arrTexts[i] == arrOldTexts[j])\n {\n lb.options[i].value = arrValues[j];\n j = lb.length;\n }\n }\n }\n}\n"
},
{
"answer_id": 1908550,
"author": "Dejan",
"author_id": 11471,
"author_profile": "https://Stackoverflow.com/users/11471",
"pm_score": 2,
"selected": false,
"text": "Public Class ListItemComparer\n Implements IComparer(Of ListItem)\n\n Public Function Compare(ByVal x As ListItem, ByVal y As ListItem) As Integer _\n Implements IComparer(Of ListItem).Compare\n\n Dim c As New CaseInsensitiveComparer\n Return c.Compare(x.Text, y.Text)\n End Function\nEnd Class\n Public Shared Sub SortDropDown(ByVal cbo As DropDownList)\n Dim lstListItems As New List(Of ListItem)\n For Each li As ListItem In cbo.Items\n lstListItems.Add(li)\n Next\n lstListItems.Sort(New ListItemComparer)\n cbo.Items.Clear()\n cbo.Items.AddRange(lstListItems.ToArray)\nEnd Sub\n SortDropDown(cboMyDropDown)\n"
},
{
"answer_id": 2157566,
"author": "Randy",
"author_id": 261324,
"author_profile": "https://Stackoverflow.com/users/261324",
"pm_score": 0,
"selected": false,
"text": " List<ListItem> li = new List<ListItem>();\n foreach (ListItem list in DropDownList1.Items)\n {\n li.Add(list);\n }\n li.Sort((x, y) => string.Compare(x.Text, y.Text));\n DropDownList1.Items.Clear();\n DropDownList1.DataSource = li;\n DropDownList1.DataTextField = \"Text\";\n DropDownList1.DataValueField = \"Value\";\n DropDownList1.DataBind();\n"
},
{
"answer_id": 2433427,
"author": "James McCormack",
"author_id": 71906,
"author_profile": "https://Stackoverflow.com/users/71906",
"pm_score": 5,
"selected": false,
"text": " public static void ReorderAlphabetized(this DropDownList ddl)\n {\n List<ListItem> listCopy = new List<ListItem>();\n foreach (ListItem item in ddl.Items)\n listCopy.Add(item);\n ddl.Items.Clear();\n foreach (ListItem item in listCopy.OrderBy(item => item.Text))\n ddl.Items.Add(item);\n }\n protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n ddlMyDropDown.ReorderAlphabetized();\n }\n"
},
{
"answer_id": 2963444,
"author": "mikek3332002",
"author_id": 261542,
"author_profile": "https://Stackoverflow.com/users/261542",
"pm_score": 0,
"selected": false,
"text": "<asp:ObjectDataSource ID=\"dsData\" runat=\"server\" TableName=\"Data\" \n Sort=\"ColumnName ASC\" />\n"
},
{
"answer_id": 11747858,
"author": "Tony",
"author_id": 1243783,
"author_profile": "https://Stackoverflow.com/users/1243783",
"pm_score": 2,
"selected": false,
"text": " int i = 0;\n string[] array = new string[items.Count];\n\n foreach (ListItem li in dropdownlist.items)\n {\n array[i] = li.ToString();\n i++;\n\n }\n\n Array.Sort(array);\n\n dropdownlist.DataSource = array;\n dropdownlist.DataBind();\n"
},
{
"answer_id": 15132370,
"author": "jasin_89",
"author_id": 637307,
"author_profile": "https://Stackoverflow.com/users/637307",
"pm_score": 1,
"selected": false,
"text": "var list = ddl.Items.Cast<ListItem>().OrderBy(x => x.Text).ToList();\n\nddl.DataSource = list;\nddl.DataTextField = \"Text\";\nddl.DataValueField = \"Value\"; \nddl.DataBind();\n"
},
{
"answer_id": 16245053,
"author": "Logar314159",
"author_id": 2066784,
"author_profile": "https://Stackoverflow.com/users/2066784",
"pm_score": 0,
"selected": false,
"text": " Dim Lista_Items = New List(Of ListItem)\n\n For Each item As ListItem In ddl.Items\n Lista_Items.Add(item)\n Next\n\n Lista_Items.Sort(Function(x, y) String.Compare(x.Text, y.Text))\n\n ddl.Items.Clear()\n ddl.Items.AddRange(Lista_Items.ToArray())\n Sort() List(of ) List<MyType>"
},
{
"answer_id": 18785241,
"author": "Mac Chibueze",
"author_id": 2606813,
"author_profile": "https://Stackoverflow.com/users/2606813",
"pm_score": 0,
"selected": false,
"text": "private void SortDDL(ref DropDownList objDDL)\n{\nArrayList textList = new ArrayList();\nArrayList valueList = new ArrayList();\nforeach (ListItem li in objDDL.Items)\n{\n textList.Add(li.Text);\n}\ntextList.Sort();\nforeach (object item in textList)\n{\n string value = objDDL.Items.FindByText(item.ToString()).Value;\n valueList.Add(value);\n}\nobjDDL.Items.Clear();\nfor(int i = 0; i < textList.Count; i++)\n{\n ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());\n objDDL.Items.Add(objItem);\n}\n"
},
{
"answer_id": 21131659,
"author": "Htun Thein Win",
"author_id": 3197100,
"author_profile": "https://Stackoverflow.com/users/3197100",
"pm_score": 1,
"selected": false,
"text": "USE [Your Database]\nGO\n\n\nCRATE PROC [dbo].[GetAllDataByID]\n\n@ID int\n\n\nAS\nBEGIN\n SELECT * FROM Your_Table\n WHERE ID=@ID\n ORDER BY Your_ColumnName \nEND\n <asp:DropDownList ID=\"ddlYourTable\" runat=\"server\"></asp:DropDownList>\n protected void Page_Load(object sender, EventArgs e)\n\n{\n\n if (!IsPostBack)\n {\n List<YourTable> table= new List<YourTable>();\n\n YourtableRepository tableRepo = new YourtableRepository();\n\n int conuntryInfoID=1;\n\n table= tableRepo.GetAllDataByID(ID);\n\n ddlYourTable.DataSource = stateInfo;\n ddlYourTable.DataTextField = \"Your_ColumnName\";\n ddlYourTable.DataValueField = \"ID\";\n ddlYourTable.DataBind();\n\n }\n }\n public class TableRepository\n\n {\n\n string connstr;\n\n public TableRepository() \n {\n connstr = Settings.Default.YourTableConnectionString.ToString();\n }\n\n public List<YourTable> GetAllDataByID(int ID)\n {\n List<YourTable> table= new List<YourTable>();\n using (YourTableDBDataContext dc = new YourTableDBDataContext ())\n {\n table= dc.GetAllDataByID(ID).ToList();\n }\n return table;\n }\n }\n"
},
{
"answer_id": 22969549,
"author": "Vince Pike",
"author_id": 2188655,
"author_profile": "https://Stackoverflow.com/users/2188655",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.\n/// </summary>\n/// <param name=\"dropDownList\">The drop down list you wish to modify.</param>\n/// <remarks></remarks>\nprivate void AlphabetizeDropDownList(ref DropDownList dropDownList)\n{\n //Create a datatable to sort the drop down list items\n DataTable machineDescriptionsTable = new DataTable();\n machineDescriptionsTable.Columns.Add(\"DescriptionCode\", typeof(string));\n machineDescriptionsTable.Columns.Add(\"UnitIDString\", typeof(string));\n machineDescriptionsTable.AcceptChanges();\n //Put each of the list items into the datatable\n foreach (ListItem currentDropDownListItem in dropDownList.Items) {\n string currentDropDownUnitIDString = currentDropDownListItem.Value;\n string currentDropDownDescriptionCode = currentDropDownListItem.Text;\n DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();\n currentDropDownDataRow[\"DescriptionCode\"] = currentDropDownDescriptionCode.Trim();\n currentDropDownDataRow[\"UnitIDString\"] = currentDropDownUnitIDString.Trim();\n machineDescriptionsTable.Rows.Add(currentDropDownDataRow);\n machineDescriptionsTable.AcceptChanges();\n }\n //Sort the data table by description\n DataView sortedView = new DataView(machineDescriptionsTable);\n sortedView.Sort = \"DescriptionCode\";\n machineDescriptionsTable = sortedView.ToTable();\n //Clear the items in the original dropdown list\n dropDownList.Items.Clear();\n //Create a dummy list item at the top\n ListItem dummyListItem = new ListItem(\" \", \"-1\");\n dropDownList.Items.Add(dummyListItem);\n //Begin transferring over the items alphabetically from the copy to the intended drop\n downlist\n foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {\n string currentDropDownValue = currentDataRow[\"UnitIDString\"].ToString().Trim();\n string currentDropDownText = currentDataRow[\"DescriptionCode\"].ToString().Trim();\n ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);\n //Don't deal with dummy values in the list we are transferring over\n if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {\n dropDownList.Items.Add(currentDropDownListItem);\n }\n}\n"
},
{
"answer_id": 24199589,
"author": "n00b",
"author_id": 1188930,
"author_profile": "https://Stackoverflow.com/users/1188930",
"pm_score": 0,
"selected": false,
"text": "DataTable dtOptions = new DataTable();\nDataColumn[] dcColumns = { new DataColumn(\"Text\", Type.GetType(\"System.String\")), \n new DataColumn(\"Value\", Type.GetType(\"System.String\"))};\ndtOptions.Columns.AddRange(dcColumns);\nforeach (ListItem li in ddlOperation.Items)\n{\n DataRow dr = dtOptions.NewRow();\n dr[\"Text\"] = li.Text;\n dr[\"Value\"] = li.Value;\n dtOptions.Rows.Add(dr);\n}\nDataView dv = dtOptions.DefaultView;\ndv.Sort = \"Text\";\nddlOperation.Items.Clear();\nddlOperation.DataSource = dv;\nddlOperation.DataTextField = \"Text\";\nddlOperation.DataValueField = \"Value\";\nddlOperation.DataBind();\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
222,581
|
<p>I'm looking for a simple Python script that can minify CSS as part of a web-site deployment process. (Python is the only scripting language supported on the server and full-blown parsers like <a href="http://cthedot.de/cssutils/" rel="noreferrer">CSS Utils</a> are overkill for this project).</p>
<p>Basically I'd like <a href="http://www.crockford.com/javascript/jsmin.py.txt" rel="noreferrer">jsmin.py</a> for CSS. A single script with no dependencies.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 223689,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 7,
"selected": true,
"text": "import sys, re\n\nwith open( sys.argv[1] , 'r' ) as f:\n css = f.read()\n\n# remove comments - this will break a lot of hacks :-P\ncss = re.sub( r'\\s*/\\*\\s*\\*/', \"$$HACK1$$\", css ) # preserve IE<6 comment hack\ncss = re.sub( r'/\\*[\\s\\S]*?\\*/', \"\", css )\ncss = css.replace( \"$$HACK1$$\", '/**/' ) # preserve IE<6 comment hack\n\n# url() doesn't need quotes\ncss = re.sub( r'url\\(([\"\\'])([^)]*)\\1\\)', r'url(\\2)', css )\n\n# spaces may be safely collapsed as generated content will collapse them anyway\ncss = re.sub( r'\\s+', ' ', css )\n\n# shorten collapsable colors: #aabbcc to #abc\ncss = re.sub( r'#([0-9a-f])\\1([0-9a-f])\\2([0-9a-f])\\3(\\s|;)', r'#\\1\\2\\3\\4', css )\n\n# fragment values can loose zeros\ncss = re.sub( r':\\s*0(\\.\\d+([cm]m|e[mx]|in|p[ctx]))\\s*;', r':\\1;', css )\n\nfor rule in re.findall( r'([^{]+){([^}]*)}', css ):\n\n # we don't need spaces around operators\n selectors = [re.sub( r'(?<=[\\[\\(>+=])\\s+|\\s+(?=[=~^$*|>+\\]\\)])', r'', selector.strip() ) for selector in rule[0].split( ',' )]\n\n # order is important, but we still want to discard repetitions\n properties = {}\n porder = []\n for prop in re.findall( '(.*?):(.*?)(;|$)', rule[1] ):\n key = prop[0].strip().lower()\n if key not in porder: porder.append( key )\n properties[ key ] = prop[1].strip()\n\n # output rule if it contains any declarations\n if properties:\n print \"%s{%s}\" % ( ','.join( selectors ), ''.join(['%s:%s;' % (key, properties[key]) for key in porder])[:-1] ) \n"
},
{
"answer_id": 29980020,
"author": "Yahya Yahyaoui",
"author_id": 1377439,
"author_profile": "https://Stackoverflow.com/users/1377439",
"pm_score": 2,
"selected": false,
"text": "import requests\nf = open(\"style.css\", \"r\")\ncss_text = f.read()\nf.close()\nr = requests.post(\"http://cssminifier.com/raw\", data={\"input\":css_text})\ncss_minified = r.text\nf2 = open(\"style.min.css\", \"w\")\nf2.write(css_minified)\nf2.close()\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7167/"
] |
222,598
|
<p>I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do <code>list.Clone()</code>.</p>
<p>Is there an easy way around this?</p>
|
[
{
"answer_id": 222611,
"author": "Anthony Potts",
"author_id": 22777,
"author_profile": "https://Stackoverflow.com/users/22777",
"pm_score": 7,
"selected": false,
"text": "List<int> oldList = new List<int>( );\n// Populate oldList...\n\nList<int> newList = oldList.GetRange(0, oldList.Count);\n"
},
{
"answer_id": 222623,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 9,
"selected": false,
"text": "List<YourType> newList = new List<YourType>(oldList);\n ICloneable List<ICloneable> oldList = new List<ICloneable>();\nList<ICloneable> newList = new List<ICloneable>(oldList.Count);\n\noldList.ForEach((item) =>\n {\n newList.Add((ICloneable)item.Clone());\n });\n ICloneable ICloneable ICloneable List<YourType> oldList = new List<YourType>();\nList<YourType> newList = new List<YourType>(oldList.Count);\n\noldList.ForEach((item)=>\n {\n newList.Add(new YourType(item));\n });\n ICloneable YourType.CopyFrom(YourType itemToCopy) YourType"
},
{
"answer_id": 222626,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "List<int> newList = new List<int>(oldList);\n List<T> Clone<T>(IEnumerable<T> oldList)\n{\n return newList = new List<T>(oldList);\n}\n List<string> myNewList = Clone(myOldList);\n"
},
{
"answer_id": 222640,
"author": "ajm",
"author_id": 18984,
"author_profile": "https://Stackoverflow.com/users/18984",
"pm_score": 10,
"selected": true,
"text": "static class Extensions\n{\n public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable\n {\n return listToClone.Select(item => (T)item.Clone()).ToList();\n }\n}\n"
},
{
"answer_id": 222761,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 7,
"selected": false,
"text": "public static object DeepClone(object obj) \n{\n object objResult = null;\n\n using (var ms = new MemoryStream())\n {\n var bf = new BinaryFormatter();\n bf.Serialize(ms, obj);\n\n ms.Position = 0;\n objResult = bf.Deserialize(ms);\n }\n\n return objResult;\n}\n [Serializable()]"
},
{
"answer_id": 5778243,
"author": "pratik",
"author_id": 723702,
"author_profile": "https://Stackoverflow.com/users/723702",
"pm_score": 2,
"selected": false,
"text": "public static Object CloneType(Object objtype)\n{\n Object lstfinal = new Object();\n\n using (MemoryStream memStream = new MemoryStream())\n {\n BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));\n binaryFormatter.Serialize(memStream, objtype); memStream.Seek(0, SeekOrigin.Begin);\n lstfinal = binaryFormatter.Deserialize(memStream);\n }\n\n return lstfinal;\n}\n"
},
{
"answer_id": 6759706,
"author": "Ajith",
"author_id": 853645,
"author_profile": "https://Stackoverflow.com/users/853645",
"pm_score": 5,
"selected": false,
"text": "public static T DeepClone<T>(T obj)\n{\n T objResult;\n using (MemoryStream ms = new MemoryStream())\n {\n BinaryFormatter bf = new BinaryFormatter();\n bf.Serialize(ms, obj);\n ms.Position = 0;\n objResult = (T)bf.Deserialize(ms);\n }\n return objResult;\n}\n"
},
{
"answer_id": 7684037,
"author": "Peter",
"author_id": 333427,
"author_profile": "https://Stackoverflow.com/users/333427",
"pm_score": 2,
"selected": false,
"text": "public class CloneableList<T> : List<T>, ICloneable where T : ICloneable\n{\n public object Clone()\n {\n var clone = new List<T>();\n ForEach(item => clone.Add((T)item.Clone()));\n return clone;\n }\n}\n"
},
{
"answer_id": 14865133,
"author": "Derek Liang",
"author_id": 995960,
"author_profile": "https://Stackoverflow.com/users/995960",
"pm_score": 4,
"selected": false,
"text": "Mapper.CreateMap<YourType, YourType>();\n YourTypeList.ConvertAll(Mapper.Map<YourType, YourType>);\n"
},
{
"answer_id": 16983192,
"author": "Furkan Katı",
"author_id": 2463322,
"author_profile": "https://Stackoverflow.com/users/2463322",
"pm_score": 2,
"selected": false,
"text": "namespace extension\n{\n public class ext\n {\n public static List<double> clone(this List<double> t)\n {\n List<double> kop = new List<double>();\n int x;\n for (x = 0; x < t.Count; x++)\n {\n kop.Add(t[x]);\n }\n return kop;\n }\n };\n\n}\n public class matrix\n{\n public List<List<double>> mat;\n public int rows,cols;\n public matrix clone()\n { \n // create new object\n matrix copy = new matrix();\n // firstly I can directly copy rows and cols because they are value types\n copy.rows = this.rows; \n copy.cols = this.cols;\n // but now I can no t directly copy mat because it is not value type so\n int x;\n // I assume I have clone method for List<double>\n for(x=0;x<this.mat.count;x++)\n {\n copy.mat.Add(this.mat[x].clone());\n }\n // then mat is cloned\n return copy; // and copy of original is returned \n }\n};\n"
},
{
"answer_id": 17448286,
"author": "Kamil Budziewski",
"author_id": 1714342,
"author_profile": "https://Stackoverflow.com/users/1714342",
"pm_score": 0,
"selected": false,
"text": "static class CollectionExtensions\n{\n public static ICollection<T> Clone<T>(this ICollection<T> listToClone)\n {\n var array = new T[listToClone.Count];\n listToClone.CopyTo(array,0);\n return array.ToList();\n }\n}\n"
},
{
"answer_id": 19729043,
"author": "ProfNimrod",
"author_id": 728065,
"author_profile": "https://Stackoverflow.com/users/728065",
"pm_score": 4,
"selected": false,
"text": "List<T> newList = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(listToCopy))\n"
},
{
"answer_id": 27966469,
"author": "JHaps",
"author_id": 2407900,
"author_profile": "https://Stackoverflow.com/users/2407900",
"pm_score": 0,
"selected": false,
"text": "ToArray Array.Clone(...)"
},
{
"answer_id": 31342925,
"author": "Jader Feijo",
"author_id": 434474,
"author_profile": "https://Stackoverflow.com/users/434474",
"pm_score": 4,
"selected": false,
"text": "List<T> List<T> myList = ...;\nList<T> cloneOfMyList = new List<T>(myList);\n myList cloneOfMyList"
},
{
"answer_id": 32374266,
"author": "Adam Lewis",
"author_id": 5296503,
"author_profile": "https://Stackoverflow.com/users/5296503",
"pm_score": 0,
"selected": false,
"text": "// Example Usage\nint[] indexes = getRandomUniqueIndexArray(selectFrom.Length, toSet.Length);\n\nfor(int i = 0; i < toSet.Length; i++)\n toSet[i] = selectFrom[indexes[i]];\n\n\nprivate int[] getRandomUniqueIndexArray(int length, int count)\n{\n if(count > length || count < 1 || length < 1)\n return new int[0];\n\n int[] toReturn = new int[count];\n if(count == length)\n {\n for(int i = 0; i < toReturn.Length; i++) toReturn[i] = i;\n return toReturn;\n }\n\n Random r = new Random();\n int startPos = count - 1;\n for(int i = startPos; i >= 0; i--)\n {\n int index = r.Next(length - i);\n for(int j = startPos; j > i; j--)\n if(toReturn[j] >= index)\n toReturn[j]++;\n toReturn[i] = index;\n }\n\n return toReturn;\n}\n"
},
{
"answer_id": 34365709,
"author": "Roma Borodov",
"author_id": 4711853,
"author_profile": "https://Stackoverflow.com/users/4711853",
"pm_score": 0,
"selected": false,
"text": "[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]\npublic class Person\n{\n ...\n Job JobDescription\n ...\n}\n\n[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]\npublic class Job\n{...\n}\n\nprivate static readonly Type stringType = typeof (string);\n\npublic static class CopyFactory\n{\n static readonly Dictionary<Type, PropertyInfo[]> ProperyList = new Dictionary<Type, PropertyInfo[]>();\n\n private static readonly MethodInfo CreateCopyReflectionMethod;\n\n static CopyFactory()\n {\n CreateCopyReflectionMethod = typeof(CopyFactory).GetMethod(\"CreateCopyReflection\", BindingFlags.Static | BindingFlags.Public);\n }\n\n public static T CreateCopyReflection<T>(T source) where T : new()\n {\n var copyInstance = new T();\n var sourceType = typeof(T);\n\n PropertyInfo[] propList;\n if (ProperyList.ContainsKey(sourceType))\n propList = ProperyList[sourceType];\n else\n {\n propList = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);\n ProperyList.Add(sourceType, propList);\n }\n\n foreach (var prop in propList)\n {\n var value = prop.GetValue(source, null);\n prop.SetValue(copyInstance,\n value != null && prop.PropertyType.IsClass && prop.PropertyType != stringType ? CreateCopyReflectionMethod.MakeGenericMethod(prop.PropertyType).Invoke(null, new object[] { value }) : value, null);\n }\n\n return copyInstance;\n }\n var person = new Person\n {\n ...\n };\n\n for (var i = 0; i < 1000000; i++)\n {\n personList.Add(person);\n }\n var watcher = new Stopwatch();\n watcher.Start();\n var copylist = personList.Select(CopyFactory.CreateCopyReflection).ToList();\n watcher.Stop();\n var elapsed = watcher.Elapsed;\n Serializer.DeepClone(personList);\n"
},
{
"answer_id": 34407506,
"author": "user3245269",
"author_id": 3245269,
"author_profile": "https://Stackoverflow.com/users/3245269",
"pm_score": 2,
"selected": false,
"text": "public static List<T> Clone<T>(this List<T> oldList)\n{\n var newList = new List<T>(oldList.Capacity);\n newList.AddRange(oldList);\n return newList;\n}\n"
},
{
"answer_id": 36527173,
"author": "shahrooz.bazrafshan",
"author_id": 6183397,
"author_profile": "https://Stackoverflow.com/users/6183397",
"pm_score": 2,
"selected": false,
"text": " public List<TEntity> Clone<TEntity>(List<TEntity> o1List) where TEntity : class , new()\n {\n List<TEntity> retList = new List<TEntity>();\n try\n {\n Type sourceType = typeof(TEntity);\n foreach(var o1 in o1List)\n {\n TEntity o2 = new TEntity();\n foreach (PropertyInfo propInfo in (sourceType.GetProperties()))\n {\n var val = propInfo.GetValue(o1, null);\n propInfo.SetValue(o2, val);\n }\n retList.Add(o2);\n }\n return retList;\n }\n catch\n {\n return retList;\n }\n }\n"
},
{
"answer_id": 40508693,
"author": "F.H.",
"author_id": 2906568,
"author_profile": "https://Stackoverflow.com/users/2906568",
"pm_score": 3,
"selected": false,
"text": "public static T DeepCopy<T>(this T value)\n{\n JavaScriptSerializer js = new JavaScriptSerializer();\n\n string json = js.Serialize(value);\n\n return js.Deserialize<T>(json);\n}\n public static T DeepCopy<T>(this T value)\n{\n string json = JsonConvert.SerializeObject(value);\n\n return JsonConvert.DeserializeObject<T>(json);\n}\n"
},
{
"answer_id": 41759372,
"author": "Albert arnau",
"author_id": 4210556,
"author_profile": "https://Stackoverflow.com/users/4210556",
"pm_score": 0,
"selected": false,
"text": "using Newtonsoft.Json;\n\nstatic class typeExtensions\n{\n [Extension()]\n public static T jsonCloneObject<T>(T source)\n {\n string json = JsonConvert.SerializeObject(source);\n return JsonConvert.DeserializeObject<T>(json);\n }\n}\n obj clonedObj = originalObj.jsonCloneObject;\n"
},
{
"answer_id": 46396131,
"author": "Xavier John",
"author_id": 1394827,
"author_profile": "https://Stackoverflow.com/users/1394827",
"pm_score": 6,
"selected": false,
"text": "Microsoft (R) Roslyn C# Compiler version 2.3.2.62116\nLoading context from 'CSharpInteractive.rsp'.\nType \"#help\" for more information.\n> var x = new List<int>() { 3, 4 };\n> var y = x.ToList();\n> x.Add(5)\n> x\nList<int>(3) { 3, 4, 5 }\n> y\nList<int>(2) { 3, 4 }\n> \n"
},
{
"answer_id": 48848578,
"author": "Steve",
"author_id": 3396597,
"author_profile": "https://Stackoverflow.com/users/3396597",
"pm_score": 2,
"selected": false,
"text": " //try this\n List<string> ListCopy= new List<string>(OldList);\n //or try\n List<T> ListCopy=OldList.ToList();\n"
},
{
"answer_id": 54294849,
"author": "John Kurtz",
"author_id": 2928659,
"author_profile": "https://Stackoverflow.com/users/2928659",
"pm_score": 2,
"selected": false,
"text": "public interface IMyCloneable<T>\n{\n T Clone();\n}\n public static List<T> Clone<T>(this List<T> listToClone) where T : IMyCloneable<T>\n{\n return listToClone.Select(item => (T)item.Clone()).ToList();\n}\n public class VidMark : IMyCloneable<VidMark>\n{\n public long Beg { get; set; }\n public long End { get; set; }\n public string Desc { get; set; }\n public int Rank { get; set; } = 0;\n\n public VidMark Clone()\n {\n return (VidMark)this.MemberwiseClone();\n }\n}\n private List<VidMark> _VidMarks;\nprivate List<VidMark> _UndoVidMarks;\n\n//Other methods instantiate and fill the lists\n\nprivate void SetUndoVidMarks()\n{\n _UndoVidMarks = _VidMarks.Clone();\n}\n"
},
{
"answer_id": 54902498,
"author": "Thomas Cerny",
"author_id": 2009315,
"author_profile": "https://Stackoverflow.com/users/2009315",
"pm_score": 2,
"selected": false,
"text": "IList CloneList(IList list)\n{\n IList result;\n result = (IList)Activator.CreateInstance(list.GetType());\n foreach (object item in list) result.Add(item);\n return result;\n}\n List<T> Clone<T>(List<T> argument) => (List<T>)CloneList(argument);\n"
},
{
"answer_id": 56119843,
"author": "ztorstri",
"author_id": 2162802,
"author_profile": "https://Stackoverflow.com/users/2162802",
"pm_score": 3,
"selected": false,
"text": "public class Student\n{\n public Student(Student student)\n {\n FirstName = student.FirstName;\n LastName = student.LastName;\n }\n\n public string FirstName { get; set; }\n public string LastName { get; set; }\n}\n\n// wherever you have the list\nList<Student> students;\n\n// and then where you want to make a copy\nList<Student> copy = students.Select(s => new Student(s)).ToList();\n using System.Linq\n"
},
{
"answer_id": 65511416,
"author": "Zeyad",
"author_id": 9731189,
"author_profile": "https://Stackoverflow.com/users/9731189",
"pm_score": 0,
"selected": false,
"text": "public List<T> CloneList<T>(IEnumerable<T> listToClone) {\n Type listType = listToClone.GetType();\n Type elementType = listType.GetGenericArguments()[0];\n List<T> listCopy = new List<T>();\n foreach (T item in listToClone) {\n object itemCopy = Activator.CreateInstance(elementType);\n foreach (PropertyInfo property in elementType.GetProperties()) {\n elementType.GetProperty(property.Name).SetValue(itemCopy, property.GetValue(item));\n }\n listCopy.Add((T)itemCopy);\n }\n return listCopy;\n}\n"
},
{
"answer_id": 68555809,
"author": "Martin Zaloga",
"author_id": 4273469,
"author_profile": "https://Stackoverflow.com/users/4273469",
"pm_score": 2,
"selected": false,
"text": "public static IEnumerable<T> DeepCopy<T>(this IEnumerable<T> collectionToDeepCopy)\n{\n var serializedCollection = JsonConvert.SerializeObject(collectionToDeepCopy);\n return JsonConvert.DeserializeObject<IEnumerable<T>>(serializedCollection);\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30025/"
] |
222,601
|
<p>Why is it that in a C# switch statement, for a variable used in multiple cases, you only declare it in the first case?</p>
<p>For example, the following throws the error "A local variable named 'variable' is already defined in this scope".</p>
<pre><code>switch (Type)
{
case Type.A:
string variable = "x";
break;
case Type.B:
string variable = "y";
break;
}
</code></pre>
<p>However, per the logic, the initial declaration should not be hit if the type is <code>Type.B</code>. Do all variables within a switch statement exist in a single scope, and are they created/allocated before any logic is processed?</p>
|
[
{
"answer_id": 222617,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "switch (Type)\n{\nstring variable;\n\n case Type.A:\n variable = \"x\";\n break;\n case Type.B:\n variable = \"y\";\n break;\n}\n"
},
{
"answer_id": 222683,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 8,
"selected": false,
"text": "switch (Type)\n{\n case Type.A:\n {\n string variable = \"x\";\n /* Do other stuff with variable */\n }\n break;\n\n case Type.B:\n {\n string variable = \"y\";\n /* Do other stuff with variable */\n }\n break;\n}\n"
},
{
"answer_id": 24319771,
"author": "percebus",
"author_id": 1361858,
"author_profile": "https://Stackoverflow.com/users/1361858",
"pm_score": -1,
"selected": false,
"text": "switch C C++ switch GOTO: : case switch Enum break case switch(mood)\n{\n case Mood.BORED:\n case Mood.HAPPY:\n drink(oBeer) // will drink if bored OR happy\nbreak;\n\n case Mood.SAD: // unnecessary but proofs a concept\n default:\n drink(oCoffee)\nbreak;\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10693/"
] |
222,606
|
<p>I need a way to detect mouse/keyboard activity on Linux. Something similar to what any IM program would do. If no activity is detected for, say 5 minutes, it will set your IM status to "I'm not here right now".</p>
<p>Any help towards this is appreciated.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 222624,
"author": "Keith Twombley",
"author_id": 23866,
"author_profile": "https://Stackoverflow.com/users/23866",
"pm_score": 2,
"selected": false,
"text": "who -u -H"
},
{
"answer_id": 223026,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "xidle man 3 XScreenSaver XIDLE"
},
{
"answer_id": 4671833,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 2,
"selected": false,
"text": "# cpan -i X11::IdleTime; sleep 2; perl -MX11::IdleTime -e 'print GetIdleTime(), $/;'\n"
},
{
"answer_id": 4702411,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 5,
"selected": false,
"text": "cat>/tmp/idletime.c<<EOF\n#include <time.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <X11/Xlib.h>\n#include <X11/Xutil.h>\n#include <X11/extensions/scrnsaver.h>\n\nint GetIdleTime () {\n time_t idle_time;\n static XScreenSaverInfo *mit_info;\n Display *display;\n int screen;\n mit_info = XScreenSaverAllocInfo();\n if((display=XOpenDisplay(NULL)) == NULL) { return(-1); }\n screen = DefaultScreen(display);\n XScreenSaverQueryInfo(display, RootWindow(display,screen), mit_info);\n idle_time = (mit_info->idle) / 1000;\n XFree(mit_info);\n XCloseDisplay(display); \n return idle_time;\n}\n\nint main() {\n printf(\"%d\\n\", GetIdleTime());\n return 0;\n}\nEOF\n\ngcc -Wall /tmp/idletime.c -o /tmp/idletime -L/usr/X11R6/lib/ -lX11 -lXext -lXss \nDISPLAY=:0 /tmp/idletime\n"
},
{
"answer_id": 7324044,
"author": "rosch",
"author_id": 931246,
"author_profile": "https://Stackoverflow.com/users/931246",
"pm_score": 5,
"selected": false,
"text": "xprintidle"
},
{
"answer_id": 50919424,
"author": "shitpoet",
"author_id": 3167374,
"author_profile": "https://Stackoverflow.com/users/3167374",
"pm_score": 2,
"selected": false,
"text": "xprintidle #!/bin/sh\nidletime=$(xprintidle)\nthreshold=300000 # 5 min = 5 * 60 * 1000 ms\nif [ \"$idletime\" -gt \"$threshold\" ]; then\n echo \"idle\"\nfi\n xprintidle"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
222,629
|
<p>I have this simple regex,</p>
<pre><code>[\d]{1,5}
</code></pre>
<p>that matches any integer between 0 and 99999.</p>
<p>How would I modify it so that it didn't match 0, but matches 01 and 10, etc?</p>
<p>I know there is a way to do an OR like so...</p>
<pre><code>[\d]{1,5}|[^0]{1}
</code></pre>
<p>(doesn't make much sense)</p>
<p>There a way to do an AND?</p>
|
[
{
"answer_id": 222675,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "[1-9]\\d{0,4}\n ^0*[1-9]\\d{0,4}$\n"
},
{
"answer_id": 222701,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "^(?=regex1)(?=regex2)(?=regex3).*\n (?= ) ^(?=\\d{1,5}$)(?=.*?[1-9]).*\n"
},
{
"answer_id": 222717,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "^([1-9][0-9]{0,4}|[0-9]{,1}[1-9][0-9]{,3}|[0-9]{,2}[1-9][0-9]{,2}|[0-9]{,3}[1-9][0-9]|[0-9]{,4}[1-9])$\n"
},
{
"answer_id": 222738,
"author": "Rontologist",
"author_id": 13925,
"author_profile": "https://Stackoverflow.com/users/13925",
"pm_score": 1,
"selected": false,
"text": "var str = user_string;\nif ('0' != str && str.matches(/^\\d{1,5}$/) {\n // code for match\n}\n var str = user_string;\nif (!str.matches(/^0+$/) && str.matches(/^\\d{1,5}$/) {\n // code for match\n}\n"
},
{
"answer_id": 222770,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "#!/bin/perl -w\n\nwhile (<>)\n{\n chomp;\n print \"OK: $_\\n\" if m/^(?!0+$)\\d{1,6}$/;\n}\n 0\n00\n000\n0000\n00000\n000000\n0000001\n000001\nOK: 000001\n101\nOK: 101\n01\nOK: 01\n00001\nOK: 00001\n1000\nOK: 1000\n101\nOK: 101\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
] |
222,630
|
<p>I'm in the process of making my PHP site Unicode-aware. I'm wondering if anyone has experience with the <code>mbstring.func_overload</code> setting, which replaces the normal string functions (e.g. <code>strlen</code>) with their multi-byte equivalents (<code>mb_strlen</code>). There aren't any comments on the PHP manual page.</p>
<p>Are there any potential problems that I should be aware of? Any cases where calling the multi-byte version is a bad idea?</p>
<p>I suppose one example would be functions that deal with encryption, since they may expect to deal with strings of bytes, rather than strings of characters.</p>
<p>Also, the manual page includes a note: "It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour."</p>
<p>Does that mean that it's not stable in a per-directory context, or it's generally not stable? The wording is unclear.</p>
|
[
{
"answer_id": 222664,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "strlen()"
},
{
"answer_id": 8985225,
"author": "gphilip",
"author_id": 397935,
"author_profile": "https://Stackoverflow.com/users/397935",
"pm_score": 3,
"selected": false,
"text": "mbstring.func_overload mbstring.internal_encoding func_overload"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4321/"
] |
222,649
|
<p>We are seeing this error in a Winform application. Can anyone help on why you would see this error, and more importantly how to fix it or avoid it from happening.</p>
<pre>
System.ComponentModel.Win32Exception: Error creating window handle.
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.OnVisibleChanged(EventArgs e)
at System.Windows.Forms.ButtonBase.OnVisibleChanged(EventArgs e)
</pre>
|
[
{
"answer_id": 9811589,
"author": "xlthim",
"author_id": 1284318,
"author_profile": "https://Stackoverflow.com/users/1284318",
"pm_score": 1,
"selected": false,
"text": "if (_form.Handle.ToInt32() > 0)\n{\n _form.Invoke(method, args);\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
222,652
|
<p>A UITableViewCell comes "pre-built" with a UILabel as its one and only subview after you've init'ed it. I'd <em>really</em> like to change the background color of said label, but no matter what I do the color does not change. The code in question:</p>
<pre><code>UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkGrayColor];
label.opaque = YES;
</code></pre>
|
[
{
"answer_id": 222685,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 4,
"selected": true,
"text": "initWithFrame:reuseIdentifier: UILabel UILabel"
},
{
"answer_id": 223437,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 2,
"selected": false,
"text": "UILabel* label = [[[UILabel alloc] init] autorelease];\nlabel.textColor = [UIColor whiteColor];\nlabel.backgroundColor = [UIColor darkGrayColor];\nlabel.opaque = YES;\n[cell.contentView addSubview:label];\n"
},
{
"answer_id": 4119623,
"author": "TomSwift",
"author_id": 291788,
"author_profile": "https://Stackoverflow.com/users/291788",
"pm_score": 3,
"selected": false,
"text": "- (void) layoutSubviews\n{ \n [super layoutSubviews];\n\n self.textLabel.backgroundColor = [UIColor redColor];\n}\n"
},
{
"answer_id": 12298601,
"author": "Manikandan",
"author_id": 1222747,
"author_profile": "https://Stackoverflow.com/users/1222747",
"pm_score": 0,
"selected": false,
"text": "for (UIView *views in views.subviews)\n{\n UILabel* temp = (UILabel*)[views.subviews objectAtIndex:0];\n temp.textColor = [UIColor whiteColor]; \n temp.shadowColor = [UIColor blackColor];\n temp.shadowOffset = CGSizeMake(0.0f, -1.0f);\n} \n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23498/"
] |
222,655
|
<p>If you create a class library that uses things from other assemblies, is it possible to embed those other assemblies inside the class library as some kind of resource?</p>
<p>I.e. instead of having <em>MyAssembly.dll</em>, <em>SomeAssembly1.dll</em> and <em>SomeAssembly2.dll</em> sitting on the file system, those other two files get bundled in to <em>MyAssembly.dll</em> and are usable in its code.</p>
<hr>
<p>I'm also a little confused about why .NET assemblies are <em>.dll</em> files. Didn't this format exist before .NET? Are all .NET assemblies DLLs, but not all DLLs are .NET assemblies? Why do they use the same file format and/or file extension?</p>
|
[
{
"answer_id": 222680,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "ResourceManager"
},
{
"answer_id": 625115,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 6,
"selected": false,
"text": " static NameOfStartupClassHere()\n {\n AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolver);\n }\n\n static System.Reflection.Assembly Resolver(object sender, ResolveEventArgs args)\n {\n Assembly a1 = Assembly.GetExecutingAssembly();\n Stream s = a1.GetManifestResourceStream(args.Name);\n byte[] block = new byte[s.Length];\n s.Read(block, 0, block.Length);\n Assembly a2 = Assembly.Load(block);\n return a2;\n }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82/"
] |
222,661
|
<p>VB.net web system with a SQL Server 2005 backend. I've got a stored procedure that returns a varchar, and we're finally getting values that won't fit in a varchar(8000).</p>
<p>I've changed the return parameter to a varchar(max), but how do I tell the OleDbParameter.Size Property to accept any amount of text?</p>
<p>As a concrete example, the VB code that got the return parameter from the stored procedure used to look like:</p>
<pre><code>objOutParam1 = objCommand.Parameters.Add("@RStr", OleDbType.varchar)
objOutParam1.Size = 8000
objOutParam1.Direction = ParameterDirection.Output
</code></pre>
<p>What can I make .Size to work with a (max)?</p>
<p>Update:</p>
<p>To answer some questions:</p>
<p>For all intents and purposes, this text all needs to come out as one chunk. (Changing that would take more structural work than I want to do - or am authorized for, really.)</p>
<p>If I don't set a size, I get an error reading "String[6]: the Size property has an invalid size of 0."</p>
|
[
{
"answer_id": 222694,
"author": "Ed Altorfer",
"author_id": 26552,
"author_profile": "https://Stackoverflow.com/users/26552",
"pm_score": 3,
"selected": false,
"text": "SqlParameter p = new SqlParameter(\"@RStr\", SqlDbType.VarChar);\np.Direction = ParameterDirection.Output;\n"
},
{
"answer_id": 222734,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "objOutParam1.Size = Int32.MaxValue;\n"
},
{
"answer_id": 264793,
"author": "PaulB",
"author_id": 29432,
"author_profile": "https://Stackoverflow.com/users/29432",
"pm_score": 0,
"selected": false,
"text": " param.Size = int.MaxValue;\n param.SqlDbType = SqlDbType.VarBinary;\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
222,681
|
<p>I'm lead to believe that I cannot count on the order of items added to a dictionary for enumeration purposes.</p>
<p><strong>Is there a class (generic if possible) to which items may be added with a key and which can be enumerated in addition order or which can be retrieved by key?</strong></p>
<p>Clarification: I do not want to enumerate in Key Order. I want to enumerate in addition order. Which is to say that I want to be able to retrieve the items via enumeration on a FIFO ( first in first out) basis.</p>
|
[
{
"answer_id": 222695,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 2,
"selected": false,
"text": "List Dictionary SortedDictionary KeyedCollection"
},
{
"answer_id": 222742,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 3,
"selected": true,
"text": "SortedDictionary IComparer IComparer SortedDictionary HashedLinkedList<KeyValuePair<T>> HashedLinkedList<T> IEqualityComparer Find(ref T x) T SortedDictionary LinkedList IDirectedEnumerable"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] |
222,688
|
<p>In a WinForms UserControl, I would pass data to the main GUI thread by calling this.BeginInvoke() from any of the control's methods. What's the equivalent in a Silverlight UserControl?</p>
<p>In other words, how can I take data provided by an arbitrary worker thread and ensure that it gets processed on the main displatch thread?</p>
|
[
{
"answer_id": 222744,
"author": "Timothy Lee Russell",
"author_id": 12919,
"author_profile": "https://Stackoverflow.com/users/12919",
"pm_score": 4,
"selected": true,
"text": "private void UpdateStatus()\n{\n this.Dispatcher.BeginInvoke( delegate { StatusLabel.Text = \"Updated\"; });\n}\n"
},
{
"answer_id": 7051556,
"author": "Ernest Poletaev",
"author_id": 771098,
"author_profile": "https://Stackoverflow.com/users/771098",
"pm_score": 2,
"selected": false,
"text": " private void UpdateStatus()\n {\n // check if we not in main thread\n if(!this.Dispatcher.CheckAccess())\n {\n // call same method in main thread\n this.Dispatcher.BeginInvoke( UpdateStatus );\n return;\n }\n\n // in main thread now\n StatusLabel.Text = \"Updated\";\n }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] |
222,716
|
<p>I am interested in writing a simplistic navigation application as a pet project. After searching around for free map-data I have settled on the <a href="http://www.census.gov/geo/www/tiger/tgrshp2007/tgrshp2007.html" rel="nofollow noreferrer">US Census Bureau TIGER</a> 2007 Line/Shapefile map data. The data is split up into zip files for individual counties and I've downloaded a single counties map-data for my area.</p>
<p><strong>What would be the best way to read in this map-data into a useable format?</strong> </p>
<p>How should I:</p>
<ul>
<li>Read in these files</li>
<li>Parse them - Regular expression or some library that can already parse these Shapefiles?</li>
<li>Load the data into my application - Should I load the points directly into some datastructure in memory? Use a small database? I have no need for persistence once you close the application of the map data. The user can load the Shapefile again.</li>
</ul>
<p><strong>What would be the best way to render the map once I have read the in the Shapefile data?</strong></p>
<p>Ideally I'd like to be able to read in a counties map data shapefile and render all the poly-lines onto the screen and allow rotating and scaling.</p>
<p>How should I:</p>
<ul>
<li>Convert lat/lon points to screen coordinates? - As far as I know the Shapefile uses longitude and latitude for its points. So obviously I'm going to have to convert these somehow to screen coordinates to display the map features.</li>
<li>Render the map data (A series of polylines for roads, boundaries, etc) in a way that I can easily rotate and scale the entire map?</li>
<li>Render my whole map as a series of "tiles" so only the features/lines within the viewing area are rendered?</li>
</ul>
<p>Ex. of TIGER data rendered as a display map:<br>
<img src="https://i.stack.imgur.com/mNJ9X.png" alt="alt text"></p>
<p>Anyone with some experience and insight into what the best way for me to read in these files, how I should represent them (database, in memory datastructure) in my program, and how I should render (with rotating/scaling) the map-data on screen would be appreciated. </p>
<p>EDIT: To clarify, I do not want to use any Google or Yahoo maps API. Similarly, I don't want to use OpenStreetMap. I'm looking for a more from-scratch approach than utilizing those apis/programs. This will be a <strong>desktop</strong> application.</p>
|
[
{
"answer_id": 494602,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": false,
"text": "x x"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
] |
222,740
|
<p>I have an HTML input box</p>
<pre><code><input type="text" id="foo" value="bar">
</code></pre>
<p>I've attached a handler for the '<em>keyup</em>' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be!</p>
<p>I've tried picking up '<em>keypress</em>' and '<em>change</em>' events, same problem. </p>
<p>I'm sure this is simple to solve, but at present I think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the future!</p>
<p><em>Is there anyway to obtain the current value during those events?</em></p>
<p>EDIT: looks like I had a caching problem with my js file as I checked the same code later on and it worked just fine. I would delete the question, but not sure if that loses rep for the kind folk who posted ideas :)</p>
|
[
{
"answer_id": 222767,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 6,
"selected": true,
"text": "function showMe(e) {\n// i am spammy!\n alert(e.value);\n}\n....\n<input type=\"text\" id=\"foo\" value=\"bar\" onkeyup=\"showMe(this)\" />\n"
},
{
"answer_id": 222768,
"author": "domgblackwell",
"author_id": 16954,
"author_profile": "https://Stackoverflow.com/users/16954",
"pm_score": 1,
"selected": false,
"text": "keypress change keyup"
},
{
"answer_id": 222780,
"author": "Neal Swearer",
"author_id": 29962,
"author_profile": "https://Stackoverflow.com/users/29962",
"pm_score": 2,
"selected": false,
"text": "<html>\n <head>\n <script>\n function callme(field) {\n alert(\"field:\" + field.value);\n }\n </script>\n </head>\n <body>\n <form name=\"f1\">\n <input type=\"text\" onkeyup=\"callme(this);\" name=\"text1\">\n </form>\n </body>\n</html>\n"
},
{
"answer_id": 222788,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 1,
"selected": false,
"text": "<html>\n<head>\n <script type=\"text/javascript\" src=\"jquery.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function() {\n $('#foo').keyup(function(e) {\n var v = $('#foo').val();\n $('#debug').val(v);\n })\n });\n </script>\n</head>\n<body>\n <form>\n <input type=\"text\" id=\"foo\" value=\"bar\"><br>\n <textarea id=\"debug\"></textarea>\n </form>\n</body>\n</html>\n"
},
{
"answer_id": 33945348,
"author": "Jonatas Walker",
"author_id": 4640499,
"author_profile": "https://Stackoverflow.com/users/4640499",
"pm_score": 4,
"selected": false,
"text": "var onChange = function(evt) {\n console.info(this.value);\n // or\n console.info(evt.target.value);\n};\nvar input = document.getElementById('some-id');\ninput.addEventListener('input', onChange, false);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6521/"
] |
222,752
|
<p>I have the following tuple, which contains tuples:</p>
<pre><code>MY_TUPLE = (
('A','Apple'),
('C','Carrot'),
('B','Banana'),
)
</code></pre>
<p>I'd like to sort this tuple based upon the <strong>second</strong> value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 222762,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 6,
"selected": true,
"text": "from operator import itemgetter\n\nMY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))\n itemgetter MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))\n"
},
{
"answer_id": 222769,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 2,
"selected": false,
"text": "sorted(my_tuple, key=lambda tup: tup[1])\n"
},
{
"answer_id": 222776,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 3,
"selected": false,
"text": ">>> import operator \n>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]\n>>> map(operator.itemgetter(0), L)\n['c', 'd', 'a', 'b']\n>>> map(operator.itemgetter(1), L)\n[2, 1, 4, 3]\n>>> sorted(L, key=operator.itemgetter(1))\n[('d', 1), ('c', 2), ('b', 3), ('a', 4)]\n"
},
{
"answer_id": 222789,
"author": "Huuuze",
"author_id": 10040,
"author_profile": "https://Stackoverflow.com/users/10040",
"pm_score": -1,
"selected": false,
"text": "templist = [ (line[1], line) for line in MY_TUPLE ] \ntemplist.sort()\nSORTED_MY_TUPLE = [ line[1] for line in templist ]\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] |
222,755
|
<p>I am using Java Struts, sending it to user using the following codes</p>
<pre><code>response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileFullName);
</code></pre>
<p>Firstly I hope that this is the correct place for my question... :) I hope
that you can help me.</p>
<p>The error message I get when I try to open a file from Internet Explorer is</p>
<pre><code>"C:\Documents and Settings\USERNAME\Local Settings\Temporary Internet
Files\Content.IE5\QXJ0P436\btbillsdfjlsfjk.csv' could not be found"
</code></pre>
<p>I am trying to "Open" the csv file format into Excel. It allows me to
"Save" the file to which ever directory I want but I don't want to do that,
I would just like to open the file. This has always worked in the past so
I'm now wondering why the file is 'missing'.</p>
<p>Any ideas?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 222800,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "Expires: 0 Pragma: cache Cache-Control: private"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25368/"
] |
222,756
|
<p>Background:
I'm working on a silverlight (1.0) application that dynamically builds a map of the United States with icons and text overlayed at specific locations. The map works great in the browser and now I need to get a static (printable and insertable into documents/powerpoints) copy of a displayed map.</p>
<p>Objective:
In order to get a printable copy of the map that can also be used in powerpoint slides, word, etc. I've chosen to create an ASP.NET HttpHandler to recreate the xaml on the server side in WPF and then render the WPF to a bitmap image which is returned as a png file, generated at 300dpi for better print quality. </p>
<p>Problem:
This works great with one problem, I can't get the image to scale to a specified size. I've tried several different things, some of which can be seen in the commented out lines. I need to be able to specify a height and width of the image, either in inches or pixels, I don't necessarily care which, and have the xaml scale to that size for the generated bitmap. Currently, if I make the size bigger than the root canvas, the canvas gets rendered at its original size in the top left corner of the generated image at the size specified. Below is the important part of my httphandler. The root canvas stored as "MyImage" has a Height of 600 and a Width of 800. What am I missing to get the content to scale to fit the size specified?</p>
<p>I don't fully understand what the dimensions being passed into Arrange() and Measure() do as some of this code was taken from online examples. I also don't fully understand the RenderTargetBitmap stuff. Any guidance would be appreciated.</p>
<pre><code>Public Sub Capture(ByVal MyImage As Canvas)
' Determine the constraining scale to maintain the aspect ratio and the bounds of the image size
Dim scale As Double = Math.Min(Width / MyImage.Width, Height / MyImage.Height)
'Dim vbox As New Viewbox()
'vbox.Stretch = Stretch.Uniform
'vbox.StretchDirection = StretchDirection.Both
'vbox.Height = Height * scale * 300 / 96.0
'vbox.Width = Width * scale * 300 / 96.0
'vbox.Child = MyImage
Dim bounds As Rect = New Rect(0, 0, MyImage.Width * scale, MyImage.Height * scale)
MyImage.Measure(New Size(Width * scale, Height * scale))
MyImage.Arrange(bounds)
'MyImage.UpdateLayout()
' Create the target bitmap
Dim rtb As RenderTargetBitmap = New RenderTargetBitmap(CInt(Width * scale * 300 / 96.0), CInt(Height * scale * 300 / 96.0), 300, 300, PixelFormats.Pbgra32)
' Render the image to the target bitmap
Dim dv As DrawingVisual = New DrawingVisual()
Using ctx As DrawingContext = dv.RenderOpen()
Dim vb As New VisualBrush(MyImage)
'Dim vb As New VisualBrush(vbox)
ctx.DrawRectangle(vb, Nothing, New Rect(New System.Windows.Point(), bounds.Size))
End Using
rtb.Render(dv)
' Encode the image in the format selected
Dim encoder As System.Windows.Media.Imaging.BitmapEncoder
Select Case Encoding.ToLower
Case "jpg"
encoder = New System.Windows.Media.Imaging.JpegBitmapEncoder()
Case "png"
encoder = New System.Windows.Media.Imaging.PngBitmapEncoder()
Case "gif"
encoder = New System.Windows.Media.Imaging.GifBitmapEncoder()
Case "bmp"
encoder = New System.Windows.Media.Imaging.BmpBitmapEncoder()
Case "tif"
encoder = New System.Windows.Media.Imaging.TiffBitmapEncoder()
Case "wmp"
encoder = New System.Windows.Media.Imaging.WmpBitmapEncoder()
End Select
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb))
' Create the memory stream to save the encoded image.
retImageStream = New System.IO.MemoryStream()
encoder.Save(retImageStream)
retImageStream.Flush()
retImageStream.Seek(0, System.IO.SeekOrigin.Begin)
MyImage = Nothing
End Sub
</code></pre>
|
[
{
"answer_id": 224492,
"author": "Donnelle",
"author_id": 28074,
"author_profile": "https://Stackoverflow.com/users/28074",
"pm_score": 5,
"selected": true,
"text": "\nprivate void ExportCanvas(int width, int height)\n{\n string path = @\"c:\\temp\\Test.tif\";\n FileStream fs = new FileStream(path, FileMode.Create);\n\n\n RenderTargetBitmap renderBitmap = new RenderTargetBitmap(width,\n height, 1/300, 1/300, PixelFormats.Pbgra32);\n\n DrawingVisual visual = new DrawingVisual();\n using (DrawingContext context = visual.RenderOpen())\n {\n VisualBrush brush = new VisualBrush(MyCanvas);\n context.DrawRectangle(brush,\n null,\n new Rect(new Point(), new Size(MyCanvas.Width, MyCanvas.Height)));\n }\n\n visual.Transform = new ScaleTransform(width / MyCanvas.ActualWidth, height / MyCanvas.ActualHeight);\n\n renderBitmap.Render(visual);\n\n BitmapEncoder encoder = new TiffBitmapEncoder();\n encoder.Frames.Add(BitmapFrame.Create(renderBitmap));\n encoder.Save(fs);\n fs.Close();\n}\n"
},
{
"answer_id": 227339,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Public Sub Capture(ByVal MyImage As Canvas)\n ' Normally we would obtain a user's configured DPI setting to account for the possibilty of a high DPI setting. \n ' However, this code is running server side so the client's DPI is not obtainable.\n Const SCREEN_DPI As Double = 96.0 ' Screen DPI\n Const TARGET_DPI As Double = 300.0 ' Print Quality DPI\n\n ' Determine the constraining scale to maintain the aspect ratio and the bounds of the image size\n Dim scale As Double = Math.Min(Width * SCREEN_DPI / MyImage.Width, Height * SCREEN_DPI / MyImage.Height)\n\n ' Setup the bounds of the image\n Dim bounds As Rect = New Rect(0, 0, MyImage.Width * scale, MyImage.Height * scale)\n MyImage.Measure(New Size(MyImage.Width * scale, MyImage.Height * scale))\n MyImage.Arrange(bounds)\n\n ' Create the target bitmap\n Dim rtb As RenderTargetBitmap = New RenderTargetBitmap(CDbl(MyImage.Width * scale / SCREEN_DPI * TARGET_DPI), CDbl(MyImage.Height * scale / SCREEN_DPI * TARGET_DPI), TARGET_DPI, TARGET_DPI, PixelFormats.Pbgra32)\n\n ' Render the image to the target bitmap\n Dim dv As DrawingVisual = New DrawingVisual()\n Using ctx As DrawingContext = dv.RenderOpen()\n Dim vb As New VisualBrush(MyImage)\n ctx.DrawRectangle(vb, Nothing, New Rect(New System.Windows.Point(), bounds.Size))\n End Using\n ' Transform the visual to scale the image to our desired size.\n 'dv.Transform = New ScaleTransform(scale, scale)\n\n ' Render the visual to the bitmap.\n rtb.Render(dv)\n\n ' Encode the image in the format selected. If no valid format was selected, default to png.\n Dim encoder As System.Windows.Media.Imaging.BitmapEncoder\n Select Case Encoding.ToLower\n Case \"jpg\"\n encoder = New System.Windows.Media.Imaging.JpegBitmapEncoder()\n Case \"png\"\n encoder = New System.Windows.Media.Imaging.PngBitmapEncoder()\n Case \"gif\"\n encoder = New System.Windows.Media.Imaging.GifBitmapEncoder()\n Case \"bmp\"\n encoder = New System.Windows.Media.Imaging.BmpBitmapEncoder()\n Case \"tif\"\n encoder = New System.Windows.Media.Imaging.TiffBitmapEncoder()\n Case \"wmp\"\n encoder = New System.Windows.Media.Imaging.WmpBitmapEncoder()\n Case Else\n encoder = New System.Windows.Media.Imaging.PngBitmapEncoder()\n End Select\n encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb))\n\n ' Create the memory stream to save the encoded image.\n retImageStream = New System.IO.MemoryStream()\n encoder.Save(retImageStream)\n retImageStream.Flush()\n retImageStream.Seek(0, System.IO.SeekOrigin.Begin)\n MyImage = Nothing\n End Sub\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
222,760
|
<p>What's the better way to insert cell comments in excel 2007 files programmatically using c# and .net 3.5?</p>
|
[
{
"answer_id": 18343598,
"author": "Daniil Shevelev",
"author_id": 1515058,
"author_profile": "https://Stackoverflow.com/users/1515058",
"pm_score": 2,
"selected": false,
"text": "Excel.Range cell; \ncell.AddComment(\"My comment\");\n"
},
{
"answer_id": 37179261,
"author": "Cihan",
"author_id": 5003089,
"author_profile": "https://Stackoverflow.com/users/5003089",
"pm_score": 1,
"selected": false,
"text": "Excel._Worksheet oSheet =\n (Microsoft.Office.Interop.Excel._Worksheet) excelWorkbook.ActiveSheet;\noSheet.Cells[2, 3].Cells.AddComment(\"Selam\");\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30032/"
] |
222,772
|
<p>I wanted to compare the datetime which is in this format "7/20/2008" with the ones in the database which is in format "7/20/2008 7:14:53 AM".</p>
<p>I tried using "like" clause but it did not work beacuse the "like" clause uses only string and the one which I am using is date time format.</p>
<p>Can anyone tell how to convert and compare it in database and pull up datetime.</p>
<pre><code> protected void User_Querytime()
{
DataClasses2DataContext dc1 = new DataClasses2DataContext();
DateTime date1;
string date = Request.QueryString.Get("TimeOfMessage");
date1 = Convert.ToDateTime(date);
var query7 = from u in dc1.syncback_logs
where u.TimeOfMessage = date1
orderby u.TimeOfMessage descending
select u;
GridView1.DataSource = query7;
GridView1.DataBind();
}
</code></pre>
|
[
{
"answer_id": 222857,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 1,
"selected": false,
"text": " // Random Date Collection\n List<DateTime> dateTimes = new List<DateTime>();\n dateTimes.Add(DateTime.Parse(\"7/20/2008 7:14:53 AM\"));\n dateTimes.Add(DateTime.Parse(\"7/20/2008 7:14:54 AM\"));\n dateTimes.Add(DateTime.Parse(\"7/20/2009 7:14:53 AM\"));\n\n DateTime myDateTime = DateTime.Parse(\"7/20/2008\");\n\n var query = from d in dateTimes\n where d.ToShortDateString() == myDateTime.ToShortDateString()\n select d;\n"
},
{
"answer_id": 222881,
"author": "Jeremy Frey",
"author_id": 13412,
"author_profile": "https://Stackoverflow.com/users/13412",
"pm_score": 0,
"selected": false,
"text": "where u.TimeOfMessage.Date == date1\n"
},
{
"answer_id": 222901,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 0,
"selected": false,
"text": "TimeOfMessage TimeOfMessage.Date"
},
{
"answer_id": 222911,
"author": "Seth Petry-Johnson",
"author_id": 23632,
"author_profile": "https://Stackoverflow.com/users/23632",
"pm_score": 2,
"selected": false,
"text": "date1 List<DateTime> dateTimes = new List<DateTime>();\ndateTimes.Add(DateTime.Parse(\"7/20/2008 7:14:53 AM\"));\ndateTimes.Add(DateTime.Parse(\"7/20/2008 12:12:01 AM\"));\ndateTimes.Add(DateTime.Parse(\"7/21/2008 9:00:00 AM\"));\ndateTimes.Add(DateTime.Parse(\"7/20/2009 7:14:53 AM\"));\n\nDateTime targetDate = Convert.ToDateTime(\"7/20/2008\");\n\n// Remove time info from data in database\nvar matchingDates = from date in dateTimes\n where date.Date == targetDate\n select date;\n\n// Or use your target date to create a range\nDateTime rangeStart = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day, 0, 0, 0);\nDateTime rangeEnd = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day, 23, 59, 59);\n\nvar matchingDates2 = from date in dateTimes\n where (date >= rangeStart) && (date <= rangeEnd)\n select date;\n"
},
{
"answer_id": 12600043,
"author": "Sushant",
"author_id": 1559484,
"author_profile": "https://Stackoverflow.com/users/1559484",
"pm_score": 0,
"selected": false,
"text": "using System.Data.Objects;\n var bla = (from log in context.Contacts\n where EntityFunctions.TruncateTime(log.ModifiedDate) < today.Date\n select log).FirstOrDefault();\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
222,777
|
<p>I am working on a site laid out with <code>div</code>s. I am having trouble with one in particular: the training photo <code>div</code>.</p>
<p>If you go to <a href="http://php.wmsgroup.com/eofd6.org/education.html" rel="nofollow noreferrer">http://php.wmsgroup.com/eofd6.org/education.html</a> you'll see a photo underneath the left nav that has dropped down. I want it to snap right under that nav box. I have tried several different things with its positioning as well as the main content <code>div</code>s positioning and I can't get it right.</p>
<p>Any help would be appreciated. The link to the style sheet is <a href="http://php.wmsgroup.com/eofd6.org/in.css" rel="nofollow noreferrer">http://php.wmsgroup.com/eofd6.org/in.css</a></p>
<p>Thanks!</p>
|
[
{
"answer_id": 222829,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 1,
"selected": false,
"text": "<html>\n<head>\n <style type=\"text/css\">\n #leftColumn {\n width: 30%;\n margin: 0px;\n float: left;\n display: inline;\n clear: left;\n }\n\n #rightColumn{\n width: 60%; /* allow 10% for flex/margins */\n margin: 0px auto;\n float: left;\n display: inline; \n clear: right;\n }\n\n </style>\n</head>\n<body>\n <div id=\"pageWrapper\">\n <div id=\"header\"></div>\n <div id=\"leftColumn\">\n <div id=\"nav\"> </div>\n <div id=\"training_photo\"> </div>\n </div>\n <div id=\"rightColumn\">\n <div id=\"content\"> </content>\n </div>\n </div>\n <div id=\"footer\"> </footer>\n</body>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30043/"
] |
222,778
|
<p>I have an annoying problem which I might be able to somehow circumvent, but on the other hand would much rather be on top of it and understand what exactly is going on, since it looks like this stuff is really here to stay.</p>
<p>Here's the story: I have a simple OpenGL app which works fine: never a major problem in compiling, linking, or running it. Now I decided to try to move some of the more intensive calculations into a worker thread, in order to possibly make the GUI even more responsive — using Boost.Thread, of course.</p>
<p>In short, if I add the following fragment in the beginning of my .cpp file:</p>
<pre><code>#include <boost/thread/thread.hpp>
void dummyThreadFun() { while (1); }
boost::thread p(dummyThreadFun);
</code></pre>
<p>, then I start getting "This application has failed to start because MSVCP90.dll was not found" when trying to launch the Debug build. (Release mode works ok.)</p>
<p>Now looking at the executable using the Dependency Walker, who also does not find this DLL (which is expected I guess), I could see that we are looking for it in order to be able to call the following functions:</p>
<pre><code>?max@?$numeric_limits@K@std@@SAKXZ
?max@?$numeric_limits@_J@std@@SA_JXZ
?min@?$numeric_limits@K@std@@SAKXZ
?min@?$numeric_limits@_J@std@@SA_JXZ
</code></pre>
<p>Next, I tried to convert every instance of <code>min</code> and <code>max</code> to use macros instead, but probably couldn't find all references to them, as this did not help. (I'm using some external libraries for which I don't have the source code available. But even if I could do this — I don't think it's the right way really.)</p>
<p>So, my questions — I guess — are:</p>
<ol>
<li>Why do we look for a non-debug DLL even though working with the debug build?</li>
<li>What is the correct way to fix the problem? Or even a quick-and-dirty one?</li>
</ol>
<p>I had this first in a pretty much vanilla installation of Visual Studio 2008. Then tried installing the Feature Pack and SP1, but they didn't help either. Of course also tried to Rebuild several times.</p>
<p>I am using prebuilt binaries for Boost (v1.36.0). This is not the first time I use Boost in this project, but it may be the first time that I use a part that is based on a separate source.</p>
<p>Disabling incremental linking doesn't help. The fact that the program is OpenGL doesn't seem to be relevant either — I got a similar issue when adding the same three lines of code into a simple console program (but there it was complaining about MSVCR90.dll and <code>_mkdir</code>, and when I replaced the latter with <code>boost::create_directory</code>, the problem went away!!). And it's really just removing or adding those three lines that makes the program run ok, or not run at all, respectively.</p>
<p>I can't say I understand Side-by-Side (don't even know if this is related but that's what I assume for now), and to be honest, I am not super-interested either — as long as I can just build, debug and deploy my app...</p>
<hr>
<p><strong>Edit 1:</strong> While trying to build a stripped-down example that anyway reproduces the problem, I have discovered that the issue has to do with <a href="http://www.spread.org/" rel="nofollow noreferrer">the Spread Toolkit</a>, the use of which is a factor common to all my programs having this problem. (However, I never had this before starting to link in the Boost stuff.)</p>
<p>I have now come up with a minimal program that lets me reproduce the issue. It consists of two compilation units, A.cpp and B.cpp. </p>
<p>A.cpp:</p>
<pre><code>#include "sp.h"
int main(int argc, char* argv[])
{
mailbox mbox = -1;
SP_join(mbox, "foo");
return 0;
}
</code></pre>
<p>B.cpp:</p>
<pre><code>#include <boost/filesystem.hpp>
</code></pre>
<p>Some observations:</p>
<ol>
<li>If I comment out the line <code>SP_join</code> of A.cpp, the problem goes away.</li>
<li>If I comment out the single line of B.cpp, the problem goes away.</li>
<li>If I move or copy B.cpp's single line to the beginning or end of A.cpp, the problem goes away. </li>
</ol>
<p>(In scenarios 2 and 3, the program crashes when calling <code>SP_join</code>, but that's just because the mailbox is not valid... this has nothing to do with the issue at hand.)</p>
<p>In addition, Spread's core library is linked in, and that's surely part of the answer to my question #1, since there's no debug build of that lib in my system.</p>
<p>Currently, I'm trying to come up with something that'd make it possible to reproduce the issue in another environment. (Even though I will be quite surprised if it actually can be repeated outside my premises...)</p>
<hr>
<p><strong>Edit 2:</strong> Ok, so <a href="http://users.tkk.fi/jsreunan/BoostThreadTest.zip" rel="nofollow noreferrer">here</a> we now have a package using which I was able to reproduce the issue on an almost vanilla installation of WinXP32 + VS2008 + Boost 1.36.0 (still <a href="http://www.boostpro.com/products/free" rel="nofollow noreferrer">pre-built binaries from BoostPro Computing</a>). </p>
<p>The culprit is surely the Spread lib, my build of which somehow requires a rather archaic version of STLPort for <em>MSVC 6</em>! Nevertheless, I still find the symptoms relatively amusing. Also, it would be nice to hear if you can actually reproduce the issue — including scenarios 1-3 above. The package is quite small, and it should contain all the necessary pieces.</p>
<p>As it turns out, the issue did not really have anything to do with Boost.Thread specifically, as this example now uses the Boost Filesystem library. Additionally, it now complains about MSVCR90.dll, not P as previously.</p>
|
[
{
"answer_id": 222795,
"author": "Reunanen",
"author_id": 19254,
"author_profile": "https://Stackoverflow.com/users/19254",
"pm_score": 0,
"selected": false,
"text": "boost::posix_time::ptime pt = boost::posix_time::microsec_clock::universal_time();\n #include"
},
{
"answer_id": 223375,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "BOOST_THREAD_USE_DLL BOOST_THREAD_USE_DLL _DEBUG BOOST_XYZ config.hpp ptime config.hpp"
},
{
"answer_id": 223440,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 1,
"selected": false,
"text": "boost::posix::time BOOST_THREAD_USE_DLL BOOST_THREAD_USE_LIB boost::posix::time"
},
{
"answer_id": 225863,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 3,
"selected": true,
"text": "_DEBUG"
},
{
"answer_id": 228128,
"author": "Tom Barta",
"author_id": 29839,
"author_profile": "https://Stackoverflow.com/users/29839",
"pm_score": 1,
"selected": false,
"text": "d c cp #pragma comment(lib) /nodefaultlib:..."
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19254/"
] |
222,782
|
<p>So I'm in the process of getting GIT sold at work. First thing I need is to convince everyone that GIT is better at what they're already used to doing. We currently use Perforce. Anybody else go through a similar sale? Any good links/advice?</p>
<p>One of the big wins is that we can work with it disconnected from the network. Another win IMO is the way adds/checkouts are handled. More points are welcome! Also we have about 10-20 devs total.</p>
|
[
{
"answer_id": 223963,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 7,
"selected": true,
"text": "git-p4raw git bisect"
},
{
"answer_id": 10138304,
"author": "Svend Hansen",
"author_id": 779130,
"author_profile": "https://Stackoverflow.com/users/779130",
"pm_score": 2,
"selected": false,
"text": "git diff -//Server/mainline/.../target/... //Svend_Hansen_Server/.../target/...\n -//Server/mainline/projectA/target/... //Svend_Hansen_Server/projectA/target/...\n-//Server/mainline/projectB/target/... //Svend_Hansen_Server/projectB/target/...\n...\n git diff"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9401/"
] |
222,783
|
<p>What is the simplest way to get: <code>http://www.[Domain].com</code> in asp.net?</p>
<p>There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone?</p>
|
[
{
"answer_id": 222812,
"author": "SaaS Developer",
"author_id": 7215,
"author_profile": "https://Stackoverflow.com/users/7215",
"pm_score": 1,
"selected": false,
"text": "System.Web.UI.Page.Request.Url\n"
},
{
"answer_id": 222822,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "this.Request.Url.Host\n"
},
{
"answer_id": 222835,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "System.Web.HttpContext.Current.Server.ResolveUrl(\"~/\")\n"
},
{
"answer_id": 222898,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": true,
"text": "string.Format(\"{0}://{1}:{2}\", Request.Url.Scheme, Request.Url.Host, Request.Url.Port)\n"
},
{
"answer_id": 223028,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 2,
"selected": false,
"text": "String baseURL = string.Format(\n (Request.Url.Port != 80) ? \"{0}://{1}:{2}\" : \"{0}://{1}\", \n Request.Url.Scheme, \n Request.Url.Host, \n Request.Url.Port)\n"
},
{
"answer_id": 223754,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 0,
"selected": false,
"text": "'Returns current page URL \nFunction fullurl() As String\n Dim strProtocol, strHost, strPort, strurl, strQueryString As String\n strProtocol = Request.ServerVariables(\"HTTPS\")\n strPort = Request.ServerVariables(\"SERVER_PORT\")\n strHost = Request.ServerVariables(\"SERVER_NAME\")\n strurl = Request.ServerVariables(\"url\")\n strQueryString = Request.ServerVariables(\"QUERY_STRING\")\n\n If strProtocol = \"off\" Then\n strProtocol = \"http://\"\n Else\n strProtocol = \"https://\"\n End If\n\n If strPort <> \"80\" Then\n strPort = \":\" & strPort\n Else\n strPort = \"\"\n End If\n\n If strQueryString.Length > 0 Then\n strQueryString = \"?\" & strQueryString\n End If\n\n Return strProtocol & strHost & strPort & strurl & strQueryString\nEnd Function\n"
},
{
"answer_id": 1134107,
"author": "empz",
"author_id": 105937,
"author_profile": "https://Stackoverflow.com/users/105937",
"pm_score": 0,
"selected": false,
"text": "string.Format(\"{0}://{1}:{2}{3}\", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, ResolveUrl(\"~\")\n"
},
{
"answer_id": 2338457,
"author": "Oliver Crow",
"author_id": 281683,
"author_profile": "https://Stackoverflow.com/users/281683",
"pm_score": 0,
"selected": false,
"text": "string url = String.Format(\n Request.Url.IsDefaultPort ? \"{0}://{1}{3}\" : \"{0}://{1}:{2}{3}\",\n Request.Url.Scheme, Request.Url.Host,\n Request.Url.Port, ResolveUrl(\"~/\"));\n"
},
{
"answer_id": 8637149,
"author": "Cyril Durand",
"author_id": 814735,
"author_profile": "https://Stackoverflow.com/users/814735",
"pm_score": 2,
"selected": false,
"text": "new Uri(this.Request.Url, \"/\") new Uri(this.Request.Url, this.Request.ResolveUrl(\"~/\"))"
},
{
"answer_id": 16710375,
"author": "Jakob Dyrby",
"author_id": 2412950,
"author_profile": "https://Stackoverflow.com/users/2412950",
"pm_score": 1,
"selected": false,
"text": "string FullApplicationPath {\n get {\n StringBuilder sb = new StringBuilder();\n sb.AppendFormat(\"{0}://{1}\", Request.Url.Scheme, Request.Url.Host);\n\n if (!Request.Url.IsDefaultPort)\n sb.AppendFormat(\":{0}\", Request.Url.Port);\n\n if (!string.Equals(\"/\", Request.ApplicationPath))\n sb.Append(Request.ApplicationPath);\n\n return sb.ToString();\n }\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25809/"
] |
222,790
|
<p>I have a simple interface:</p>
<pre><code>public interface IVisitorsLogController
{
List<VisitorsLog> GetVisitorsLog();
int GetUniqueSubscribersCount();
int GetVisitorsCount();
string GetVisitorsSummary();
}
</code></pre>
<p>the class VisitorsLogController implements this interface.</p>
<p>From a console application or a TestFixture - no problem - the console/test fixture compile perfectly.</p>
<p>However, from an Asp.Net web site (not application) in the same solution with this code in the code behind</p>
<pre><code>private IVisitorsLogController ctl;
protected int GetUniqueMembersCount()
{
ctl = new VisitorsLogController();
return ctl.GetUniqueSubscribersCount();
}
</code></pre>
<p>the compiler throws this exception:</p>
<blockquote>
<p>Error 1 'WebSiteBusinessRules.Interfaces.IVisitorsLogController'
does not contain a definition for
'GetUniqueSubscribersCount' and no
extension method
'GetUniqueSubscribersCount' accepting
a first argument of type
'WebSiteBusinessRules.Interfaces.IVisitorsLogController'
could be found (are you missing a
using directive or an assembly
reference?)</p>
</blockquote>
<p>yet for this code in the same file:</p>
<pre><code> protected static int GetVisitorsCount()
{
return VisitorsLogController.Instance.GetVisitorsCount(DateTime.Today);
}
</code></pre>
<p>the compiler compiles these lines without complaining. In fact if I add anything new to the Interface the compiler now complains when trying to compile the asp.net page.</p>
<p>It can't be a missing using directive or assembly reference otherwise both methods would fail.</p>
<p>This is driving me nuts!</p>
<p>Any thoughts please?</p>
<p>Thanks,</p>
<p>Jeremy</p>
|
[
{
"answer_id": 222887,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "ctl = VisitorsLogController.Instance;\n ctl."
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30046/"
] |
222,792
|
<p>How can <strong><code>REVOKE</code></strong> operations on a table be audited in Oracle? Grants can be audited with...</p>
<pre><code>AUDIT GRANT ON *schema.table*;
</code></pre>
<p>Both grants and revokes on system privileges and rolls can be audited with...</p>
<pre><code>AUDIT SYSTEM GRANT;
</code></pre>
<p>Neither of these statements will audit object level revokes. My database is 10g. I am interested in auditing revokes done by SYS, but that is not my primary concern so the answer need not work for the SYS user.</p>
<p>*A trigger could catch these, but I would prefer to use the built in auditing, so if a trigger is the only way to do this, then vote up the "This can't be done" answer.</p>
|
[
{
"answer_id": 250665,
"author": "Leigh Riffel",
"author_id": 27010,
"author_profile": "https://Stackoverflow.com/users/27010",
"pm_score": 2,
"selected": true,
"text": "audit_sys_operations true audit_trail db_extended"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27010/"
] |
222,825
|
<p>How do you retain the indentation of numbered lists? I have a page where the numbers are pushed off the page. How can I prevent this?</p>
<pre><code><ol style="padding: 0">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
</code></pre>
|
[
{
"answer_id": 222923,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 3,
"selected": true,
"text": "ol { margin-left: 30px; }\n"
},
{
"answer_id": 223112,
"author": "Mike Cornell",
"author_id": 419788,
"author_profile": "https://Stackoverflow.com/users/419788",
"pm_score": 1,
"selected": false,
"text": "li { list-style-position: outside; }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30043/"
] |
222,826
|
<p>I have a canvas inside a scrollview. I attached a keydown event handler to the scrollview. For most keys, the handler gets called. </p>
<p>However, for the arrow keys, the handler does not get called. Instead, the scrollview gets scrolled in the appropriate direction.</p>
<p>I also attached a keyup handler to the scrollview and the keyup does get called for the arrow keys.</p>
<p>Is there any way to get the arrow key down event here?</p>
|
[
{
"answer_id": 223323,
"author": "Mike Blandford",
"author_id": 28643,
"author_profile": "https://Stackoverflow.com/users/28643",
"pm_score": 2,
"selected": true,
"text": "scrollView.IsTabStop = false;\n\ninvisibleTextBox.Foreground = new SolidColorBrush(Colors.Transparent);\ninvisibleTextBox.Background = new SolidColorBrush(Colors.Transparent);\nCanvas.SetZIndex(invisibleTextBox, -1000);\ninvisibleTextBox.KeyDown += new KeyEventHandler(HandleKeyDown);\ninvisibleTextBox.KeyUp += new KeyEventHandler(HandleKeyUp);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28643/"
] |
222,827
|
<p>First, I know about this: <a href="https://stackoverflow.com/questions/51217/how-would-you-organize-a-subversion-repository-for-in-house-software-projects">How would you organize a Subversion repository for in house software projects?</a>
Next, the actual question:
My team is restructuring our repository and I'm looking for hints on how to organize it. (SVN in this case).
Here's what we came up with. We have one repository, multiple projects and multiple svn:externals cross-references</p>
<pre><code>\commonTools /*tools used in all projects. Referenced in each project with svn:externals*/
\NUnit.v2.4.8
\NCover.v.1.5.8
\<other similar tools>
\commonFiles /*settings strong name keys etc.*/
\ReSharper.settings
\VisualStudio.settings
\trash /*each member of the team has trash for samples, experiments etc*/
\user1
\user2
\projects
\Solution1 /*Single actual project (Visual Studio Solution)*/
\trunk
\src
\Project1 /*Each sub-project resulting in single .dll or .exe*/
\Project2
\lib
\tools
\tests
\Solution1.sln
\tags
\branches
\Solution2
\trunk
\src
\Project3 /*Each sub-project resulting in single .dll or .exe*/
\Project1 /*Project1 from Solution1 references with svn:externals*/
\lib
\tools
\tests
\Solution2.sln
\tags
\branches
</code></pre>
<p>To clear the vocabulary: Solution means single product, Project is a Visual Studio Project (that results in a single .dll or single .exe)</p>
<p>That's how we plan to lay out the repository. The main issue is, that we have multiple Solutions, but we want to share Projects among Solutions.
We thought that there is no point really in moving those shared Projects to their own Solutions, and instead we decided to use svn:externals to share Projects among Solutions. We also want to keep common set of tools and 3rd party libraries in one place in the repository, and them reference them in each Solution with svn:externals.</p>
<p>What do you think about this layout? Especially about the use of svn:externals. It's not an ideal solution, but considering all pros and cons, it's the best we could think of. How would YOU do it?</p>
|
[
{
"answer_id": 222952,
"author": "SqlRyan",
"author_id": 8114,
"author_profile": "https://Stackoverflow.com/users/8114",
"pm_score": 2,
"selected": false,
"text": "\\Project1\n \\Development (for active dev - what you've called \"Trunk\", containing everything about a project)\n \\Branches (For older, still-evolving supported branches of the code)\n \\Version1\n \\Version1.1\n \\Version2\n \\Documentation (For any accompanying documents that aren't version-specific\n"
},
{
"answer_id": 304036,
"author": "Rob Williams",
"author_id": 26682,
"author_profile": "https://Stackoverflow.com/users/26682",
"pm_score": 8,
"selected": true,
"text": "%DirLibraryRoot%\\ComponentA-1.2.3.4.dll %DirLibraryRoot%\\ComponentB-5.6.7.8.dll %DirOutputRoot%\\ProjectA-9.10.11.12.dll %DirOutputRoot%\\ProjectB-13.14.15.16.exe %DirToolRoot%\\ToolA\\1.2.3.4 %DirToolRoot%\\ToolB\\5.6.7.8 ${project.base.dir}/src ${project.base.dir}/tst ${project.base.dir}/some/dirs ${env.Variable}/other/dir .\\some\\dirs\\here ..\\some\\more\\dirs C:\\some\\dirs\\here \\\\server\\share\\more\\stuff\\there Rob.sln"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13163/"
] |
222,833
|
<p>I currently use the following command, but it's a little unwieldy to type. What's a shorter alternative?</p>
<pre><code>find . -name '*.txt' -exec grep 'sometext' '{}' \; -print
</code></pre>
<p>Here are my requirements:</p>
<ul>
<li>limit to a file extension (I use SVN and don't want to be searching through all those .svn directories)</li>
<li>can default to the current directory, but it's nice to be able to specify a different directory</li>
<li>must be recursive</li>
</ul>
<p><strong>UPDATE:</strong> Here's my best solution so far:</p>
<pre><code>grep -r 'sometext' * --include='*.txt'
</code></pre>
<p><strong>UPDATE #2:</strong> After using grep for a bit, I realized that I like the output of my first method better. So, I followed the suggestions of several responders and simply made a shell script and now I call that with two parameters (extension and text to find).</p>
|
[
{
"answer_id": 222854,
"author": "Chris Dodd",
"author_id": 29759,
"author_profile": "https://Stackoverflow.com/users/29759",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\nset -f # disable pathname expansion\n\npattern=\"-iname *.[chsyl] -o -iname *.[ch]pp -o -iname *.hh -o -iname *.cc\n-o -iname *.java -o -iname *.inl\"\nprune=\"\"\nmoreargs=true\nwhile $moreargs && [ $# -gt 0 ]; do\n case $1 in\n -h)\n pattern=\"-iname *.h -o -iname *.hpp -o -iname *.hh\"\n shift\n ;;\n -prune)\n prune=\"-name $2 -prune -false -o $prune\"\n shift\n shift\n ;;\n *)\n moreargs=false;\n ;;\n esac\ndone\n\nfind . $prune $pattern | sed 's/ /\\\\ /g' | xargs grep \"$@\"\n"
},
{
"answer_id": 222860,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 1,
"selected": false,
"text": "$ myFind.sh txt targetString\n find . -name \"*.$1\" -exec grep $2 {} \\; -print\n"
},
{
"answer_id": 222908,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 0,
"selected": false,
"text": "grep $(find . -name \"*,txt\")"
},
{
"answer_id": 222959,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 2,
"selected": false,
"text": "grep 'sometext' **/*.txt\n grep -r 'sometext' *\n find . -name '*.txt' \\! -wholename '*/.svn/*' -exec grep 'sometext' '{}' \\; -print\n function grep_no_svn {\n find . -name \"${2:-*}\" \\! -wholename '*/.svn/*' -exec grep \"$1\" '{}' \\; -print\n}\n $ grep_here_no_svn \"sometext\"\n $ grep_here_no_svn \"sometext\" \"*.txt\"\n"
},
{
"answer_id": 223031,
"author": "Liudvikas Bukys",
"author_id": 5845,
"author_profile": "https://Stackoverflow.com/users/5845",
"pm_score": 2,
"selected": false,
"text": "grep find . -name '*.txt' -print0 | xargs -0 grep 'sometext' /dev/null\n find -print0 xargs -0 /dev/null"
},
{
"answer_id": 223359,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "ack ack -aG'\\.txt$' 'sometext'\n"
},
{
"answer_id": 224382,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": 2,
"selected": false,
"text": "ack grep -R ack"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29738/"
] |
222,834
|
<p>I want to generate some formatted output of data retrieved from an MS-Access database and stored in a <em>DataTable</em> object/variable, myDataTable. However, some of the fields in myDataTable cotain <em>dbNull</em> data. So, the following VB.net code snippet will give errors if the value of any of the fields <em>lastname</em>, <em>intials</em>, or <em>sID</em> is <em>dbNull</em>.</p>
<pre><code> dim myDataTable as DataTable
dim tmpStr as String
dim sID as Integer = 1
...
myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table
...
For Each myItem As DataRow In myDataTable.Rows
tmpStr = nameItem("lastname") + " " + nameItem("initials")
If myItem("sID")=sID Then
' Do something
End If
' print tmpStr
Next
</code></pre>
<p>So, how do i get the above code to work when the fields may contain <em>dbNull</em> without having to check each time if the data is dbNull as in <a href="https://stackoverflow.com/questions/105671/any-systemdbnullvalue-vs-any-is-systemdbnull">this question</a>?</p>
|
[
{
"answer_id": 222849,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 8,
"selected": true,
"text": "If NOT IsDbNull(myItem(\"sID\")) AndAlso myItem(\"sID\") = sId Then\n 'Do success\nELSE\n 'Failure\nEnd If\n"
},
{
"answer_id": 222850,
"author": "Azim J",
"author_id": 4612,
"author_profile": "https://Stackoverflow.com/users/4612",
"pm_score": 1,
"selected": false,
"text": "tmpStr = nameItem(\"lastname\") + \" \" + nameItem(\"initials\")\n tmpStr = myItem(\"lastname\").toString + \" \" + myItem(\"intials\").toString\n myItem(\"sID\").Equals(sID)\n"
},
{
"answer_id": 222856,
"author": "brendan",
"author_id": 225,
"author_profile": "https://Stackoverflow.com/users/225",
"pm_score": 2,
"selected": false,
"text": " If IsDbNull(myItem(\"sID\")) = False AndAlso myItem(\"sID\")==sID Then\n // Do something\nEnd If\n"
},
{
"answer_id": 1723822,
"author": "Steve Wortham",
"author_id": 102896,
"author_profile": "https://Stackoverflow.com/users/102896",
"pm_score": 5,
"selected": false,
"text": "Public Shared Function NotNull(Of T)(ByVal Value As T, ByVal DefaultValue As T) As T\n If Value Is Nothing OrElse IsDBNull(Value) Then\n Return DefaultValue\n Else\n Return Value\n End If\nEnd Function\n If NotNull(myItem(\"sID\"), \"\") = sID Then\n ' Do something\nEnd If\n"
},
{
"answer_id": 9953399,
"author": "Greg May",
"author_id": 1304623,
"author_profile": "https://Stackoverflow.com/users/1304623",
"pm_score": 3,
"selected": false,
"text": "nullable Private Shared Function GetNullable(Of T)(dataobj As Object) As T\n If Convert.IsDBNull(dataobj) Then\n Return Nothing\n Else\n Return CType(dataobj, T)\n End If\nEnd Function\n mynullable = GetNullable(Of Integer?)(myobj)\n mynullable mynullable.HasValue"
},
{
"answer_id": 12281381,
"author": "John B",
"author_id": 1649034,
"author_profile": "https://Stackoverflow.com/users/1649034",
"pm_score": 2,
"selected": false,
"text": "While reader.Read()\n colDropdownListNames.Add(New DDLItem( _\n CType(reader(\"rid\"), Integer), _\n CType(reader(\"Item_Status\"), String), _\n CType(reader(\"Text_Show\"), String), _\n CType( IIf(IsDBNull(reader(\"Text_Use\")), \"\", reader(\"Text_Use\")) , String), _\n CType(reader(\"Text_SystemOnly\"), String), _\n CType(reader(\"Parent_rid\"), Integer)))\nEnd While\n"
},
{
"answer_id": 20246737,
"author": "BINU NARAYANAN NELLIYAMPATHI",
"author_id": 3042456,
"author_profile": "https://Stackoverflow.com/users/3042456",
"pm_score": 1,
"selected": false,
"text": " VB.Net\n ========\n Dim da As New SqlDataAdapter\n Dim dt As New DataTable\n Call conecDB() 'Connection to Database\n da.SelectCommand = New SqlCommand(\"select max(RefNo) from BaseData\", connDB)\n\n da.Fill(dt)\n\n If dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) = \"\" Then\n MsgBox(\"datbase is null\")\n\n ElseIf dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) <> \"\" Then\n MsgBox(\"datbase have value\")\n\n End If\n"
},
{
"answer_id": 21633737,
"author": "user3284874",
"author_id": 3284874,
"author_profile": "https://Stackoverflow.com/users/3284874",
"pm_score": 0,
"selected": false,
"text": "DBNull TRIM Me.txtProvNum.Text = IIf(Convert.IsDBNull(TRIM(myReader(\"Prov_Num\"))), \"\", TRIM(myReader(\"Prov_Num\")))\n Me.txtProvNum.Text = IIf(Convert.IsDBNull(myReader(\"Prov_Num\")), \"\", myReader(\"Prov_Num\"))\n"
},
{
"answer_id": 69917487,
"author": "B H",
"author_id": 1539001,
"author_profile": "https://Stackoverflow.com/users/1539001",
"pm_score": 0,
"selected": false,
"text": "DbNull.Value.Equals(myValue)\n"
},
{
"answer_id": 74531408,
"author": "schlebe",
"author_id": 948359,
"author_profile": "https://Stackoverflow.com/users/948359",
"pm_score": 0,
"selected": false,
"text": "VB.Net Dim nId As Integer = dr(\"id\") + \"0\"\n DBNull id dr(\"id\") Dim myDataTable as DataTable\n Dim s as String\n Dim sID as Integer = 1\n\n ...\n myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table\n ...\n\n For Each myItem As DataRow In myDataTable.Rows\n s = nameItem(\"lastname\") + \" \" + nameItem(\"initials\")\n If myItem(\"sID\") + \"0\" = sID Then\n ' Do something\n End If\n Next\n sID dr(\"sID\") Extension Dim iNo1 As Integer = dr(\"numero\") + \"0\"\nDim iNo2 As Integer = dr(\"numero\") & \"0\" '-> iNo = 10 when dr() = 1\nDim iNo3 As Integer = dr(\"numero\") + \"4\" '-> iNo = 5 when dr() = 1\nDim iNo4 As Integer = dr(\"numero\") & \"4\" '-> iNo = 14 when dr() = 1\nDim iNo5 As Integer = dr(\"numero\") + \"\" -> System.InvalidCastException : 'La conversion de la chaîne \"\" en type 'Integer' n'est pas valide.'\nDim iNo6 As Integer = dr(\"numero\") & \"\" -> System.InvalidCastException : 'La conversion de la chaîne \"\" en type 'Integer' n'est pas valide.'\nDim iNo7 As Integer = \"\" + dr(\"numero\") -> System.InvalidCastException : 'La conversion de la chaîne \"\" en type 'Integer' n'est pas valide.'\nDim iNo8 As Integer = \"\" & dr(\"numero\") -> System.InvalidCastException : 'La conversion de la chaîne \"\" en type 'Integer' n'est pas valide.'\nDim iNo9 As Integer = \"0\" + dr(\"numero\")\nDim iNo0 As Integer = \"0\" & dr(\"numero\")\n Dim iNo9 As Integer = \"0\" + dr(\"numero\")\nDim iNo0 As Integer = \"0\" & dr(\"numero\")\n Extension Dim iNo = dr.GetInteger(\"numero\",0)\n Module Extension\n '***********************************************************************\n '* GetString()\n '***********************************************************************\n\n <Extension()>\n Public Function GetString(ByRef rd As SqlDataReader, ByRef sName As String, Optional ByVal sDefault As String = \"\") As String\n Return GetString(rd, rd.GetOrdinal(sName), sDefault)\n End Function\n\n <Extension()>\n Public Function GetString(ByRef rd As SqlDataReader, ByVal iCol As Integer, Optional ByVal sDefault As String = \"\") As String\n If rd.IsDBNull(iCol) Then\n Return sDefault\n Else\n Return rd.Item(iCol).ToString()\n End If\n End Function\n\n '***********************************************************************\n '* GetInteger()\n '***********************************************************************\n\n <Extension()>\n Public Function GetInteger(ByRef rd As SqlDataReader, ByRef sName As String, Optional ByVal iDefault As Integer = -1) As Integer\n Return GetInteger(rd, rd.GetOrdinal(sName), iDefault)\n End Function\n\n <Extension()>\n Public Function GetInteger(ByRef rd As SqlDataReader, ByVal iCol As Integer, Optional ByVal iDefault As Integer = -1) As Integer\n If rd.IsDBNull(iCol) Then\n Return iDefault\n Else\n Return rd.Item(iCol)\n End If\n End Function\n\nEnd Module\n GetBoolean() GetDate() COALESCE"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4612/"
] |
222,839
|
<p>I have a WPF window for editing database information, which is represented using an Entity Framework object. When the user closes the window, I'd like to notice in the Closing event whether the information has changed and show a message box offering to save the changes to the database.</p>
<p>Unfortunately, changes to the currently focused edit aren't assigned to the binding source until the edit loses focus, which happens at some point after the Closing event has been processed.</p>
<p>Ideally, there would be a routine which commits all changes in the view hierarchy that I could call before checking to see if my entity has been modified. I've also looked for information on programmatically clearing the focus in the control with focus, but can't figure out how to do it.</p>
<p>My question is, how is this typically handled?</p>
|
[
{
"answer_id": 224287,
"author": "Donnelle",
"author_id": 28074,
"author_profile": "https://Stackoverflow.com/users/28074",
"pm_score": 4,
"selected": true,
"text": "\n\nprivate void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n{\n ForceDataValidation();\n}\n\n\nprivate static void ForceDataValidation()\n{\n TextBox textBox = Keyboard.FocusedElement as TextBox;\n\n if (textBox != null)\n {\n BindingExpression be = textBox.GetBindingExpression(TextBox.TextProperty);\n if (be != null && !textBox.IsReadOnly && textBox.IsEnabled)\n {\n be.UpdateSource();\n }\n }\n\n}\n\n\n"
},
{
"answer_id": 229871,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 0,
"selected": false,
"text": "IInputElement x = System.Windows.Input.Keyboard.FocusedElement;\nDummyField.Focus();\nx.Focus();\n TextBox t = Keyboard.FocusedElement as TextBox;\nif ((t != null) && (t.GetBindingExpression(TextBox.TextProperty) != null))\n t.GetBindingExpression(TextBox.TextProperty).UpdateSource();\nComboBox c = Keyboard.FocusedElement as ComboBox;\nif ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null))\n c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();\n"
},
{
"answer_id": 4724716,
"author": "Dave the Rave",
"author_id": 580011,
"author_profile": "https://Stackoverflow.com/users/580011",
"pm_score": 1,
"selected": false,
"text": "Control currentControl = System.Windows.Input.Keyboard.FocusedElement as Control;\n\nif (currentControl != null)\n{\n // Force focus away from the current control to update its binding source.\n currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));\n currentControl.Focus();\n}\n"
},
{
"answer_id": 4724828,
"author": "sourcenouveau",
"author_id": 111327,
"author_profile": "https://Stackoverflow.com/users/111327",
"pm_score": 5,
"selected": false,
"text": "Binding UpdateSourceTrigger PropertyChanged Value=\"{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}\"\n"
},
{
"answer_id": 26358931,
"author": "user3738532",
"author_id": 3738532,
"author_profile": "https://Stackoverflow.com/users/3738532",
"pm_score": 3,
"selected": false,
"text": "private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n{\n FocusManager.SetFocusedElement(this, null);\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30002/"
] |
222,841
|
<p>Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?</p>
|
[
{
"answer_id": 222847,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 11,
"selected": true,
"text": "var arr = Array.prototype.slice.call( htmlCollection )\n var arr = [].slice.call(htmlCollection);\n var arr = Array.from(htmlCollection);\n Array.from Array.from var arr = [...htmlCollection];\n NodeList"
},
{
"answer_id": 1872365,
"author": "Gareth Davis",
"author_id": 31480,
"author_profile": "https://Stackoverflow.com/users/31480",
"pm_score": 3,
"selected": false,
"text": "$A function $A(iterable) {\n if (!iterable) return [];\n if ('toArray' in Object(iterable)) return iterable.toArray();\n var length = iterable.length || 0, results = new Array(length);\n while (length--) results[length] = iterable[length];\n return results;\n}\n Array.prototype.slice iterable"
},
{
"answer_id": 16595969,
"author": "Gustavo",
"author_id": 1572493,
"author_profile": "https://Stackoverflow.com/users/1572493",
"pm_score": 2,
"selected": false,
"text": "var Divs = new Array(); \nvar Elemns = document.getElementsByClassName(\"divisao\");\n try {\n Divs = Elemns.prototype.slice.call(Elemns);\n } catch(e) {\n Divs = $A(Elemns);\n }\n function $A(iterable) {\n if (!iterable) return [];\n if ('toArray' in Object(iterable)) return iterable.toArray();\n var length = iterable.length || 0, results = new Array(length);\n while (length--) results[length] = iterable[length];\n return results;\n}\n"
},
{
"answer_id": 22676083,
"author": "Codesmith",
"author_id": 586652,
"author_profile": "https://Stackoverflow.com/users/586652",
"pm_score": 5,
"selected": false,
"text": "Array.prototype HTMLCollection Array function toArray(x) {\n for(var i = 0, a = []; i < x.length; i++)\n a.push(x[i]);\n\n return a\n}\n"
},
{
"answer_id": 37042313,
"author": "mido",
"author_id": 3074768,
"author_profile": "https://Stackoverflow.com/users/3074768",
"pm_score": 7,
"selected": false,
"text": "let arry = [...htmlCollection] \n let arry = Array.from(htmlCollection)\n"
},
{
"answer_id": 38929954,
"author": "Nicholas",
"author_id": 195050,
"author_profile": "https://Stackoverflow.com/users/195050",
"pm_score": 3,
"selected": false,
"text": "var arr = [];\n[].push.apply(arr, htmlCollection);\n"
},
{
"answer_id": 51272101,
"author": "Shahar Shokrani",
"author_id": 6844481,
"author_profile": "https://Stackoverflow.com/users/6844481",
"pm_score": 3,
"selected": false,
"text": "makeArray var domArray = jQuery.makeArray(htmlCollection);\n var domDataLength = domData.length //Better performance, no need to calculate every iteration the domArray length\nvar resultArray = new Array(domDataLength) // Since we know the length its improves the performance to declare the result array from the beginning.\n\nfor (var i = 0 ; i < domDataLength ; i++) {\n resultArray[i] = domArray[i]; //Since we already declared the resultArray we can not make use of the more expensive push method.\n}\n \"array-like\""
},
{
"answer_id": 65992448,
"author": "Roman Karagodin",
"author_id": 14282340,
"author_profile": "https://Stackoverflow.com/users/14282340",
"pm_score": 2,
"selected": false,
"text": "Array.prototype HTMLCollection [...collection] Array.from(collection) Array.prototype [0] length HTMLCollection FileList [] Array.prototype Array.prototype const _ = Array.prototype;\nconst collection = document.getElementById('ol').children;\nalert(_.reduce.call(collection, (acc, { textContent }, i) => {\n return acc += `${i+1}) ${textContent}` + '\\n';\n}, '')); <ol id=\"ol\">\n <li>foo</li>\n <li>bar</li>\n <li>bat</li>\n <li>baz</li>\n</ol>"
},
{
"answer_id": 70576919,
"author": "Avi",
"author_id": 15185401,
"author_profile": "https://Stackoverflow.com/users/15185401",
"pm_score": 2,
"selected": false,
"text": "var allbuttons = document.getElementsByTagName(\"button\");\nconsole.log(allbuttons);\n\nvar copyAllButtons = [];\nfor (let i = 0; i < allbuttons.length; i++) {\n copyAllButtons.push(allbuttons[i]);\n}\nconsole.log(copyAllButtons);\n HTMLCollection []\n[]\n <script src=\"./script.js\"></script>\n HTMLCollection(6) [button.btn.btn-dark.click-me, button.btn.btn-dark.reset, button#b, button#b, button#b, button#b, b: button#b]\n(6) [button.btn.btn-dark.click-me, button.btn.btn-dark.reset, button#b, button#b, button#b, button#b]\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20/"
] |
222,871
|
<p>I have generated linq to sql entites but cannot figure out how to assign null to a nullable column. whenever i try to assign null to it it says "there is no implicit type conversion between int and ". BTW the type of the field is int? and the database column is also nullable.</p>
|
[
{
"answer_id": 222905,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 0,
"selected": false,
"text": "int? Nullable<int> Value int?"
},
{
"answer_id": 223514,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 0,
"selected": false,
"text": "null private int? _someID;\n/// <summary>\n/// Gets or sets the SomeID.\n/// </summary>\n[Column(Name=\"SomeID\", Storage=\"_someID\", DbType=\"INT\", UpdateCheck=UpdateCheck.Never)]\npublic int? SomeID\n{\n\nprivate int _someOtherID;\n/// <summary>\n/// Gets or sets the SomeOtherID.\n/// </summary>\n[Column(Name=\"SomeOtherID\", Storage=\"_someOtherID\", DbType=\"INT NOT NULL\", CanBeNull=false, UpdateCheck=UpdateCheck.Never)]\npublic int SomeOtherID\n{\n"
},
{
"answer_id": 37219005,
"author": "DFTR",
"author_id": 881421,
"author_profile": "https://Stackoverflow.com/users/881421",
"pm_score": 0,
"selected": false,
"text": "someEntity newEntity = new someEntity()\n{\n aNullableInt = new Nullable<Int32>()\n};\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16439/"
] |
222,877
|
<p>What's the difference between:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
</code></pre>
<p>and:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
</code></pre>
<p>I've seen <code>super</code> being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.</p>
|
[
{
"answer_id": 222922,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 9,
"selected": true,
"text": "super() super() Child"
},
{
"answer_id": 224020,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 5,
"selected": false,
"text": "class A:\n def __init__(self):\n print(\"A.__init__()\")\n\nclass B(A):\n def __init__(self):\n print(\"B.__init__()\")\n super(B, self).__init__()\n class A class A(object)"
},
{
"answer_id": 33469090,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 9,
"selected": false,
"text": "SomeBaseClass.__init__(self) \n SomeBaseClass __init__ super().__init__()\n __init__ SomeBaseClass super() super() __init__ __init__ super __init__ super super(Child, self).__init__()\n super().__init__()\n self cls Child __class__ super super super super super class SomeBaseClass(object):\n def __init__(self):\n print('SomeBaseClass.__init__(self) called')\n \nclass UnsuperChild(SomeBaseClass):\n def __init__(self):\n print('UnsuperChild.__init__(self) called')\n SomeBaseClass.__init__(self)\n \nclass SuperChild(SomeBaseClass):\n def __init__(self):\n print('SuperChild.__init__(self) called')\n super().__init__()\n class InjectMe(SomeBaseClass):\n def __init__(self):\n print('InjectMe.__init__(self) called')\n super().__init__()\n\nclass UnsuperInjector(UnsuperChild, InjectMe): pass\n\nclass SuperInjector(SuperChild, InjectMe): pass\n >>> o = UnsuperInjector()\nUnsuperChild.__init__(self) called\nSomeBaseClass.__init__(self) called\n super >>> o2 = SuperInjector()\nSuperChild.__init__(self) called\nInjectMe.__init__(self) called\nSomeBaseClass.__init__(self) called\n super UnsuperChild InjectMe super UnsuperChild InjectMe UnsuperInjector InjectMe UnsuperChild super super super super"
},
{
"answer_id": 39376081,
"author": "Michael Ekoka",
"author_id": 56974,
"author_profile": "https://Stackoverflow.com/users/56974",
"pm_score": 5,
"selected": false,
"text": "super() A B C a b c super(B, b) \n# resolves to the scope of B's parent i.e. A \n# and applies that scope to b, as if b was an instance of A\n\nsuper(C, c) \n# resolves to the scope of C's parent i.e. B\n# and applies that scope to c\n\nsuper(B, c) \n# resolves to the scope of B's parent i.e. A \n# and applies that scope to c\n super super() __new__() class A(object):\n def __new__(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n return super(A, cls).__new__(cls, *a, **kw)\n __new__() __new__() # if you defined this\nclass A(object):\n def __new__(cls):\n pass\n\n# calling this would raise a TypeError due to the missing argument\nA.__new__()\n\n# whereas this would be fine\nA.__new__(A)\n super() A A.__new__(cls) super(A, cls)\n __new__() super(A, cls).__new__ cls super(A, cls).__new__(cls, *a, **kw)\n super class A(object):\n def __new__(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n return object.__new__(cls, *a, **kw)\n super super() __init__() class A(object): \n def __init__(self, *a, **kw):\n # ...\n # you make some changes here\n # ...\n\n super(A, self).__init__(*a, **kw)\n __init__ # you try calling `__init__()` from the class without specifying an instance\n# and a TypeError is raised due to the expected but missing reference\nA.__init__() # TypeError ...\n\n# you create an instance\na = A()\n\n# you call `__init__()` from that instance and it works\na.__init__()\n\n# you can also call `__init__()` with the class and explicitly pass the instance \nA.__init__(a)\n super() __init__() super(A, self)\n super(A, self) self s __init__() s.__init__(...) self __init__() super __init__() class A(object): \n def __init__(self, *a, **kw):\n # ...\n # you make some changes here\n # ...\n\n object.__init__(self, *a, **kw)\n super class A(object):\n @classmethod\n def alternate_constructor(cls, *a, **kw):\n print \"A.alternate_constructor called\"\n return cls(*a, **kw)\n\nclass B(A):\n @classmethod\n def alternate_constructor(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n print \"B.alternate_constructor called\"\n return super(B, cls).alternate_constructor(*a, **kw)\n # calling directly from the class is fine,\n# a reference to the class is passed implicitly\na = A.alternate_constructor()\nb = B.alternate_constructor()\n super() super(B, cls_or_subcls)\n super(B, cls) A cls alternate_constructor() super(B, cls).alternate_constructor(...) cls A alternate_constructor() super(B, cls).alternate_constructor()\n super() A.alternate_constructor() class B(A):\n @classmethod\n def alternate_constructor(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n print \"B.alternate_constructor called\"\n return A.alternate_constructor(cls, *a, **kw)\n A.alternate_constructor() A cls class B(A):\n @classmethod\n def alternate_constructor(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n print \"B.alternate_constructor called\"\n # first we get a reference to the unbound \n # `A.alternate_constructor` function \n unbound_func = A.alternate_constructor.im_func\n # now we call it and pass our own `cls` as its first argument\n return unbound_func(cls, *a, **kw)\n"
},
{
"answer_id": 41384524,
"author": "skhalymon",
"author_id": 1322168,
"author_profile": "https://Stackoverflow.com/users/1322168",
"pm_score": 6,
"selected": false,
"text": "super() A\n / \\\n B C\n \\ /\n D\n In [26]: D.__mro__\nOut[26]: (__main__.D, __main__.B, __main__.C, __main__.A, object)\n super() In [23]: class A(object): # or with Python 3 can define class A:\n...: def __init__(self):\n...: print(\"I'm from A\")\n...: \n...: class B(A):\n...: def __init__(self):\n...: print(\"I'm from B\")\n...: super().__init__()\n...: \n...: class C(A):\n...: def __init__(self):\n...: print(\"I'm from C\")\n...: super().__init__()\n...: \n...: class D(B, C):\n...: def __init__(self):\n...: print(\"I'm from D\")\n...: super().__init__()\n...: d = D()\n...:\nI'm from D\nI'm from B\nI'm from C\nI'm from A\n\n A\n / ⇖\n B ⇒ C\n ⇖ /\n D\n super() In [21]: class A(object): # or class A:\n...: def __init__(self):\n...: print(\"I'm from A\")\n...: \n...: class B(A):\n...: def __init__(self):\n...: super().__init__() # or super(B, self).__init_()\n...: print(\"I'm from B\")\n...: \n...: class C(A):\n...: def __init__(self):\n...: super().__init__()\n...: print(\"I'm from C\")\n...: \n...: class D(B, C):\n...: def __init__(self):\n...: super().__init__()\n...: print(\"I'm from D\")\n...: d = D()\n...: \nI'm from A\nI'm from C\nI'm from B\nI'm from D\n A\n / ⇘\n B ⇐ C\n ⇘ /\n D \n"
},
{
"answer_id": 51388706,
"author": "dorisxx",
"author_id": 10095572,
"author_profile": "https://Stackoverflow.com/users/10095572",
"pm_score": 0,
"selected": false,
"text": "class Child(SomeBaseClass):\n def __init__(self):\n SomeBaseClass.__init__(self)\n class Child(SomeBaseClass):\n def __init__(self):\n super(Child, self).__init__()\n super(Child,self) Child, self super self __init__ super(SomeBaseClass,self) super object super"
},
{
"answer_id": 56715064,
"author": "Aviad Rozenhek",
"author_id": 52917,
"author_profile": "https://Stackoverflow.com/users/52917",
"pm_score": 2,
"selected": false,
"text": "super() __init__ super() SuperObject **kwargs class SuperObject: \n def __init__(self, **kwargs):\n print('SuperObject')\n mro = type(self).__mro__\n assert mro[-1] is object\n if mro[-2] is not SuperObject:\n raise TypeError(\n 'all top-level classes in this hierarchy must inherit from SuperObject',\n 'the last class in the MRO should be SuperObject',\n f'mro={[cls.__name__ for cls in mro]}'\n )\n\n # super().__init__ is guaranteed to be object.__init__ \n init = super().__init__\n init()\n class A(SuperObject):\n def __init__(self, **kwargs):\n print(\"A\")\n super(A, self).__init__(**kwargs)\n\nclass B(SuperObject):\n def __init__(self, **kwargs):\n print(\"B\")\n super(B, self).__init__(**kwargs)\n\nclass C(A):\n def __init__(self, age, **kwargs):\n print(\"C\",f\"age={age}\")\n super(C, self).__init__(age=age, **kwargs)\n\nclass D(B):\n def __init__(self, name, **kwargs):\n print(\"D\", f\"name={name}\")\n super(D, self).__init__(name=name, **kwargs)\n\nclass E(C,D):\n def __init__(self, name, age, *args, **kwargs):\n print( \"E\", f\"name={name}\", f\"age={age}\")\n super(E, self).__init__(name=name, age=age, *args, **kwargs)\n\nE(name='python', age=28)\n E name=python age=28\nC age=28\nA\nD name=python\nB\nSuperObject\n"
},
{
"answer_id": 56741323,
"author": "run_the_race",
"author_id": 5506400,
"author_profile": "https://Stackoverflow.com/users/5506400",
"pm_score": 4,
"selected": false,
"text": "jack Jack super(Jack, jack).method(...) jack Jack jack self self Jack Jack Jen Jen Adam Sue Sue Cain Sue Cain Class Jen(Cain, Sue):\n"
},
{
"answer_id": 61852947,
"author": "tsh",
"author_id": 2045384,
"author_profile": "https://Stackoverflow.com/users/2045384",
"pm_score": 1,
"selected": false,
"text": "class X():\n def __init__(self):\n print(\"X\")\n\nclass Y(X):\n def __init__(self):\n # X.__init__(self)\n super(Y, self).__init__()\n print(\"Y\")\n\nclass P(X):\n def __init__(self):\n super(P, self).__init__()\n print(\"P\")\n\nclass Q(Y, P):\n def __init__(self):\n super(Q, self).__init__()\n print(\"Q\")\n\nQ()\n Y X.__init__ X\nY\nQ\n super(Y, self).__init__() X\nP\nY\nQ\n P Q X Y super(Child, self) class Y(X) Y(X)"
},
{
"answer_id": 63194428,
"author": "cdude",
"author_id": 9554268,
"author_profile": "https://Stackoverflow.com/users/9554268",
"pm_score": 2,
"selected": false,
"text": "class Base(object):\n def __init__(self):\n print(\"initializing Base\")\n\nclass ChildA(Base):\n def __init__(self):\n print(\"initializing ChildA\")\n Base.__init__(self)\n\nclass ChildB(Base):\n def __init__(self):\n print(\"initializing ChildB\")\n super().__init__()\n\nclass Grandchild(ChildA, ChildB):\n def __init__(self):\n print(\"initializing Grandchild\")\n super().__init__()\n \nGrandchild()\n initializing Grandchild\ninitializing ChildA\ninitializing Base\n Base.__init__(self) super().__init__() initializing Grandchild\ninitializing ChildA\ninitializing ChildB\ninitializing Base\n"
},
{
"answer_id": 65383999,
"author": "Raymond Hettinger",
"author_id": 424499,
"author_profile": "https://Stackoverflow.com/users/424499",
"pm_score": 4,
"selected": false,
"text": "class A:\n def m(self):\n print('A')\n\nclass B(A):\n def m(self):\n print('B start')\n super().m()\n print('B end')\n \nclass C(A):\n def m(self):\n print('C start')\n super().m()\n print('C end')\n\nclass D(B, C):\n def m(self):\n print('D start')\n super().m()\n print('D end')\n >>> a = A()\n>>> b = B()\n>>> c = C()\n>>> d = D()\n >>> a.m()\nA\n B -> A -> object >>> type(b).__mro__ \n(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)\n\n>>> b.m()\nB start\nA\nB end\n C -> A -> object >>> type(c).__mro__ \n(<class '__main__.C'>, <class '__main__.A'>, <class 'object'>)\n\n>>> c.m()\nC start\nA\nC end\n D -> B -> C -> A -> object >>> type(d).__mro__\n(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)\n\n>>> d.m()\nD start\nB start\nC start\nA\nC end\nB end\nD end\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25785/"
] |
222,895
|
<p>I like LINQ to SQL, but it seems like the classes it generates are tightly coupled to the database they are stored in, which seems like a Bad Thing. </p>
<p>For example, using ye olde Northwind database, if I create the dbml with the Products table, a <code>Product</code> class is generated. I can use this class in any other tier, which is all well and good, but if I decide I'd rather use plain old ADO.NET (or switch databases), I'll have to recreate the <code>Product</code> class, along with every other "model."</p>
<p>Is there a way around this? Or to create your object models separately, and then have the tables mapped to them? I've played around with the various mapping classes provided, but haven't found a satisfactory answer yet.</p>
|
[
{
"answer_id": 222919,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 1,
"selected": false,
"text": "Product Product"
},
{
"answer_id": 229905,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 4,
"selected": true,
"text": "[Table(Name=\"Products\")]\npublic partial class Product: IProduct { }\n"
},
{
"answer_id": 364138,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 2,
"selected": false,
"text": "select public IQueryable<LinqExample.Core.Person> GetAll() {\n var people = from pe in this.db.Persons\n select new Person {\n Id = pe.id,\n FirstName = pe.fname,\n LastName = pe.lname,\n Reports = this.GetReports(pe.id)\n };\n return people;\n}\n Person"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
222,897
|
<p>Is it possible to extend LINQ-to-SQL entity-classes with constructor-methods and in the same go; make that entity-class inherit from it's data-context class?--In essence converting the entity-class into a business object.</p>
<p>This is the pattern I am currently using:</p>
<pre><code>namespace Xxx
{
public class User : Xxx.DataContext
{
public enum SiteAccessRights
{
NotRegistered = 0,
Registered = 1,
Administrator = 3
}
private Xxx.Entities.User _user;
public Int32 ID
{
get
{
return this._user.UsersID;
}
}
public Xxx.User.SiteAccessRights AccessRights
{
get
{
return (Xxx.User.SiteAccessRights)this._user.UsersAccessRights;
}
set
{
this._user.UsersAccessRights = (Int32)value;
}
}
public String Alias
{
get
{
return this._user.UsersAlias;
}
set
{
this._user.UsersAlias = value;
}
}
public User(Int32 userID)
{
var user = (from u in base.Users
where u.UsersID == userID
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User();
base.Users.InsertOnSubmit(this._user);
}
}
public User(Xxx.User.SiteAccessRights accessRights, String alias)
{
var user = (from u in base.Users
where u.UsersAccessRights == (Int32)accessRights && u.UsersAlias == alias
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User
{
UsersAccessRights = (Int32)accessRights,
UsersAlias = alias
};
base.Users.InsertOnSubmit(this._user);
}
}
public void DeleteOnSubmit()
{
base.Users.DeleteOnSubmit(this._user);
}
}
}
</code></pre>
<p><strong>Update:</strong></p>
<p>Notice that I have two constructor-methods in my <code>User</code> class. I'd like to transfer those to the <code>User</code> entity-class <em>and</em> extend the <code>User</code> entity-class on it's data-context class, so that the data-context is available to the entity-class on "new-up".</p>
<p>Hope this makes sense.</p>
|
[
{
"answer_id": 222935,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": true,
"text": "namespace Xxx.Entities\n{\n public partial class User : IDisposable\n { DataContext ctx;\n\n public static GetUserByID(int userID)\n { var ctx = new DataContext();\n var user = ctx.Users.FirstOrDefault(u=>u.UsersID == userID);\n\n if (user == null)\n {\n user = new User();\n ctx.Users.InsertOnSubmit(user);\n }\n\n user.ctx = ctx;\n return user; \n } \n\n public void Dispose() { if (ctx != null) ctx.Dispose(); }\n }\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
222,916
|
<p>I have a multi-threaded C++ app which does 3D rendering with the OpenSceneGraph library. I'm planning to kick off OSG's render loop as a separate thread using boost::threads, passing a data structure containing shared state in to the thread. I'm trying to avoid anything too heavyweight (like mutexes) for synchronization, as the render loop needs to be pretty tight, and OSG itself tries to avoid having to ever lock. Most of the shared state is set before the thread is started, and never changed. I do have some data that does need to be changed, which I am planning to double-buffer. However, I have a simple boolean for signaling the thread to suspend rendering, and later resume rendering, and another to kill it. In both cases the app thread sets the bool, and the render thread only reads it. Do I need to synchronize access to these bools? As far as I can tell, the worse thing that could happen is the the render loop continues on for an extra frame before suspending or quitting.</p>
|
[
{
"answer_id": 222926,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": true,
"text": "std::atomic<bool> volatile"
},
{
"answer_id": 47869744,
"author": "Tadeusz Kopec for Ukraine",
"author_id": 113662,
"author_profile": "https://Stackoverflow.com/users/113662",
"pm_score": 2,
"selected": false,
"text": "std::atomic<bool> volatile"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
] |
222,925
|
<p>In PHP, I want to read a file into a variable and process the PHP in the file at the same time without using output buffering. Is this possible?</p>
<p>Essentially I want to be able to accomplish this without using <code>ob_start()</code>:</p>
<pre><code><?php
ob_start();
include 'myfile.php';
$xhtml = ob_get_clean();
?>
</code></pre>
<p>Is this possible in PHP?</p>
<p>Update: I want to do some more complex things within an output callback (where output buffering is not allowed).</p>
|
[
{
"answer_id": 223081,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$data = file_get_contents('http://google.com/');\n"
},
{
"answer_id": 223845,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 0,
"selected": false,
"text": "$fileData = file_get_contents('fileOnDisk.php');\n$results = eval($fileData);\n"
},
{
"answer_id": 223865,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 2,
"selected": false,
"text": "<?php\n$file = file_get_contents('/path/to/file.php');\n$xhtml = eval(\"?>$file\");\n?>\n ?> eval()"
},
{
"answer_id": 229193,
"author": "Wes Mason",
"author_id": 2228202,
"author_profile": "https://Stackoverflow.com/users/2228202",
"pm_score": 6,
"selected": true,
"text": "// myinclude.php\n$value = 'foo';\n$otherValue = 'bar';\nreturn $value . $otherValue;\n\n\n// index.php\n$output = include './myinclude.php';\necho $output;\n// Will echo foobar\n"
},
{
"answer_id": 26656953,
"author": "David Newcomb",
"author_id": 52070,
"author_profile": "https://Stackoverflow.com/users/52070",
"pm_score": -1,
"selected": false,
"text": "preg_replace_callback function evalCallback($matches)\n{\n // [0] = <?php return returnOrEcho(\"hi1\");?>\n // [1] = <?php\n // [2] = return returnOrEcho(\"hi1\");\n // [3] = ?>\n return eval($matches[2]);\n}\n\nfunction evalPhp($file)\n{\n // Load contents\n $contents = file_get_contents($file);\n // Add returns\n $content_with_returns = str_replace(\n \"returnOrEcho\"\n ,\"return returnOrEcho\"\n ,$contents);\n // eval\n $modified_content = preg_replace_callback(\n array(\"|(\\<\\?php)(.*)(\\?\\>)|\"\n ,\"evalCallback\"\n ,$content_with_returns);\n return $modified_content;\n}\n returnOrEcho return eval echo function returnOrEcho($str)\n{\n return $str;\n}\n function returnOrEcho($str)\n{\n echo $str;\n}\n <?php returnOrEcho(\"hi1\");?>\n<?php returnOrEcho(\"hi3\".\"oo\");?>\n<?php returnOrEcho(6*7);?>\n preg_replace_callback"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18986/"
] |
222,956
|
<p>When using a UITableViewController, the initWithStyle: method automatically creates the underlying UITableView with - according to the documentation - "the correct dimensions".</p>
<p>My problem is that these "correct dimensions" seem 320x460 (the iPhone's screen size), but I'm pushing this TableView/Controller pair into a UINavigationController which is itself contained in a UIView, which itself is about half the height of the screen.</p>
<p>No frame or bounds wrangling I can come up with seems to correctly reset the table's size, and as such it's "too long", meaning there are a collection of rows that are pushed off the bottom of the screen and are not visible nor reachable by scrolling.</p>
<p>So my question comes down to: what is the proper way to tell a UITableViewController to resize its component UITableView to a specified rectangle?</p>
<p>Thanks!</p>
<p><strong>Update</strong> I've tried all the techniques suggested here to no avail, but I did find one interesting thing: if I eschew the UINavigationController altogether (which I'm not yet willing to do for production, but as an experiment), and add the table view as a <em>direct</em> subview of the enclosing view I mentioned, the frame size given <em>is respected</em>. The <strong>very moment</strong> I re-introduce the UINavigationController into the mix, no matter if it is added as a subview before or after the table view, and no matter if alloc/init it before or after the table view is added as a subview, the result is the same as it was before.</p>
<p>I'm beginning to suspect UINavigationController isn't much of a team player...</p>
<p><strong>Update 2</strong> The suggestion to check frame size after the table view on screen was a good one: turns out that the navigation controller is in fact resizing it some time in between load and display. My solution, hacky at best, has been to cache the frame given on load and to reset it if changed at the beginning of tableView:cellForRowAtIndexPath:. Why there you ask? Because it's the one place I found that worked, that's why!</p>
<p>I don't consider this a solution as it's obviously improper, but for the benefit of anyone else reading, it does seem to work.</p>
|
[
{
"answer_id": 923390,
"author": "Blago",
"author_id": 113999,
"author_profile": "https://Stackoverflow.com/users/113999",
"pm_score": 3,
"selected": false,
"text": "-(void) loadView {\n [self setView:[[[UIView alloc] initWithFrame:CGRectZero] autorelease]];\n [[self view] setAutoresizesSubviews:NO];\n\n /* Create & configure table and other views... */\n\n [self setResultsTable:[[RadarTableViewController alloc] initWithNibName:nil bundle:nil]];\n [[resultsTable view] setFrame:CGRectMake(0,45,320,200)];\n}\n"
},
{
"answer_id": 10578532,
"author": "munibsiddiqui",
"author_id": 1386725,
"author_profile": "https://Stackoverflow.com/users/1386725",
"pm_score": 2,
"selected": false,
"text": " UIEdgeInsets inset = UIEdgeInsetsMake(50, 0, 0, 0);\n self.tableView.contentInset = inset;\n"
},
{
"answer_id": 11026887,
"author": "Vindex",
"author_id": 1455325,
"author_profile": "https://Stackoverflow.com/users/1455325",
"pm_score": -1,
"selected": false,
"text": "UINavigationController"
},
{
"answer_id": 19037423,
"author": "Walter R",
"author_id": 2343792,
"author_profile": "https://Stackoverflow.com/users/2343792",
"pm_score": 0,
"selected": false,
"text": "self.edgesForExtendedLayout = UIRectEdgeNone;\n\n//This one in case your NavigationController is not Translucent\nself.extendedLayoutIncludesOpaqueBars = NO; \n"
},
{
"answer_id": 23100431,
"author": "lixiang",
"author_id": 2889181,
"author_profile": "https://Stackoverflow.com/users/2889181",
"pm_score": 1,
"selected": false,
"text": "{\n UIEdgeInsets insets;\n insets.left = 0;\n insets.right = 0;\n insets.top = 0;\n insets.bottom = 60;\n self.tableView.contentInset = insets;\n [self.tableView setScrollIndicatorInsets:insets];\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23498/"
] |
222,957
|
<p>Before I get into the details of this problem, I'd like to make the situation clear. Our web analytics company works as a consultant for large sites, and (other than adding a single SCRIPT tag) we have no control over the pages themselves.</p>
<p>Our existing script installs handlers using "old" way (a fancy version of element.onclick = blah; that also executes the original handler) which is completely unaware of "new" (addEventListener or attachEvent) handlers on the page. We'd like to fix this to make our script able to run on more sites without requiring as much custom development.</p>
<p>The initial thought here was to have our own script use addEventListener/attachEvent, but this presents a problem: of the client's site sets a handler using the "old" way, it would wipe out the handler we installed the "new" way. Quick and dirty testing shows this happens in both IE7 and FF3, although I didn't test the whole range of browsers. There's also a risk that if we use the "new" way after the page's event handlers are already set, we could erase their handlers.</p>
<p>So my question is: what safe technique can I use to add an event handler in Javascript using addEventListener/attachEvent that works regardless of how other event handlers on the page are installed?</p>
<p>Please remember: we have no way of modifying the site that our script is installed on. (I have to emphasize that because the default answer to questions like this is always, "just rewrite the page to do everything the same way.")</p>
|
[
{
"answer_id": 222990,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 4,
"selected": true,
"text": "elem.onclick = function() { alert(\"foo\"); };\nelem.addEventListener(\"click\", function() { alert(\"bar\"); }, false);\n addEventListener attachEvent onclick click"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30050/"
] |
222,981
|
<p>I cannot correctly position the div <code>form</code> in my layout.</p>
<p>By looking at my div placement and css below, does anyone have an idea what I could be doing wrong?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#floorplans {
float: left;
height: 165px;
width: 203px;
border-right: 1px solid #FFFFFF;
border-bottom: 1px solid #FFFFFF;
position: relative;
background: #FFFFFF url(https://lorempixel.com/320/170/) no-repeat;
padding-top: 14px;
padding-left: 20px;
display: block;
color: #000000;
line-height: 1.5em;
padding-right: 10px;
}
#development {
float: left;
height: 165px;
width: 204px;
border-right: 1px solid #FFFFFF;
border-bottom: 1px solid #FFFFFF;
position: relative;
background: #FFFFFF url(https://lorempixel.com/204/165/) no-repeat;
padding-top: 14px;
padding-left: 20px;
display: block;
color: #000000;
line-height: 1.5em;
padding-right: 10px;
}
#projects {
background: #FFFFFF url(https://lorempixel.com/153/127/) no-repeat;
height: 127px;
width: 153px;
text-align: left;
padding-left: 300px;
color: #333333;
padding-top: 25px;
display: block;
float: left;
position: relative;
line-height: 1.5em;
font-size: 10px;
padding-right: 15px;
clear: left;
}
#form {
background: #990000 url(https://lorempixel.com/450/309/) no-repeat;
float: left;
height: 309px;
width: 450px;
position: relative;
padding-top: 20px;
padding-left: 30px;
padding-right: 30px;
color: #FFFFFF;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<div id="logo"></div>
<div id="topnav"></div>
<div id="nav">
<ul>
<li><a href="#">link</a></li>
<li><a href="#">link2</a></li>
<li><a href="#">link3</a></li>
<li id="last"><a href="#">link4</a></li>
</ul>
</div>
<div id="gallery"></div>
<div id="floorplans"></div>
<div id="development"></div>
<div id="projects"></div>
<div id="form">
<div>
</div>
<div id="footer"></div>
</div></code></pre>
</div>
</div>
</p>
<p>You'll notice the div <code>form</code> is dropping down. What should I do to get things to line up? Should I rework the placement of the divs?</p>
|
[
{
"answer_id": 223015,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": true,
"text": "div div clear:left; #projects #projects #form #projects #form {\n margin-top:-180px;\n}\n#projects {\n border-right: 1px solid #FFFFFF;\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30043/"
] |
222,988
|
<p>My code is in c# asp.net 3.5</p>
<p>In the following code the "Msg" has many words with spaces and characters (eg:Failed to prepare Sync Favorites : Directory does not exist: \STL-FNP-02\ryounes$\Sync\Favorites). This "Msg" is pulled from database to a gridview. I am not able to create hyperlink for this "Msg" in gridview. Since it has spaces it is not creating hyperlink.</p>
<p>I need to create hyperlink for this "Msg" and latter use it in linq query. </p>
<p>I think one shud either use eval or url encoder. I am not sure how to do it. Can anyone say how to go about it?</p>
<pre><code> <asp:HyperLinkField DataTextField="Msg" HeaderText="Msg" DataNavigateUrlFields="Msg"
DataNavigateUrlFormatString="Sync.aspx?Msg={0}" />
</code></pre>
|
[
{
"answer_id": 223062,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 3,
"selected": true,
"text": "<asp:TemplateField HeaderText=\"Msg\"> \n <asp:HyperLink runat=\"server\" Text='<%# HttpUtility.UrlEncode(Eval(\"Msg\")) %>' NavigateUrl='<%#Eval(\"Msg\")%>' />\n</asp:TemplateField>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
222,996
|
<p>I have the following class which uses BinaryReader internally and implements IDisposable.</p>
<pre>
class DisposableClass : IDisposable
{
private BinaryReader reader;
public DisposableClass(Stream stream)
{
reader = new BinaryReader(stream);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)reader).Dispose();
// reader.Dispose();// this won't compile
}
}
public void Dispose()
{
this.Dispose(true);
}
}
</pre>
<p>I have already figured out that I need to cast BinaryReader to IDisposable to be able to call Dispose on it, but I don't understand why I can't just call the Dispose() method directly without casting to IDisposable?</p>
|
[
{
"answer_id": 223020,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 4,
"selected": true,
"text": "Dispose BinaryReader public void Dispose()\n{\n}\n void IDisposable.Dispose()\n{\n}\n IDisposable IDisposable"
},
{
"answer_id": 223169,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "BinaryReader public class BinaryReader : IDisposable\n{\n public virtual void Close()\n {\n this.Dispose(true);\n }\n protected virtual void Dispose(bool disposing)\n {\n if (disposing)\n {\n Stream stream = this.m_stream;\n this.m_stream = null;\n if (stream != null)\n {\n stream.Close();\n }\n }\n this.m_stream = null;\n this.m_buffer = null;\n this.m_decoder = null;\n this.m_charBytes = null;\n this.m_singleChar = null;\n this.m_charBuffer = null;\n }\n void IDisposable.Dispose()\n {\n this.Dispose(true);\n }\n}\n IDisposable.Dispose() Close() Dispose() IDisposable Dispose(bool) public class BinaryReader : IDisposable\n{\n public virtual void Close()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n protected virtual void Dispose(bool disposing)\n {\n if (disposing)\n {\n Stream stream = this.m_stream;\n this.m_stream = null;\n if (stream != null)\n {\n stream.Close();\n }\n }\n this.m_stream = null;\n this.m_buffer = null;\n this.m_decoder = null;\n this.m_charBytes = null;\n this.m_singleChar = null;\n this.m_charBuffer = null;\n }\n public void Dispose()\n {\n this.Close();\n }\n}\n Close() Dispose() Dispose(true) Close() ((IDisposable)reader).Dispose() BinaryReader IDisposable using (BinaryReader reader = new BinaryReader(...))\n{\n}\n"
},
{
"answer_id": 223794,
"author": "trampster",
"author_id": 78561,
"author_profile": "https://Stackoverflow.com/users/78561",
"pm_score": 1,
"selected": false,
"text": "public virtual void Close()\n{\n this.Dispose(true);\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1534/"
] |
222,999
|
<p>I created a single page (with code behind .vb) and created Public intFileID As Integer</p>
<p>in the Page load I check for the querystring and assign it if available or set intFileID = 0.</p>
<pre><code>Public intFileID As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.QueryString("fileid") Is Nothing Then
intFileID = CInt(Request.QueryString("fileid"))
End If
If intFileID > 0 Then
GetFile(intFileID)
End If
End If
End Sub
Private Sub GetFile()
'uses intFileID to retrieve the specific record from database and set's the various textbox.text
End Sub
</code></pre>
<p>There is a click event for the Submit button that inserts or updates a record based on the value of the intFileID variable. I need to be able to persist that value on postback for it all to work.</p>
<p>The page simply inserts or updates a record in a SQL database. I'm not using a gridview,formview,detailsview, or any other rad type object which persists the key value by itself and I don't want to use any of them.</p>
<p>How can I persist the value set in intFileID without creating something in the HTML which could possibly be changed.</p>
<p><strong>[EDIT] Changed Page_Load to use ViewState to persist the intFileID value</strong></p>
<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.QueryString("fileid") Is Nothing Then
intFileID = CInt(Request.QueryString("fileid"))
End If
If intFileID > 0 Then
GetFile(intFileID)
End If
ViewState("intFileID") = intFileID
Else
intFileID = ViewState("intFileID")
End If
End Sub
</code></pre>
|
[
{
"answer_id": 223006,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "Page.Session[\"MyPage_FileID\"] = intFileID\n"
},
{
"answer_id": 223048,
"author": "jerhinesmith",
"author_id": 1108,
"author_profile": "https://Stackoverflow.com/users/1108",
"pm_score": 6,
"selected": true,
"text": "ViewState(key) = value\n value = ViewState(key)\n"
},
{
"answer_id": 223156,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "If Not Page.IsPostBack"
},
{
"answer_id": 227493,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Private intFileId As Integer = 0\n\nPublic Property FileID() As Integer\n Get\n Return intFileId\n End Get\n Set(ByVal value As Integer)\n intFileId = value\n End Set\nEnd Property\n\n\nProtected Overrides Function SaveControlState() As Object\n Dim objState(2) As Object\n objState(0) = MyBase.SaveControlState()\n objState(1) = Me.FileID\n Return objState\nEnd Function\n\n\nProtected Overrides Sub LoadControlState(ByVal savedState As Object)\n Dim objState() As Object\n objState = savedState\n MyBase.LoadControlState(objState(0))\n Me.FileID = CInt(objState(1))\nEnd Sub\n\n\n\n\nProtected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n Me.Page.RegisterRequiresControlState(Me)\nEnd Sub\n\n\nProtected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n\n If Not Page.IsPostBack Then\n If Not String.IsNullOrEmpty(Request.QueryString(\"fileid\")) Then\n Me.FileID = CInt(Request.QueryString(\"fileid\"))\n End If\n End If\n\n Response.Write(Me.FileID.ToString())\nEnd Sub\n"
},
{
"answer_id": 34962176,
"author": "Sahil Saini",
"author_id": 4846477,
"author_profile": "https://Stackoverflow.com/users/4846477",
"pm_score": 1,
"selected": false,
"text": "Session[\"KeyName\"] = your value; Datatable dt = (DataTable)(Session[\"KeyName\"]); ViewState[\"KEY\"]= value; String str = (String)ViewState[\"KEY\"];"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
223,013
|
<p>I often need to run reduce (also called foldl / foldr, depending on your contexts) in java to aggregate elements of an Itterable. </p>
<p>Reduce takes a collection/iterable/etc, a function of two parameters, and an optional start value (depending on the implementation details). The function is successively applied to an element of the collection and the output of the previous invocation of reduce until all elements have been processed, and returns the final value.</p>
<p>Is there a type-safe implementation of reduce in any common java api? <a href="http://google-collections.googlecode.com" rel="noreferrer">Google Collections</a> <em>seems</em> like it should have one, but I haven't been able to find it. (possibly because I don't know what other names it would use.)</p>
|
[
{
"answer_id": 223152,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 3,
"selected": true,
"text": "public interface Reducer<A, T>\n{\n public A foldIn(A accum, T next);\n}\n public class Reductor<A, T>\n{\n private Reducer<A, T> worker;\n public Reductor<A, T>(Reducer<A, T> worker)\n {\n this.worker = worker;\n }\n\n public A fold(A rval, Iterator<T> itr)\n {\n while(itr.hasNext())\n {\n A rval = worker.foldIn(rval, itr.next());\n }\n return rval;\n }\n}\n Reductor r = new Reductor<A, T>(new Reducer<A, T>()\n{\n public A foldIn(A prev, T next)\n {\n A rval;\n //do stuff...\n return rval;\n }\n }\n\n A fold = r.fold(new A(), collection.getIterator());\n"
},
{
"answer_id": 3088389,
"author": "Greg Haines",
"author_id": 372559,
"author_profile": "https://Stackoverflow.com/users/372559",
"pm_score": 2,
"selected": false,
"text": "public interface Reducer<A,T>\n{\n A foldIn(A accum, T next);\n}\n\npublic static <T> T reduce(final Reducer<T,T> reducer, \n final Iterable<? extends T> i)\n{\n T result = null;\n final Iterator<? extends T> iter = i.iterator();\n if (iter.hasNext())\n {\n result = iter.next();\n while (iter.hasNext())\n {\n result = reducer.foldIn(result, iter.next());\n }\n }\n return result;\n}\n\npublic static <A,T> A reduce(final Reducer<A,T> reducer, \n final Iterable<? extends T> i, \n final A initializer)\n{\n A result = initializer;\n final Iterator<? extends T> iter = i.iterator();\n while (iter.hasNext())\n {\n result = reducer.foldIn(result, iter.next());\n }\n return result;\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
] |
223,021
|
<p>I'm using the 'using' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary 'std::'s).</p>
<pre><code>using std::string;
using std::vector;
class Foo { /*...*/ };
</code></pre>
<p>What is the scope on this declaration? If I do this in a header, will it inject these 'using' declarations into every cpp file that includes the header?</p>
|
[
{
"answer_id": 223036,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 2,
"selected": false,
"text": "using using"
},
{
"answer_id": 223047,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 7,
"selected": true,
"text": "using using"
},
{
"answer_id": 223050,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 7,
"selected": false,
"text": "using using void myFunction()\n{\n using namespace std; // only applies to the function's scope\n vector<int> myVector;\n}\n"
},
{
"answer_id": 224909,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "using std::string using ImplementationDetail::Foo namespace MyNS {\n namespace ImplementationDetail {\n int Foo;\n }\n using ImplementationDetail::Foo;\n}\n"
},
{
"answer_id": 68379432,
"author": "Stardusstt",
"author_id": 12790909,
"author_profile": "https://Stackoverflow.com/users/12790909",
"pm_score": 0,
"selected": false,
"text": "//header.h\n#include <string>\n\nstd::string t1; // ok\nstring t2; // ok\n //header.cpp\nusing namespace std ;\n\n#include \"header.h\"\n\n...\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13300/"
] |
223,032
|
<p><a href="http://en.wikipedia.org/wiki/Tf-idf" rel="noreferrer">TF-IDF (term frequency - inverse document frequency)</a> is a staple of information retrieval. It's not a proper model though, and it seems to break down when new terms are introduced into the corpus. How do people handle it when queries or new documents have new terms, especially if they are high frequency. Under traditional cosine matching, those would have no impact on the total match. </p>
|
[
{
"answer_id": 404145,
"author": "Trochee",
"author_id": 49890,
"author_profile": "https://Stackoverflow.com/users/49890",
"pm_score": 1,
"selected": false,
"text": "_UNKNOWN_"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
] |
223,038
|
<p>I have run into a common, yet difficult problem. I do not use Photoshop for image manipulation. Since all my work is web-based, <a href="http://en.wikipedia.org/wiki/GIMP" rel="noreferrer">GIMP</a> does what I need in 99% of the situations. The <em>problem</em> is that I occasionally receive <a href="http://en.wikipedia.org/wiki/Adobe_Photoshop#Features" rel="noreferrer">PSD</a> files with <a href="http://en.wikipedia.org/wiki/CMYK_color_model" rel="noreferrer">CMYK</a> encoding rather than <a href="http://en.wikipedia.org/wiki/RGB_color_model" rel="noreferrer">RGB</a> encoding. These files will not open in GIMP, nor will they convert in <a href="http://en.wikipedia.org/wiki/ImageMagick" rel="noreferrer">ImageMagick</a>. </p>
<p>Has anyone found a good solution for converting CMYK files to RGB files (either PSD format or a flat format like PNG) that does <strong>not</strong> involve the use of Photoshop? Say a plug-in for GIMP or a standalone utility?</p>
|
[
{
"answer_id": 4120484,
"author": "Jj.",
"author_id": 43490,
"author_profile": "https://Stackoverflow.com/users/43490",
"pm_score": 4,
"selected": false,
"text": "convert input.psd -colorspace rgb output.png\n Error loading PSD file: Unsupported color mode: CMYK\n Version: ImageMagick 6.5.7-8 2009-11-26 Q16 http://www.imagemagick.org\nCopyright: Copyright (C) 1999-2009 ImageMagick Studio LLC\nFeatures: OpenMP\n"
},
{
"answer_id": 31159388,
"author": "pefu",
"author_id": 1133959,
"author_profile": "https://Stackoverflow.com/users/1133959",
"pm_score": 4,
"selected": false,
"text": "Image-->Properties Image-->Convert Image Color Space"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16339/"
] |
223,040
|
<p>If two users edit the same wiki topic, what methods have been used in wikis (or in similar collaborative editing software) to merge the second user's edits with the first?</p>
<p>I'd like a solution that:</p>
<ul>
<li>doesn't require locking</li>
<li>doesn't lose any additions to the page.</li>
<li>It may add extra "boilerplate" text to indicate where differing changes were made.</li>
</ul>
<p>(I'm interested in a solution that could be used to implement <a href="https://web.archive.org/web/20081009065531/http://stackoverflow.uservoice.com:80/pages/general/suggestions/28245" rel="nofollow noreferrer">this uservoice idea</a> for stack overflow.)</p>
|
[
{
"answer_id": 223577,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 3,
"selected": true,
"text": " # When a topic is edited, the user takes a \"lease\" on that topic.\n # If another user tries to also edit the topic while the lease\n # is still active, they will get a warning. The warning text will\n # be different depending on whether the lease has \"expired\" or\n # not i.e. if it was taken out more than LeaseLength seconds ago.\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] |
223,058
|
<p><strong><em>Imagine</em></strong> a base class with many constructors and a virtual method</p>
<pre><code>public class Foo
{
...
public Foo() {...}
public Foo(int i) {...}
...
public virtual void SomethingElse() {...}
...
}
</code></pre>
<p>and now i want to create a descendant class that overrides the virtual method:</p>
<pre><code>public class Bar : Foo
{
public override void SomethingElse() {...}
}
</code></pre>
<p>And another descendant that does some more stuff:</p>
<pre><code>public class Bah : Bar
{
public void DoMoreStuff() {...}
}
</code></pre>
<p>Do i really have to copy all constructors from Foo into Bar and Bah? And then if i change a constructor signature in Foo, do i have to update it in Bar and Bah?</p>
<p>Is there no way to inherit constructors? Is there no way to encourage code reuse?</p>
|
[
{
"answer_id": 223068,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 8,
"selected": true,
"text": "base this null"
},
{
"answer_id": 223072,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": false,
"text": " public Bar(int i): base(i) {}\n public Bar(int i, int j) : base(i, j) {}\n"
},
{
"answer_id": 223073,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 6,
"selected": false,
"text": "public Foo(params int[] list) {...}\n"
},
{
"answer_id": 223458,
"author": "dviljoen",
"author_id": 29021,
"author_profile": "https://Stackoverflow.com/users/29021",
"pm_score": 5,
"selected": false,
"text": "public Bar(int i, int j) : this(i) { ... }\n ^^^^^\n"
},
{
"answer_id": 223500,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "Foo Initialise() public class Foo\n{\n ...\n public Foo() {...}\n\n public virtual void Initialise(int i) {...}\n public virtual void Initialise(int i, int i) {...}\n public virtual void Initialise(int i, int i, int i) {...}\n ... \n public virtual void Initialise(int i, int i, ..., int i) {...}\n\n ...\n\n public virtual void SomethingElse() {...}\n ...\n}\n"
},
{
"answer_id": 739591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "Subclass(): base() {}\nSubclass(int x): base(x) {}\nSubclass(int x,y): base(x,y) {}\n"
},
{
"answer_id": 3831476,
"author": "Pavlo Neiman",
"author_id": 164001,
"author_profile": "https://Stackoverflow.com/users/164001",
"pm_score": 3,
"selected": false,
"text": "public class BaseClass\n{\n public BaseClass(params int[] parameters)\n {\n\n } \n}\n\npublic class ChildClass : BaseClass\n{\n public ChildClass(params int[] parameters)\n : base(parameters)\n {\n\n }\n}\n"
},
{
"answer_id": 8143922,
"author": "Exocubic",
"author_id": 1048558,
"author_profile": "https://Stackoverflow.com/users/1048558",
"pm_score": 3,
"selected": false,
"text": "public class FooParams\n{\n public int Size...\n protected myCustomStruct _ReasonForLife ...\n}\npublic class Foo\n{\n private FooParams _myParams;\n public Foo(FooParams myParams)\n {\n _myParams = myParams;\n }\n}\n public class Bar : Foo\n{\n public Bar(FooParams myParams) : base(myParams) {}\n}\n"
},
{
"answer_id": 24743423,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 3,
"selected": false,
"text": "Foo Bar Bah Foo Bar Bah create // In Foo:\npublic T create<T>(int i) where: where T : Foo, new() {\n T obj = new T();\n // Do whatever you would do with `i` in `Foo(i)` here, for instance,\n // if you save it as a data member; `obj.dataMember = i;`\n return obj;\n}\n create Foo Bar b new Bar(42) var b = Foo.create<Bar>(42);\n// or\nBar b = Foo.create<Bar>(42);\n// or\nvar b = Bar.create<Bar>(42); // But you still need the <Bar> bit\n// or\nBar b = Bar.create<Bar>(42);\n create Foo create makeThingy using System.IO;\nusing System;\n\nclass Program\n{\n static void Main()\n {\n Bar b1 = Foo.create<Bar>(42);\n b1.ShowDataMember(\"b1\");\n\n Bar b2 = Bar.create<Bar>(43); // Just to show `Foo.create` vs. `Bar.create` doesn't matter\n b2.ShowDataMember(\"b2\");\n }\n\n class Foo\n {\n public int DataMember { get; private set; }\n\n public static T create<T>(int i) where T: Foo, new()\n {\n T obj = new T();\n obj.DataMember = i;\n return obj;\n }\n }\n\n class Bar : Foo\n {\n public void ShowDataMember(string prefix)\n {\n Console.WriteLine(prefix + \".DataMember = \" + this.DataMember);\n }\n }\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
223,063
|
<p>I would like to create an application that serves web pages internally and can be run in multiple instances on the same machine. To do so, I would like to create an <code>HttpListener</code> that listens on a port that is:</p>
<ol>
<li>Randomly selected </li>
<li>Currently unused</li>
</ol>
<p>Essentially, what I would like is something like:</p>
<pre><code>mListener = new HttpListener();
mListener.Prefixes.Add("http://*:0/");
mListener.Start();
selectedPort = mListener.Port;
</code></pre>
<p>How can I accomplish this?</p>
|
[
{
"answer_id": 223188,
"author": "Snooganz",
"author_id": 28224,
"author_profile": "https://Stackoverflow.com/users/28224",
"pm_score": 4,
"selected": false,
"text": " static List<int> usedPorts = new List<int>();\n static Random r = new Random();\n\n public HttpListener CreateNewListener()\n {\n HttpListener mListener;\n int newPort = -1;\n while (true)\n {\n mListener = new HttpListener();\n newPort = r.Next(49152, 65535); // IANA suggests the range 49152 to 65535 for dynamic or private ports.\n if (usedPorts.Contains(newPort))\n {\n continue;\n }\n mListener.Prefixes.Add(string.Format(\"http://*:{0}/\", newPort));\n try\n {\n mListener.Start();\n }\n catch\n {\n continue;\n }\n usedPorts.Add(newPort);\n break;\n }\n\n return mListener;\n }\n"
},
{
"answer_id": 3978040,
"author": "Richard Dingwall",
"author_id": 91551,
"author_profile": "https://Stackoverflow.com/users/91551",
"pm_score": 5,
"selected": false,
"text": "public static int GetRandomUnusedPort()\n{\n var listener = new TcpListener(IPAddress.Any, 0);\n listener.Start();\n var port = ((IPEndPoint)listener.LocalEndpoint).Port;\n listener.Stop();\n return port;\n}\n"
},
{
"answer_id": 39772904,
"author": "dodbrian",
"author_id": 2537328,
"author_profile": "https://Stackoverflow.com/users/2537328",
"pm_score": 1,
"selected": false,
"text": "GetActiveTcpListeners IPGlobalProperties Port private static bool TryGetUnusedPort(int startingPort, ref int port)\n{\n var listeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();\n\n for (var i = startingPort; i <= 65535; i++)\n {\n if (listeners.Any(x => x.Port == i)) continue;\n port = i;\n return true;\n }\n\n return false;\n}\n startingPort true false"
},
{
"answer_id": 43617808,
"author": "Scott Offen",
"author_id": 1102764,
"author_profile": "https://Stackoverflow.com/users/1102764",
"pm_score": 1,
"selected": false,
"text": "RestCluster RestServer using (var server = new RestServer())\n{\n // Grab the next open port (starts at 1)\n server.Port = PortFinder.FindNextLocalOpenPort();\n\n // Grab the next open port after 2000 (inclusive)\n server.Port = PortFinder.FindNextLocalOpenPort(2000);\n\n // Grab the next open port between 2000 and 5000 (inclusive)\n server.Port = PortFinder.FindNextLocalOpenPort(200, 5000);\n ...\n}\n"
},
{
"answer_id": 46666370,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 3,
"selected": false,
"text": "public static bool TryBindListenerOnFreePort(out HttpListener httpListener, out int port)\n{\n // IANA suggested range for dynamic or private ports\n const int MinPort = 49215;\n const int MaxPort = 65535;\n\n for (port = MinPort; port < MaxPort; port++)\n {\n httpListener = new HttpListener();\n httpListener.Prefixes.Add($\"http://localhost:{port}/\");\n try\n {\n httpListener.Start();\n return true;\n }\n catch\n {\n // nothing to do here -- the listener disposes itself when Start throws\n }\n }\n\n port = 0;\n httpListener = null;\n return false;\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
223,070
|
<p>I'm looking for a database of commonly installed Windows software. At minimum I need the name of the software and the executable name, but it'd also be nice to have the publisher and the common installation path, etc. Basically, I'd like to be able to query it to find all the software by Adobe and the associated executable name, etc. </p>
<p>Basically I'm looking to be able to do </p>
<pre><code>SELECT * FROM Software WHERE Publisher = 'Microsoft'
SELECT * FROM Software WHERE Executable = 'devenv.com'
</code></pre>
<p>I came across an effort to create such a database a long time ago, but can't seem to find it now. Maybe it fizzled out. Any help would be greatly appreciated. Thanks.</p>
|
[
{
"answer_id": 47118501,
"author": "apk",
"author_id": 5104533,
"author_profile": "https://Stackoverflow.com/users/5104533",
"pm_score": 1,
"selected": false,
"text": "SELECT ?monarch ?monarchLabel ?programming_language ?programming_languageLabel ?operating_system ?operating_systemLabel WHERE {\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],en\". }\n { ?monarch wdt:P31 wd:Q7397. } UNION { ?monarch wdt:P31 wd:Q40056. }\n OPTIONAL { ?monarch wdt:P277 ?programming_language. }\n OPTIONAL { ?monarch wdt:P306 ?operating_system. }\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28926/"
] |
223,085
|
<p>I'd like to sprinkle some print statements in my code to show where I am and print important values to a console window.</p>
<p>How do I do that, but then be able to turn it off for the release version?</p>
|
[
{
"answer_id": 223091,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "System.Diagnostics.Debug.Print()"
},
{
"answer_id": 223183,
"author": "PersistenceOfVision",
"author_id": 6721,
"author_profile": "https://Stackoverflow.com/users/6721",
"pm_score": 0,
"selected": false,
"text": "#if DEBUG\n System.Console.WriteLine(\"Message\");\n#endif \n"
},
{
"answer_id": 223210,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "System.Diagnostics Debug.Write/WriteLine Debug.Assert Debug Trace.Write/WriteLine TextWriterTraceListener TextWriter TextBox WriteIf WriteLineIf Trace Trace"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9516/"
] |
223,097
|
<p>Say you have a web form with some fields that you want to validate to be only some subset of alphanumeric, a minimum or maximum length etc.</p>
<p>You can validate in the client with javascript, you can post the data back to the server and report back to the user, either via ajax or not. You could have the validation rules in the database and push back error messages to the user that way.</p>
<p>Or any combination of all of the above.</p>
<p>If you want a single place to keep validation rules for web application user data that persist to a database, what are some best practices, patterns or general good advice for doing so?</p>
<p>[edit]</p>
<p>I have edited the question title to better reflect my actual question! Some great answers so far btw.</p>
|
[
{
"answer_id": 223288,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 2,
"selected": false,
"text": "{ \"fieldName1\" : \"error description\", \n\"fieldName2\" : \"another error description\" };\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348/"
] |
223,115
|
<p>Having difficulty articulating this correlated subquery. I have two tables fictitious tables, foo and bar. foo has two fields of foo_id and total_count. bar has two fields, seconds and id.</p>
<p>I need to aggregate the seconds in bar for each individual id and update the total_count in foo. id is a foreign key in bar for foo_id.</p>
<p>I've tried something similar without much luck:</p>
<pre><code>UPDATE foo f1 set total_count = (SELECT SUM(seconds) from bar b1 INNER JOIN foo f2 WHERE b1.foo_id = f2.id) WHERE f1.foo_id = bar.id;
</code></pre>
|
[
{
"answer_id": 223154,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 0,
"selected": false,
"text": "foo id total_count bar foo_id foo.id seconds total_count foo UPDATE foo AS f1\nSET total_count = (\n SELECT SUM(seconds) \n FROM bar INNER JOIN foo \n WHERE foo_id = f1.id\n);\n WHERE WHERE f1.foo_id = bar.id;"
},
{
"answer_id": 223161,
"author": "Adam",
"author_id": 30084,
"author_profile": "https://Stackoverflow.com/users/30084",
"pm_score": 2,
"selected": true,
"text": "UPDATE foo f1\nSET total_count = (SELECT SUM(seconds)\nFROM bar b1 WHERE b1.id = f1.foo_id)\n"
},
{
"answer_id": 223174,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 0,
"selected": false,
"text": "CREATE VIEW foo AS\nSELECT id, sum(seconds) from bar group by id;\n"
},
{
"answer_id": 223544,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "UPDATE foo SET total_count = 0;\n\nUPDATE foo JOIN bar ON (foo.foo_id = bar.id)\n SET foo.total_count = foo.total_count + bar.seconds;\n"
},
{
"answer_id": 273268,
"author": "user35593",
"author_id": 35593,
"author_profile": "https://Stackoverflow.com/users/35593",
"pm_score": 1,
"selected": false,
"text": "create table foo ( foo_id int identity, total_count int default 0 )\ncreate table bar ( foo_id int, seconds int )\n\ninsert into foo default values\ninsert into foo default values\ninsert into foo default values\n\ninsert into bar values ( 1, 10 )\ninsert into bar values ( 1, 11 )\ninsert into bar values ( 1, 12 )\n /* total for foo_id 1 = 33 */\ninsert into bar values ( 2, 10 )\ninsert into bar values ( 2, 11 )\n /* total for foo_id 2 = 21 */\ninsert into bar values ( 3, 10 )\ninsert into bar values ( 3, 19 )\n /* total for foo_id 3 = 29 */\n\nselect *\nfrom foo\n\nfoo_id total_count\n----------- -----------\n1 0\n2 0\n3 0\n\nupdate f\nset total_count = sumsec\nfrom foo f\n inner join (\n select foo_id\n , sum(seconds) sumsec\n from bar\n group by foo_id\n ) a\n on f.foo_id = a.foo_id\n\nselect *\nfrom foo\n\nfoo_id total_count\n----------- -----------\n1 33\n2 21\n3 29\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
223,126
|
<p>I'm new to Rails development, and I'm trying to figure out how to use an older version of Rails with Apatana's RadRails IDE. I'm trying to help out a friend who has a site built on older version than the one that automatically gets downloaded by RadRails, and I'm pretty sure the two versions wouldn't be compatible (the site is using some pre 2.0 version, not sure of the exact number offhand).</p>
<p>Is there a way to tell RadRails to get and use a specific version of Rails? Or is there something I can do at the command line to change the installed version of Rails? I'm only vaguely familiar with the "gem" package system, but I'm assuming it would involve that.</p>
<p>Any help would be much appreciated!</p>
|
[
{
"answer_id": 226219,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 3,
"selected": true,
"text": "rails:freeze:gems rake rails:freeze:gems VERSION=2.1.0\n vendor/rails"
},
{
"answer_id": 261753,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "gem install rails -v 2.0.2 RAILS_GEM_VERSION = '2.0.2'"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.