qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
370,878 | <p>Does anyone know how to get a service ticket from the Key Distribution Center (KDC) using the Java GSS-API?</p>
<p>I have a thick-client-application that first authenticates via JAAS using the Krb5LoginModule to fetch the TGT from the ticket cache (background: Windows e.g. uses a kerberos implementation and stores the ticket granting ticket in a secure memory area). From the LoginManager I get the Subject object which contains the TGT. Now I hoped when I create a specific GSSCredential object for my service, the service ticket will be put into the Subject's private credentials as well (I've read so somewhere in the web). So I have tried the following:</p>
<pre><code>// Exception handling ommitted
LoginContext lc = new LoginContext("HelloEjbClient", new DialogCallbackHandler());
lc.login()
Subject.doAs(lc.getSubject(), new PrivilegedAction() {
public Object run() {
GSSManager manager = GSSManager.getInstance();
GSSName clientName = manager.createName("clientUser", GSSName.NT_USER_NAME);
GSSCredential clientCreds = manager.createCredential(clientName, 8 * 3600, createKerberosOid(), GSSCredential.INITIATE_ONLY);
GSSName serverName = manager.createName("myService@localhost", GSSName.NT_HOSTBASED_SERVICE);
manager.createCredential(serverName, GSSCredential.INDEFINITE_LIFETIME, createKerberosOid(), GSSCredential.INITIATE_ONLY);
return null;
}
private Oid createKerberosOid() {
return new Oid("1.2.840.113554.1.2.2");
}
});
</code></pre>
<p>Unfortunately I get a GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt).</p>
| [
{
"answer_id": 377108,
"author": "Roland Schneider",
"author_id": 16515,
"author_profile": "https://Stackoverflow.com/users/16515",
"pm_score": 5,
"selected": true,
"text": " GSSManager manager = GSSManager.getInstance();\n GSSName clientName = manager.createName(\"clientUser\", GSSName.NT_USER_NAME);\n GSSCredential clientCred = manager.createCredential(clientName,\n 8 * 3600,\n createKerberosOid(),\n GSSCredential.INITIATE_ONLY);\n\n GSSName serverName = manager.createName(\"http@server\", GSSName.NT_HOSTBASED_SERVICE);\n\n GSSContext context = manager.createContext(serverName,\n createKerberosOid(),\n clientCred,\n GSSContext.DEFAULT_LIFETIME);\n context.requestMutualAuth(true);\n context.requestConf(false);\n context.requestInteg(true);\n\n byte[] outToken = context.initSecContext(new byte[0], 0, 0);\n System.out.println(new BASE64Encoder().encode(outToken));\n context.dispose();\n"
},
{
"answer_id": 12948384,
"author": "Olivier Faucheux",
"author_id": 1166992,
"author_profile": "https://Stackoverflow.com/users/1166992",
"pm_score": 3,
"selected": false,
"text": "/**\n * Tool to retrieve a kerberos ticket. This one will not be stored in the windows ticket cache.\n */\npublic final class KerberosTicketRetriever\n{\n private final static Oid KERB_V5_OID;\n private final static Oid KRB5_PRINCIPAL_NAME_OID;\n\n static {\n try\n {\n KERB_V5_OID = new Oid(\"1.2.840.113554.1.2.2\");\n KRB5_PRINCIPAL_NAME_OID = new Oid(\"1.2.840.113554.1.2.2.1\");\n\n } catch (final GSSException ex)\n {\n throw new Error(ex);\n }\n }\n\n /**\n * Not to be instanciated\n */\n private KerberosTicketRetriever() {};\n\n /**\n *\n */\n private static class TicketCreatorAction implements PrivilegedAction\n {\n final String userPrincipal;\n final String applicationPrincipal;\n\n private StringBuffer outputBuffer;\n\n /**\n *\n * @param userPrincipal p.ex. <tt>MuelleHA@MYFIRM.COM</tt>\n * @param applicationPrincipal p.ex. <tt>HTTP/webserver.myfirm.com</tt>\n */\n private TicketCreatorAction(final String userPrincipal, final String applicationPrincipal)\n {\n this.userPrincipal = userPrincipal;\n this.applicationPrincipal = applicationPrincipal;\n }\n\n private void setOutputBuffer(final StringBuffer newOutputBuffer)\n {\n outputBuffer = newOutputBuffer;\n }\n\n /**\n * Only calls {@link #createTicket()}\n * @return <tt>null</tt>\n */\n public Object run()\n {\n try\n {\n createTicket();\n }\n catch (final GSSException ex)\n {\n throw new Error(ex);\n }\n\n return null;\n }\n\n /**\n *\n * @throws GSSException\n */\n private void createTicket () throws GSSException\n {\n final GSSManager manager = GSSManager.getInstance();\n final GSSName clientName = manager.createName(userPrincipal, KRB5_PRINCIPAL_NAME_OID);\n final GSSCredential clientCred = manager.createCredential(clientName,\n 8 * 3600,\n KERB_V5_OID,\n GSSCredential.INITIATE_ONLY);\n\n final GSSName serverName = manager.createName(applicationPrincipal, KRB5_PRINCIPAL_NAME_OID);\n\n final GSSContext context = manager.createContext(serverName,\n KERB_V5_OID,\n clientCred,\n GSSContext.DEFAULT_LIFETIME);\n context.requestMutualAuth(true);\n context.requestConf(false);\n context.requestInteg(true);\n\n final byte[] outToken = context.initSecContext(new byte[0], 0, 0);\n\n if (outputBuffer !=null)\n {\n outputBuffer.append(String.format(\"Src Name: %s\\n\", context.getSrcName()));\n outputBuffer.append(String.format(\"Target : %s\\n\", context.getTargName()));\n outputBuffer.append(new BASE64Encoder().encode(outToken));\n outputBuffer.append(\"\\n\");\n }\n\n context.dispose();\n }\n }\n\n /**\n *\n * @param realm p.ex. <tt>MYFIRM.COM</tt>\n * @param kdc p.ex. <tt>kerbserver.myfirm.com</tt>\n * @param applicationPrincipal cf. {@link #TicketCreatorAction(String, String)}\n * @throws GSSException\n * @throws LoginException\n */\n static public String retrieveTicket(\n final String realm,\n final String kdc,\n final String applicationPrincipal)\n throws GSSException, LoginException\n {\n\n // create the jass-config-file\n final File jaasConfFile;\n try\n {\n jaasConfFile = File.createTempFile(\"jaas.conf\", null);\n final PrintStream bos = new PrintStream(new FileOutputStream(jaasConfFile));\n bos.print(String.format(\n \"Krb5LoginContext { com.sun.security.auth.module.Krb5LoginModule required refreshKrb5Config=true useTicketCache=true debug=true ; };\"\n ));\n bos.close();\n jaasConfFile.deleteOnExit();\n }\n catch (final IOException ex)\n {\n throw new IOError(ex);\n }\n\n // set the properties\n System.setProperty(\"java.security.krb5.realm\", realm);\n System.setProperty(\"java.security.krb5.kdc\", kdc);\n System.setProperty(\"java.security.auth.login.config\",jaasConfFile.getAbsolutePath());\n\n // get the Subject(), i.e. the current user under Windows\n final Subject subject = new Subject();\n final LoginContext lc = new LoginContext(\"Krb5LoginContext\", subject, new DialogCallbackHandler());\n lc.login();\n\n // extract our principal\n final Set<Principal> principalSet = subject.getPrincipals();\n if (principalSet.size() != 1)\n throw new AssertionError(\"No or several principals: \" + principalSet);\n final Principal userPrincipal = principalSet.iterator().next();\n\n // now try to execute the SampleAction as the authenticated Subject\n // action.run() without doAsPrivileged leads to\n // No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)\n final TicketCreatorAction action = new TicketCreatorAction(userPrincipal.getName(), applicationPrincipal);\n final StringBuffer outputBuffer = new StringBuffer();\n action.setOutputBuffer(outputBuffer);\n Subject.doAsPrivileged(lc.getSubject(), action, null);\n\n return outputBuffer.toString();\n }\n\n public static void main (final String args[]) throws Throwable\n {\n final String ticket = retrieveTicket(\"MYFIRM.COM\", \"kerbserver\", \"HTTP/webserver.myfirm.com\");\n System.out.println(ticket);\n }\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16515/"
] |
370,884 | <p>I understand that you can use forms authentication to grant/deny access to certain pages based on the criteria of your choosing.</p>
<p>However I wish to go in a little more specific than that and say, have different buttons appear for users based on thier permissions.</p>
<p>I know I could do something like</p>
<pre><code>if(((User)ViewData["CurrentUser"]).IsEmployee).....
</code></pre>
<p>But that doesn't seem very elegant and could get messy very quickly.</p>
<p>Are there any guidelines/tools/framework features that could help me out here?</p>
| [
{
"answer_id": 371376,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 3,
"selected": false,
"text": "if (ViewContext.HttpContext.User.IsInRole(\"vEmployee\") {\n public static string TextBox(this HtmlHelper helper, \n string name, string value, string role, object htmlAttributes)\n{\n if helper.ViewContext.HttpContext.User.IsInRole(role) {\n return helper.TextBox(name, value, htmlAttributes);\n } \n else\n {\n return null;\n }\n}\n <%= Html.TextBox(\"name\", \"value\", \"vEmployee\", null) %>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3193/"
] |
370,890 | <p>I have to display marks of my students through my site. The database is created using <a href="http://en.wikipedia.org/wiki/Microsoft_Access" rel="noreferrer">Microsoft Access</a>. How can I display the marks of each student in a table, as they enter the registration number?</p>
| [
{
"answer_id": 371583,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "<%\nSet Conn = Server.CreateObject(\"ADODB.Connection\")\nConn.Open \"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:/YourDatabase.mdb\"\nSQL = \"Select * from TABLENAME where regno=\" & request(\"regno\")\nset RS= Conn.execute(SQL)\n%>\n<table>\n <tr>\n <% for x=0 to rs.fields.count-1 %>\n <th><%=RS.fields(x).value%></th>\n <% next %>\n </tr>\n <% do until RS.eof %>\n <tr>\n <% for x=0 to rs.fields.count-1 %>\n <td><%=RS.fields(x).value%></td>\n <% next %>\n </tr>\n <% rs.movenext %>\n <% loop %>\n</table>\n<%\nRS.close()\nset Conn=nothing\n%>\n"
},
{
"answer_id": 61184159,
"author": "GeniusGeek",
"author_id": 10045061,
"author_profile": "https://Stackoverflow.com/users/10045061",
"pm_score": 2,
"selected": false,
"text": " MySql.Execute(\n \"mysql.yourhost.com\", \n \"username\", \n \"password\", \n \"database\", \n \"select * from Users\", \n function (data) {\n console.log(data)\n});\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
370,892 | <p>Please follow the link <a href="http://msdn.microsoft.com/hi-in/default.aspx" rel="noreferrer">http://msdn.microsoft.com/hi-in/default.aspx</a> and see the top right corner of the page. </p>
<p>There you will find a "Microsoft.com" expander. When you move the mouse over it, it displays as a popup and grows. When you move your mouse off of it the window shrinks back. I want to mimic this effect in my WPF application using C#.</p>
| [
{
"answer_id": 370964,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 2,
"selected": false,
"text": "Popup"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46607/"
] |
370,913 | <p>I have been playing with the Linq to Sql and I was wondering if it was possible to get a single result out? For example, I have the following:</p>
<pre><code>using(DataClassContext context = new DataClassContext())
{
var customer = from c in context.table
where c.ID = textboxvalue
select c;
}
</code></pre>
<p>And with this I need to do a foreach around the var customer but i know that this will be a single value! Anyone know how I could do a <code>textbox.text = c.name;</code> or something along that line?</p>
| [
{
"answer_id": 370924,
"author": "Paul Nearney",
"author_id": 24071,
"author_profile": "https://Stackoverflow.com/users/24071",
"pm_score": 2,
"selected": false,
"text": "var customer = context.table.SingleOrDefault(c => c.ID == textboxvalue);\n"
},
{
"answer_id": 370930,
"author": "Sorskoot",
"author_id": 31722,
"author_profile": "https://Stackoverflow.com/users/31722",
"pm_score": 4,
"selected": true,
"text": "using(DataClassContext context = new DataClassContext())\n{\nvar customer = (from c in context.table\nwhere c.ID = textboxvalue\nselect c).SingleOrDefault();\n}\n Single() First() Last()"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36243/"
] |
370,925 | <p>I have a method I want to unittest that has filesystem calls in it and am wondering how to go about it. I have looked at <a href="https://stackoverflow.com/questions/129036/unit-testing-code-with-a-file-system-dependency">Unit testing code with a file system dependency</a> but it does not answer my question.</p>
<p>The method I am testing looks something like this (c#)</p>
<pre><code>public void Process(string input)
{
string outputFile = "output.txt";
this.Transform(input, Resources.XsltFile, outputFile);
if ((new FileInfo(outputFile)).Length == 0)
{
File.Delete(outputFile);
}
}
</code></pre>
<p>I am mocking the Transform(..) method to not output anything to a file as I am unittesting the Process method and not the Transform(..) method and therefore no output.txt file exists. Therefore the if check fails. </p>
<p>How should I do this properly? Should I create some sort of wrapper around the file io methods that i would mock out as well?</p>
| [
{
"answer_id": 370955,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 3,
"selected": false,
"text": "interface FileProvider {\n public Reader getContentReader(String file);\n // notice use of the Reader interface\n // - real-life returns a FileReader;\n // - testing mock returns a StringReader;\n\n\n public FileInfo getFileInfo(String path);\n // easy to mock out...\n}\n\nclass Processor {\n\n private FileProvider fileProvider;\n\n public void setFileProvider(FileProvider provider) { \n this.provider = provider; \n }\n\n public void process(String input) {\n // use this.fileProvider for all filesystem operations...\n }\n}\n FileProvider"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32313/"
] |
370,943 | <p>How can I use multiple keys in WSH Script like (ALT,CTRL,DELETE)?
How can i take a screenshot of an application and paste it in MSWord using WSH SCript?</p>
| [
{
"answer_id": 370963,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "SendKeys()"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46565/"
] |
370,944 | <p>I am using a DropDownList as </p>
<pre><code><asp:DropDownList
ID="ddlLocationName"
runat="server"
DataValueField="Guid"
DataTextField="LocationName"
AppendDataBoundItems="false"
AutoPostBack="false"
onchange="LocationChange()"
></asp:DropDownList>
</code></pre>
<p>and when I select item from dropdown the DataTextField should be displayed in the textfield. For that i am using following javascript: </p>
<pre><code>function LocationChange()
{
document.getElementById ("ctl00_mainContent_ctl02_txtEventLocation").value = document.getElementById ('ctl00_mainContent_ctl02_ddlLocationName')[document.getElementById ('ctl00_mainContent_ctl02_ddlLocationName').selectedIndex].value
}
</code></pre>
<p>It works fine when dropdown's DataValueField is not used. But how to do desired task when DataValueField property of dropdown is also used?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 370980,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "<option /> function LocationChange(){\n var ddl = $get('dropDownListId');\n var selectedOption = ddl.options[ddl.selectedIndex];\n var selectedText = selectedOption.text;\n var selectedValue = selectedOption.value;\n\n alert('Your option has a text property of ' + selectedText + ' and a value property of ' + selectedValue');\n}\n"
},
{
"answer_id": 371041,
"author": "Devashri B.",
"author_id": 43886,
"author_profile": "https://Stackoverflow.com/users/43886",
"pm_score": 0,
"selected": false,
"text": "function LocationChange()\n{ \n document.getElementById (\"ctl00_mainContent_ctl02_txtEventLocation\").value = document.getElementById ('ctl00_mainContent_ctl02_ddlLocationName')[document.getElementById ('ctl00_mainContent_ctl02_ddlLocationName').selectedIndex].innerText\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43886/"
] |
370,954 | <p>I have a KTextEdit, filled with some text. </p>
<p>When I put lots of text, the KTextEdit will be scrolled automatically to the end (obviously). </p>
<p>My question is: how can I scroll to the start (viz to the first line of the KTextEdit) ?!?</p>
| [
{
"answer_id": 370988,
"author": "user11323",
"author_id": 11323,
"author_profile": "https://Stackoverflow.com/users/11323",
"pm_score": 0,
"selected": false,
"text": "KTextEdit *kte;\n...\nkte->append(\"some huge text\");\nkte->verticalScrollBar()->setValue(0);\n"
},
{
"answer_id": 370990,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": true,
"text": "QTextCursor cursor = edit->textCursor();\ncursor.setPosition(0);\nedit->setTextCursor(cursor);\n edit->moveCursor(QTextCursor::Start);\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39339/"
] |
370,962 | <p>The question is in Java why can't I define an abstract static method? for example</p>
<pre><code>abstract class foo {
abstract void bar( ); // <-- this is ok
abstract static void bar2(); //<-- this isn't why?
}
</code></pre>
| [
{
"answer_id": 371011,
"author": "Mnementh",
"author_id": 21005,
"author_profile": "https://Stackoverflow.com/users/21005",
"pm_score": 1,
"selected": false,
"text": "foo var = new ImplementsFoo();\nvar.bar();\n"
},
{
"answer_id": 372544,
"author": "Jared",
"author_id": 44757,
"author_profile": "https://Stackoverflow.com/users/44757",
"pm_score": 8,
"selected": true,
"text": "abstract static static abstract ClassA.methodA();\n methodA();\n ClassA methodA.\n static abstract"
},
{
"answer_id": 9774365,
"author": "mjs",
"author_id": 961018,
"author_profile": "https://Stackoverflow.com/users/961018",
"pm_score": 4,
"selected": false,
"text": "public static abstract class Request { \n\n // Static method\n public static void doSomething() {\n get().doSomethingImpl();\n }\n \n // Abstract method\n abstract void doSomethingImpl();\n\n /////////////////////////////////////////////\n private static Request SINGLETON;\n private static Request get() {\n if ( SINGLETON == null ) {\n // If set(request) is never called prior,\n // it will use a default implementation. \n return SINGLETON = new RequestImplementationDefault();\n }\n return SINGLETON;\n }\n public static Request set(Request instance){\n return SINGLETON = instance;\n }\n /////////////////////////////////////////////\n}\n /////////////////////////////////////////////////////\n\npublic static final class RequestImplementationDefault extends Request {\n @Override void doSomethingImpl() {\n System.out.println(\"I am doing something AAA\");\n }\n}\n\n/////////////////////////////////////////////////////\n\npublic static final class RequestImplementaionTest extends Request {\n @Override void doSomethingImpl() {\n System.out.println(\"I am doing something BBB\");\n }\n}\n\n/////////////////////////////////////////////////////\n Request.set(new RequestImplementationDefault());\n\n// Or\n\nRequest.set(new RequestImplementationTest());\n\n// Later in the application you might use\n\nRequest.doSomething();\n ThreadLocal Request.withRequest(anotherRequestImpl, () -> { ... }) ThreadLocal"
},
{
"answer_id": 20305668,
"author": "Olaf Leimann",
"author_id": 3053102,
"author_profile": "https://Stackoverflow.com/users/3053102",
"pm_score": 0,
"selected": false,
"text": "public interface SortableObject {\n public [abstract] static String [] getSortableTypes();\n public String getSortableValueByType(String type);\n}\n public class MyDataObject implements SortableObject {\n final static String [] SORT_TYPES = {\n \"Name\",\"Date of Birth\"\n }\n static long newDataIndex = 0L ;\n\n String fullName ;\n String sortableDate ;\n long dataIndex = -1L ;\n public MyDataObject(String name, int year, int month, int day) {\n if(name == null || name.length() == 0) throw new IllegalArgumentException(\"Null/empty name not allowed.\");\n if(!validateDate(year,month,day)) throw new IllegalArgumentException(\"Date parameters do not compose a legal date.\");\n this.fullName = name ;\n this.sortableDate = MyUtils.createSortableDate(year,month,day);\n this.dataIndex = MyDataObject.newDataIndex++ ;\n }\n public String toString() {\n return \"\"+this.dataIndex+\". \"this.fullName+\" (\"+this.sortableDate+\")\";\n }\n\n // override SortableObject \n public static String [] getSortableTypes() { return SORT_TYPES ; }\n public String getSortableValueByType(String type) {\n int index = MyUtils.getStringArrayIndex(SORT_TYPES, type);\n switch(index) {\n case 0: return this.name ;\n case 1: return this.sortableDate ;\n }\n return toString(); // in the order they were created when compared\n }\n}\n public class SortableList<T extends SortableObject> \n String [] MenuItems = T.getSortableTypes();\n"
},
{
"answer_id": 30834587,
"author": "hyper-neutrino",
"author_id": 8200485,
"author_profile": "https://Stackoverflow.com/users/8200485",
"pm_score": 2,
"selected": false,
"text": "Parent Child Parent abstract abstract class Parent {\n abstract void run();\n}\n\nclass Child extends Parent {\n void run() {}\n}\n Parent run() Parent abstract class Parent {\n static void run() {}\n}\n Parent.run() abstract static abstract static static abstract static abstract"
},
{
"answer_id": 30972338,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 0,
"selected": false,
"text": "list.sort(ordering);\n Collections.sort(list, ordering);\n public interface TimeClient {\n // ...\n static public ZoneId getZoneId (String zoneString) {\n try {\n return ZoneId.of(zoneString);\n } catch (DateTimeException e) {\n System.err.println(\"Invalid time zone: \" + zoneString +\n \"; using default time zone instead.\");\n return ZoneId.systemDefault();\n }\n }\n\n default public ZonedDateTime getZonedDateTime(String zoneString) {\n return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));\n } \n}\n"
},
{
"answer_id": 32281821,
"author": "Blueriver",
"author_id": 3482428,
"author_profile": "https://Stackoverflow.com/users/3482428",
"pm_score": 1,
"selected": false,
"text": "abstract class Foo {\n abstract static void bar();\n}\n\nclass Foo2 {\n @Override\n static void bar() {}\n}\n Foo.bar(); Foo2.bar(); <E extends MySuperClass> E .doSomething()"
},
{
"answer_id": 34104505,
"author": "Darshan Chaudhary",
"author_id": 5188449,
"author_profile": "https://Stackoverflow.com/users/5188449",
"pm_score": 0,
"selected": false,
"text": "Foo Bar1, Bar2, Bar3"
},
{
"answer_id": 34105327,
"author": "AndreyS Scherbakov",
"author_id": 4819357,
"author_profile": "https://Stackoverflow.com/users/4819357",
"pm_score": 3,
"selected": false,
"text": "this this"
},
{
"answer_id": 34900818,
"author": "mhp",
"author_id": 4268348,
"author_profile": "https://Stackoverflow.com/users/4268348",
"pm_score": 2,
"selected": false,
"text": "class C1 {\n static void doWork() {\n ...\n for (int k: list)\n doMoreWork(k);\n ...\n }\n private static void doMoreWork(int k) {\n // code specific to class C1\n }\n}\nclass C2 {\n static void doWork() {\n ...\n for (int k: list)\n doMoreWork(k);\n ...\n }\n private static void doMoreWork(int k) {\n // code specific to class C2\n }\n}\n doWork() C1 C2 C3 C4 static abstract abstract class C {\n static void doWork() {\n ...\n for (int k: list)\n doMoreWork(k);\n ...\n }\n\n static abstract void doMoreWork(int k);\n}\n\nclass C1 extends C {\n private static void doMoreWork(int k) {\n // code for class C1\n }\n}\n\nclass C2 extends C {\n private static void doMoreWork(int k) {\n // code for class C2\n }\n}\n static abstract static class abstract class C {\n void doWork() {\n ...\n for (int k: list)\n doMoreWork(k);\n ...\n }\n abstract void doMoreWork(int k);\n}\nclass C1 {\n private static final C c = new C(){ \n @Override void doMoreWork(int k) {\n System.out.println(\"code for C1\");\n }\n };\n public static void doWork() {\n c.doWork();\n }\n}\nclass C2 {\n private static final C c = new C() {\n @Override void doMoreWork(int k) {\n System.out.println(\"code for C2\");\n }\n };\n public static void doWork() {\n c.doWork();\n }\n}\n public static void doWork() {\n c.doWork();\n }\n"
},
{
"answer_id": 50840314,
"author": "akash kumar",
"author_id": 9936749,
"author_profile": "https://Stackoverflow.com/users/9936749",
"pm_score": 2,
"selected": false,
"text": "static abstract static abstract"
},
{
"answer_id": 53533628,
"author": "Pratik Sherdiwala",
"author_id": 6006552,
"author_profile": "https://Stackoverflow.com/users/6006552",
"pm_score": 1,
"selected": false,
"text": "interface Demo \n{\n public static void main(String [] args) {\n System.out.println(\"I am from interface\");\n }\n}\n"
},
{
"answer_id": 65475133,
"author": "Gaurav ",
"author_id": 14900116,
"author_profile": "https://Stackoverflow.com/users/14900116",
"pm_score": 1,
"selected": false,
"text": "abstract class foo {\n abstract static void bar2(); \n}\n\n\nclass Bar extends foo {\n //in this if you override foo class static method then it will give error\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42303/"
] |
370,978 | <p>I have an application that uses a cron like job to update a set of data. The update process happens once a minute and doesn't last long. A servlet exposes this data set to the users. My problem is that during the update process, the servlet requests should block and wait for the process to complete. </p>
<p>In bottom line I have these two functions:</p>
<pre><code>private void updateData() {
}
public List getData() {
}
</code></pre>
<p>The first function runs once a minute. The second one can be called any number of times simultaneously. When updateData runs, all calls of getData must wait for it to complete. One getData call shouldn't block subsequent calls of the same function. The updateData function has higher priority than the getData, i.e. when updateData is to run, it has to wait for all calls of getData to complete, but new calls shouldn't be allowed to start.</p>
<p>What synchronization mechanism should I use for a case like this? I am using a Java server, but I would be interested to know what solutions exist for other platforms as well.</p>
| [
{
"answer_id": 370995,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 0,
"selected": false,
"text": "public void updateData() {\n synchronized (updateLock) {\n /* do stuff. */\n }\n}\n\n\npublic List getData() {\n List data;\n synchronized (updateLock) {\n data = getRealData();\n }\n /* process/return data. */\n}\n"
},
{
"answer_id": 371046,
"author": "ordnungswidrig",
"author_id": 9069,
"author_profile": "https://Stackoverflow.com/users/9069",
"pm_score": 3,
"selected": false,
"text": "public void updateData() {\n lock.writeLock().lock();\n try {\n /* do stuff. */\n } finally {\n lock.writeLock().unlock();\n }\n}\n\n\npublic List getData() {\n lock.readLock().lock();\n try {\n /* process/return data. */\n } finally {\n lock.readLock().unlock();\n }\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/370978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24054/"
] |
371,005 | <p>I have a class</p>
<pre><code>public class Broker
{
public Broker(string[] hosts, string endPoint, string port, Type remoteType)
{
}
}
</code></pre>
<p>Which I want to configure using Unity XML Configuration, I can configure it using code in C# as follows already, where "container" is my Unity container</p>
<pre><code> container.Configure<InjectedMembers>()
.ConfigureInjectionFor<Broker>("myBroker",
new InjectionConstructor(hosts, endPoint, port, new InjectionParameter(typeof(IMyBrokeredObject))));
</code></pre>
<p>and it will happly resolve using the normal unity calls</p>
<p>container.Resolve("myBroker");</p>
<p>But currently my xml cannot resolve the final parameter IMyBrokeredObject, I get a resolution exception, as Unity is trying to resolve the type insted of simply injecting the type, as it does in the code above.</p>
<p>Any Ideas?</p>
| [
{
"answer_id": 398214,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 1,
"selected": false,
"text": "<unity>\n<typeAliases>\n <typeAlias alias=\"IMyBrokeredObject\" type=\"MyAssembly.IMyBrokeredObject, MyAssembly\" />\n</typeAliases>\n<containers>\n <container>\n <types>\n <!-- Views -->\n <type type=\"IMyBrokeredObject\" mapTo=\"MyAssembly.MyBrokeredObjectImplementation, MyAssembly\" />\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,018 | <p>I using the Win32 API and C/C++. I have a HFONT and want to use it to create a new HFONT. The new font should use the exact same font metrics except that it should be bold. Something like:</p>
<pre><code>HFONT CreateBoldFont(HFONT hFont) {
LOGFONT lf;
GetLogicalFont(hFont, &lf);
lf.lfWeight = FW_BOLD;
return CreateFontIndirect(&lf);
}
</code></pre>
<p>The "GetLogicalFont" is the missing API (as far as I can tell anyway). Is there some other way to do it? Preferrably something that works on Windows Mobile 5+.</p>
| [
{
"answer_id": 371052,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 6,
"selected": true,
"text": "GetObject ( hFont, sizeof(LOGFONT), &lf );\n"
},
{
"answer_id": 372678,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 4,
"selected": false,
"text": "static HFONT CreateBoldWindowFont(HWND window)\n{\n const HFONT font = (HFONT)::SendMessage(window, WM_GETFONT, 0, 0);\n LOGFONT fontAttributes = { 0 };\n ::GetObject(font, sizeof(fontAttributes), &fontAttributes);\n fontAttributes.lfWeight = FW_BOLD;\n\n return ::CreateFontIndirect(&fontAttributes);\n}\n\nstatic void PlayWithBoldFont()\n{\n const HFONT boldFont = CreateBoldWindowFont(someWindow);\n .\n . // Play with it!\n .\n ::DeleteObject(boldFont);\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20398/"
] |
371,019 | <p>In the javadoc it says that EventListener is </p>
<blockquote>
<p>"A tagging interface that all event listener interfaces must extend."</p>
</blockquote>
<p>Why is that? What's the significance of making a custom listener implement EventListner? Is there any special handling for EventListner somewhere?</p>
| [
{
"answer_id": 371256,
"author": "asalamon74",
"author_id": 21348,
"author_profile": "https://Stackoverflow.com/users/21348",
"pm_score": 4,
"selected": true,
"text": "extends EventListener"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931/"
] |
371,026 | <p>What's the shortest way to get an Iterator over a range of Integers in Java? In other words, implement the following:</p>
<pre><code>/**
* Returns an Iterator over the integers from first to first+count.
*/
Iterator<Integer> iterator(Integer first, Integer count);
</code></pre>
<p>Something like</p>
<pre><code>(first..first+count).iterator()
</code></pre>
| [
{
"answer_id": 371034,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 3,
"selected": true,
"text": "List<Integer> ints = new ArrayList<Integer>();\nfor (int i = 0; i < count; i++) {\n ints.add(first + i);\n}\n"
},
{
"answer_id": 371043,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 4,
"selected": false,
"text": "public class IntRangeIterator implements Iterator<Integer> {\n private int nextValue;\n private final int max;\n public IntRangeIterator(int min, int max) {\n if (min > max) {\n throw new IllegalArgumentException(\"min must be <= max\");\n }\n this.nextValue = min;\n this.max = max;\n }\n\n public boolean hasNext() {\n return nextValue <= max;\n }\n\n public Integer next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return Integer.valueOf(nextValue++);\n }\n\n public void remove() {\n throw new UnsupportedOperationException();\n }\n}\n"
},
{
"answer_id": 371044,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "import java.util.*;\n\npublic class IntegerRange implements Iterator<Integer>\n{\n private final int start;\n private final int count;\n\n private int position = -1;\n\n public IntegerRange(int start, int count)\n {\n this.start = start;\n this.count = count;\n }\n\n public boolean hasNext()\n {\n return position+1 < count;\n }\n\n public Integer next()\n {\n if (position+1 >= count)\n {\n throw new NoSuchElementException();\n }\n position++;\n return start + position;\n }\n\n public void remove()\n {\n throw new UnsupportedOperationException();\n }\n}\n"
},
{
"answer_id": 371091,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "Collection Iterator public final class IntegerRange implements Set<Integer> {\n final LinkedHashSet<Integer> backingList;\n public IntegerRange(final int start, final int count) {\n backingList = new LinkedHashSet(count, 1.0f);\n for (int i=0; i < count; i++) {\n backingList.set(i, start + i);\n } \n } \n /** Insert a bunch of delegation methods here */\n}\n .iterator() Iterator Integer"
},
{
"answer_id": 6828887,
"author": "Saintali",
"author_id": 787643,
"author_profile": "https://Stackoverflow.com/users/787643",
"pm_score": 6,
"selected": false,
"text": "/**\n * @param begin inclusive\n * @param end exclusive\n * @return list of integers from begin to end\n */\npublic static List<Integer> range(final int begin, final int end) {\n return new AbstractList<Integer>() {\n @Override\n public Integer get(int index) {\n return begin + index;\n }\n\n @Override\n public int size() {\n return end - begin;\n }\n };\n}\n IntStream.range(begin, end).iterator() // returns PrimitiveIterator.OfInt\n IntStream.range(begin, end).boxed().iterator() // returns Iterator<Integer>\n"
},
{
"answer_id": 7956576,
"author": "Lee",
"author_id": 948083,
"author_profile": "https://Stackoverflow.com/users/948083",
"pm_score": 3,
"selected": false,
"text": "import com.google.common.collect.ContiguousSet;\nimport com.google.common.collect.DiscreteDomain;\nimport com.google.common.collect.DiscreteDomains;\n\nclass RangeIterator { \n\n public Iterator<Integer> range(int start, int length) {\n assert length > 0;\n Range<Integer> dim_range = Ranges.closedOpen(start, start + length);\n DiscreteDomain<Integer> ints = DiscreteDomains.integers();\n ContiguousSet<Integer> dim = dim_range.asSet(ints);\n return dim.iterator();\n }\n}\n"
},
{
"answer_id": 36742140,
"author": "btpka3",
"author_id": 533317,
"author_profile": "https://Stackoverflow.com/users/533317",
"pm_score": 2,
"selected": false,
"text": "int first = 0;\nint count = 10;\nIterator<Integer> it = IntStream.range(first, first + count).iterator();\nwhile (it.hasNext()) {\n System.out.println(it.next());\n}\n int first = 0;\nint count = 10;\nIntStream.range(first, first + count).forEach(i -> System.out.println(i));\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
] |
371,032 | <p>I am developing a program that continually sends a stream of data in the background and I want to allow the user to set a cap for both upload and download limit.</p>
<p>I have read up on the <a href="http://en.wikipedia.org/wiki/Token_bucket" rel="noreferrer">token bucket</a> and <a href="http://en.wikipedia.org/wiki/Leaky_bucket" rel="noreferrer">leaky bucket</a> alghorhithms, and seemingly the latter seems to fit the description since this is not a matter of maximizing the network bandwidth but rather being as unobtrusive as possible.</p>
<p>I am however a bit unsure on how I would implement this. A natural approach is to extend the abstract Stream class to make it simple to extend existing traffic, but would this not require the involvement of extra threads to send the data while simultaneously receiving (leaky bucket)? Any hints on other implementations that do the same would be appreciated.</p>
<p>Also, although I can modify how much data the program receives, how well does bandwidth throttling work at the C# level? Will the computer still receive the data and simply save it, effectively canceling the throttling effect or will it wait until I ask to receive more?</p>
<p>EDIT: I am interested in throttling both incoming and outgoing data, where I have no control over the opposite end of the stream.</p>
| [
{
"answer_id": 29456717,
"author": "0xDEADBEEF",
"author_id": 909365,
"author_profile": "https://Stackoverflow.com/users/909365",
"pm_score": 2,
"selected": false,
"text": "public ThrottledStream(Stream parentStream, int maxBytesPerSecond=int.MaxValue) \n{\n MaxBytesPerSecond = maxBytesPerSecond;\n parent = parentStream;\n processed = 0;\n resettimer = new System.Timers.Timer();\n resettimer.Interval = 1000;\n resettimer.Elapsed += resettimer_Elapsed;\n resettimer.Start(); \n}\n\nprotected void Throttle(int bytes)\n{\n try\n {\n processed += bytes;\n if (processed >= maxBytesPerSecond)\n wh.WaitOne();\n }\n catch\n {\n }\n}\n\nprivate void resettimer_Elapsed(object sender, ElapsedEventArgs e)\n{\n processed = 0;\n wh.Set();\n}\n public class ThrottledStream : Stream\n{\n #region Properties\n\n private int maxBytesPerSecond;\n /// <summary>\n /// Number of Bytes that are allowed per second\n /// </summary>\n public int MaxBytesPerSecond\n {\n get { return maxBytesPerSecond; }\n set \n {\n if (value < 1)\n throw new ArgumentException(\"MaxBytesPerSecond has to be >0\");\n\n maxBytesPerSecond = value; \n }\n }\n\n #endregion\n\n\n #region Private Members\n\n private int processed;\n System.Timers.Timer resettimer;\n AutoResetEvent wh = new AutoResetEvent(true);\n private Stream parent;\n\n #endregion\n\n /// <summary>\n /// Creates a new Stream with Databandwith cap\n /// </summary>\n /// <param name=\"parentStream\"></param>\n /// <param name=\"maxBytesPerSecond\"></param>\n public ThrottledStream(Stream parentStream, int maxBytesPerSecond=int.MaxValue) \n {\n MaxBytesPerSecond = maxBytesPerSecond;\n parent = parentStream;\n processed = 0;\n resettimer = new System.Timers.Timer();\n resettimer.Interval = 1000;\n resettimer.Elapsed += resettimer_Elapsed;\n resettimer.Start(); \n }\n\n protected void Throttle(int bytes)\n {\n try\n {\n processed += bytes;\n if (processed >= maxBytesPerSecond)\n wh.WaitOne();\n }\n catch\n {\n }\n }\n\n private void resettimer_Elapsed(object sender, ElapsedEventArgs e)\n {\n processed = 0;\n wh.Set();\n }\n\n #region Stream-Overrides\n\n public override void Close()\n {\n resettimer.Stop();\n resettimer.Close();\n base.Close();\n }\n protected override void Dispose(bool disposing)\n {\n resettimer.Dispose();\n base.Dispose(disposing);\n }\n\n public override bool CanRead\n {\n get { return parent.CanRead; }\n }\n\n public override bool CanSeek\n {\n get { return parent.CanSeek; }\n }\n\n public override bool CanWrite\n {\n get { return parent.CanWrite; }\n }\n\n public override void Flush()\n {\n parent.Flush();\n }\n\n public override long Length\n {\n get { return parent.Length; }\n }\n\n public override long Position\n {\n get\n {\n return parent.Position;\n }\n set\n {\n parent.Position = value;\n }\n }\n\n public override int Read(byte[] buffer, int offset, int count)\n {\n Throttle(count);\n return parent.Read(buffer, offset, count);\n }\n\n public override long Seek(long offset, SeekOrigin origin)\n {\n return parent.Seek(offset, origin);\n }\n\n public override void SetLength(long value)\n {\n parent.SetLength(value);\n }\n\n public override void Write(byte[] buffer, int offset, int count)\n {\n Throttle(count);\n parent.Write(buffer, offset, count);\n }\n\n #endregion\n\n\n}\n"
},
{
"answer_id": 42133563,
"author": "Johannes Egger",
"author_id": 1293659,
"author_profile": "https://Stackoverflow.com/users/1293659",
"pm_score": 3,
"selected": false,
"text": "public class ThrottledStream : Stream\n{\n private readonly Stream parent;\n private readonly int maxBytesPerSecond;\n private readonly IScheduler scheduler;\n private readonly IStopwatch stopwatch;\n\n private long processed;\n\n public ThrottledStream(Stream parent, int maxBytesPerSecond, IScheduler scheduler)\n {\n this.maxBytesPerSecond = maxBytesPerSecond;\n this.parent = parent;\n this.scheduler = scheduler;\n stopwatch = scheduler.StartStopwatch();\n processed = 0;\n }\n\n public ThrottledStream(Stream parent, int maxBytesPerSecond)\n : this (parent, maxBytesPerSecond, Scheduler.Immediate)\n {\n }\n\n protected void Throttle(int bytes)\n {\n processed += bytes;\n var targetTime = TimeSpan.FromSeconds((double)processed / maxBytesPerSecond);\n var actualTime = stopwatch.Elapsed;\n var sleep = targetTime - actualTime;\n if (sleep > TimeSpan.Zero)\n {\n using (var waitHandle = new AutoResetEvent(initialState: false))\n {\n scheduler.Sleep(sleep).GetAwaiter().OnCompleted(() => waitHandle.Set());\n waitHandle.WaitOne();\n }\n }\n }\n\n public override bool CanRead\n {\n get { return parent.CanRead; }\n }\n\n public override bool CanSeek\n {\n get { return parent.CanSeek; }\n }\n\n public override bool CanWrite\n {\n get { return parent.CanWrite; }\n }\n\n public override void Flush()\n {\n parent.Flush();\n }\n\n public override long Length\n {\n get { return parent.Length; }\n }\n\n public override long Position\n {\n get\n {\n return parent.Position;\n }\n set\n {\n parent.Position = value;\n }\n }\n\n public override int Read(byte[] buffer, int offset, int count)\n {\n var read = parent.Read(buffer, offset, count);\n Throttle(read);\n return read;\n }\n\n public override long Seek(long offset, SeekOrigin origin)\n {\n return parent.Seek(offset, origin);\n }\n\n public override void SetLength(long value)\n {\n parent.SetLength(value);\n }\n\n public override void Write(byte[] buffer, int offset, int count)\n {\n Throttle(count);\n parent.Write(buffer, offset, count);\n }\n}\n [TestMethod]\npublic void ShouldThrottleReading()\n{\n var content = Enumerable\n .Range(0, 1024 * 1024)\n .Select(_ => (byte)'a')\n .ToArray();\n var scheduler = new TestScheduler();\n var source = new ThrottledStream(new MemoryStream(content), content.Length / 8, scheduler);\n var target = new MemoryStream();\n\n var t = source.CopyToAsync(target);\n\n t.Wait(10).Should().BeFalse();\n scheduler.AdvanceTo(TimeSpan.FromSeconds(4).Ticks);\n t.Wait(10).Should().BeFalse();\n scheduler.AdvanceTo(TimeSpan.FromSeconds(8).Ticks - 1);\n t.Wait(10).Should().BeFalse();\n scheduler.AdvanceTo(TimeSpan.FromSeconds(8).Ticks);\n t.Wait(10).Should().BeTrue();\n}\n\n[TestMethod]\npublic void ShouldThrottleWriting()\n{\n var content = Enumerable\n .Range(0, 1024 * 1024)\n .Select(_ => (byte)'a')\n .ToArray();\n var scheduler = new TestScheduler();\n var source = new MemoryStream(content);\n var target = new ThrottledStream(new MemoryStream(), content.Length / 8, scheduler);\n\n var t = source.CopyToAsync(target);\n\n t.Wait(10).Should().BeFalse();\n scheduler.AdvanceTo(TimeSpan.FromSeconds(4).Ticks);\n t.Wait(10).Should().BeFalse();\n scheduler.AdvanceTo(TimeSpan.FromSeconds(8).Ticks - 1);\n t.Wait(10).Should().BeFalse();\n scheduler.AdvanceTo(TimeSpan.FromSeconds(8).Ticks);\n t.Wait(10).Should().BeTrue();\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9479/"
] |
371,054 | <p>I was working with the Action Delegates in C# in the hope of learning more about them and thinking where they might be useful.</p>
<p>Has anybody used the Action Delegate, and if so why? or could you give some examples where it might be useful?</p>
| [
{
"answer_id": 371074,
"author": "Sorskoot",
"author_id": 31722,
"author_profile": "https://Stackoverflow.com/users/31722",
"pm_score": 2,
"selected": false,
"text": "SpecialRequest(this,\n new BalieEventArgs \n { \n Message = \"A Message\", \n Action = UpdateMethod, \n Data = someDataObject \n });\n public void UpdateMethod(string SpecialCode){ }\n public class MyEventArgs : EventArgs\n {\n public string Message;\n public object Data;\n public Action<String> Action;\n }\n"
},
{
"answer_id": 371077,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 4,
"selected": false,
"text": "private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() { \n {typeof(TextBox), c => ((TextBox)c).Clear()},\n {typeof(CheckBox), c => ((CheckBox)c).Checked = false},\n {typeof(ListBox), c => ((ListBox)c).Items.Clear()},\n {typeof(RadioButton), c => ((RadioButton)c).Checked = false},\n {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},\n {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}\n };\n"
},
{
"answer_id": 371080,
"author": "Programmin Tool",
"author_id": 21691,
"author_profile": "https://Stackoverflow.com/users/21691",
"pm_score": 6,
"selected": false,
"text": "switch(SomeEnum)\n{\n case SomeEnum.One:\n DoThings(someUser);\n break;\n case SomeEnum.Two:\n DoSomethingElse(someUser);\n break;\n}\n Dictionary<SomeEnum, Action<User>> methodList = \n new Dictionary<SomeEnum, Action<User>>()\n\nmethodList.Add(SomeEnum.One, DoSomething);\nmethodList.Add(SomeEnum.Two, DoSomethingElse); \n methodList[SomeEnum](someUser);\n SomeOtherMethod(Action<User> someMethodToUse, User someUser)\n{\n someMethodToUse(someUser);\n} \n var neededMethod = methodList[SomeEnum];\nSomeOtherMethod(neededMethod, someUser);\n"
},
{
"answer_id": 371086,
"author": "Binary Worrier",
"author_id": 18797,
"author_profile": "https://Stackoverflow.com/users/18797",
"pm_score": 4,
"selected": false,
"text": "Action<string> static void Main(string[] args)\n {\n string[] words = \"This is as easy as it looks\".Split(' ');\n\n // Passing WriteLine as the action\n Array.ForEach(words, Console.WriteLine); \n }\n"
},
{
"answer_id": 371108,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 4,
"selected": false,
"text": "btnSubmit.Click += (sender, e) => MessageBox.Show(\"You clicked save!\");\n"
},
{
"answer_id": 371318,
"author": "Andrew Hare",
"author_id": 34211,
"author_profile": "https://Stackoverflow.com/users/34211",
"pm_score": 7,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n Action<String> print = new Action<String>(Program.Print);\n\n List<String> names = new List<String> { \"andrew\", \"nicole\" };\n\n names.ForEach(print);\n\n Console.Read();\n }\n\n static void Print(String s)\n {\n Console.WriteLine(s);\n }\n}\n print using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n List<String> names = new List<String> { \"andrew\", \"nicole\" };\n\n names.ForEach(s => Console.WriteLine(s));\n\n Console.Read();\n }\n}\n"
},
{
"answer_id": 2593122,
"author": "Ron Skufca",
"author_id": 4096,
"author_profile": "https://Stackoverflow.com/users/4096",
"pm_score": 4,
"selected": false,
"text": "DataRow dr = GetRow();\nthis.Invoke(new Action(() => {\n txtFname.Text = dr[\"Fname\"].ToString();\n txtLname.Text = dr[\"Lname\"].ToString(); \n txtMI.Text = dr[\"MI\"].ToString();\n txtSSN.Text = dr[\"SSN\"].ToString();\n txtSSN.ButtonsRight[\"OpenDialog\"].Visible = true;\n txtSSN.ButtonsRight[\"ListSSN\"].Visible = true;\n txtSSN.Focus();\n}));\n"
},
{
"answer_id": 25219769,
"author": "evilone",
"author_id": 526217,
"author_profile": "https://Stackoverflow.com/users/526217",
"pm_score": 2,
"selected": false,
"text": "BuildPerson() public class Program\n{\n public static void Main(string[] args)\n {\n var person1 = BuildPerson();\n\n Console.WriteLine(person1.Firstname);\n Console.WriteLine(person1.Lastname);\n Console.WriteLine(person1.BirthDate);\n Console.WriteLine(person1.Height);\n\n var person2 = BuildPerson(p =>\n {\n p.Firstname = \"Jane\";\n p.BirthDate = DateTime.Today;\n p.Height = 1.76;\n });\n\n Console.WriteLine(person2.Firstname);\n Console.WriteLine(person2.Lastname);\n Console.WriteLine(person2.BirthDate);\n Console.WriteLine(person2.Height);\n\n Console.Read();\n }\n\n public static Person BuildPerson(Action<Person> overrideAction = null)\n {\n var person = new Person()\n {\n Firstname = \"John\",\n Lastname = \"Doe\",\n BirthDate = new DateTime(2012, 2, 2)\n };\n\n if (overrideAction != null)\n overrideAction(person);\n\n return person;\n }\n }\n\n public class Person\n {\n public string Firstname { get; set; }\n public string Lastname { get; set; }\n public DateTime BirthDate { get; set; }\n public double Height { get; set; }\n }\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41968/"
] |
371,055 | <p>I am trying to modify the below program to ensure each msg is converted to utf-8 using Encode::decode(), but I am unsure of how and where to place this to make it work.</p>
<pre><code>#!/usr/bin/perl
use warnings;
use strict;
use Mail::Box::Manager;
open (MYFILE, '>>data.txt');
binmode(MYFILE, ':encoding(UTF-8)');
my $file = shift || $ENV{MAIL};
my $mgr = Mail::Box::Manager->new(
access => 'r',
);
my $folder = $mgr->open( folder => $file )
or die "$file: Unable to open: $!\n";
for my $msg ( sort { $a->timestamp <=> $b->timestamp } $folder->messages)
{
my $to = join( ', ', map { $_->format } $msg->to );
my $from = join( ', ', map { $_->format } $msg->from );
my $date = localtime( $msg->timestamp );
my $subject = $msg->subject;
my $body = $msg->decoded->string;
# Strip all quoted text
$body =~ s/^>.*$//msg;
print MYFILE <<"";
From: $from
To: $to
Date: $date
Subject: $subject
\n
$body
}
</code></pre>
| [
{
"answer_id": 371074,
"author": "Sorskoot",
"author_id": 31722,
"author_profile": "https://Stackoverflow.com/users/31722",
"pm_score": 2,
"selected": false,
"text": "SpecialRequest(this,\n new BalieEventArgs \n { \n Message = \"A Message\", \n Action = UpdateMethod, \n Data = someDataObject \n });\n public void UpdateMethod(string SpecialCode){ }\n public class MyEventArgs : EventArgs\n {\n public string Message;\n public object Data;\n public Action<String> Action;\n }\n"
},
{
"answer_id": 371077,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 4,
"selected": false,
"text": "private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() { \n {typeof(TextBox), c => ((TextBox)c).Clear()},\n {typeof(CheckBox), c => ((CheckBox)c).Checked = false},\n {typeof(ListBox), c => ((ListBox)c).Items.Clear()},\n {typeof(RadioButton), c => ((RadioButton)c).Checked = false},\n {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},\n {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}\n };\n"
},
{
"answer_id": 371080,
"author": "Programmin Tool",
"author_id": 21691,
"author_profile": "https://Stackoverflow.com/users/21691",
"pm_score": 6,
"selected": false,
"text": "switch(SomeEnum)\n{\n case SomeEnum.One:\n DoThings(someUser);\n break;\n case SomeEnum.Two:\n DoSomethingElse(someUser);\n break;\n}\n Dictionary<SomeEnum, Action<User>> methodList = \n new Dictionary<SomeEnum, Action<User>>()\n\nmethodList.Add(SomeEnum.One, DoSomething);\nmethodList.Add(SomeEnum.Two, DoSomethingElse); \n methodList[SomeEnum](someUser);\n SomeOtherMethod(Action<User> someMethodToUse, User someUser)\n{\n someMethodToUse(someUser);\n} \n var neededMethod = methodList[SomeEnum];\nSomeOtherMethod(neededMethod, someUser);\n"
},
{
"answer_id": 371086,
"author": "Binary Worrier",
"author_id": 18797,
"author_profile": "https://Stackoverflow.com/users/18797",
"pm_score": 4,
"selected": false,
"text": "Action<string> static void Main(string[] args)\n {\n string[] words = \"This is as easy as it looks\".Split(' ');\n\n // Passing WriteLine as the action\n Array.ForEach(words, Console.WriteLine); \n }\n"
},
{
"answer_id": 371108,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 4,
"selected": false,
"text": "btnSubmit.Click += (sender, e) => MessageBox.Show(\"You clicked save!\");\n"
},
{
"answer_id": 371318,
"author": "Andrew Hare",
"author_id": 34211,
"author_profile": "https://Stackoverflow.com/users/34211",
"pm_score": 7,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n Action<String> print = new Action<String>(Program.Print);\n\n List<String> names = new List<String> { \"andrew\", \"nicole\" };\n\n names.ForEach(print);\n\n Console.Read();\n }\n\n static void Print(String s)\n {\n Console.WriteLine(s);\n }\n}\n print using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n List<String> names = new List<String> { \"andrew\", \"nicole\" };\n\n names.ForEach(s => Console.WriteLine(s));\n\n Console.Read();\n }\n}\n"
},
{
"answer_id": 2593122,
"author": "Ron Skufca",
"author_id": 4096,
"author_profile": "https://Stackoverflow.com/users/4096",
"pm_score": 4,
"selected": false,
"text": "DataRow dr = GetRow();\nthis.Invoke(new Action(() => {\n txtFname.Text = dr[\"Fname\"].ToString();\n txtLname.Text = dr[\"Lname\"].ToString(); \n txtMI.Text = dr[\"MI\"].ToString();\n txtSSN.Text = dr[\"SSN\"].ToString();\n txtSSN.ButtonsRight[\"OpenDialog\"].Visible = true;\n txtSSN.ButtonsRight[\"ListSSN\"].Visible = true;\n txtSSN.Focus();\n}));\n"
},
{
"answer_id": 25219769,
"author": "evilone",
"author_id": 526217,
"author_profile": "https://Stackoverflow.com/users/526217",
"pm_score": 2,
"selected": false,
"text": "BuildPerson() public class Program\n{\n public static void Main(string[] args)\n {\n var person1 = BuildPerson();\n\n Console.WriteLine(person1.Firstname);\n Console.WriteLine(person1.Lastname);\n Console.WriteLine(person1.BirthDate);\n Console.WriteLine(person1.Height);\n\n var person2 = BuildPerson(p =>\n {\n p.Firstname = \"Jane\";\n p.BirthDate = DateTime.Today;\n p.Height = 1.76;\n });\n\n Console.WriteLine(person2.Firstname);\n Console.WriteLine(person2.Lastname);\n Console.WriteLine(person2.BirthDate);\n Console.WriteLine(person2.Height);\n\n Console.Read();\n }\n\n public static Person BuildPerson(Action<Person> overrideAction = null)\n {\n var person = new Person()\n {\n Firstname = \"John\",\n Lastname = \"Doe\",\n BirthDate = new DateTime(2012, 2, 2)\n };\n\n if (overrideAction != null)\n overrideAction(person);\n\n return person;\n }\n }\n\n public class Person\n {\n public string Firstname { get; set; }\n public string Lastname { get; set; }\n public DateTime BirthDate { get; set; }\n public double Height { get; set; }\n }\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
371,059 | <p>Here is my query:</p>
<pre><code> Select Top 10 CS.CaseStudyID,
CS.Title,
CSI.ImageFileName
From CaseStudy CS
Left Join CaseStudyImage CSI On CS.CaseStudyID = CSI.CaseStudyID
And CSI.CSImageID in(
Select Min(CSImageID) -- >not really satisfactory
From CaseStudyImage
Group By CaseStudyID
)
Order By CS.CaseStudyID ASC
</code></pre>
<p>Instead of min(CSImageID) I'd like a random record from my CaseStudyImage table that corresponds to the particular case study</p>
<p>Can anyone point me in the right direction pleas?</p>
| [
{
"answer_id": 371061,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 0,
"selected": false,
"text": "ORDER BY RAND() LIMIT 1"
},
{
"answer_id": 375418,
"author": "Chaowlert Chaisrichalermpol",
"author_id": 2398110,
"author_profile": "https://Stackoverflow.com/users/2398110",
"pm_score": 1,
"selected": false,
"text": "WITH CSI AS (\n SELECT CSI.CaseStudyID, CSI.ImageFileName,\n ROW_NUMBER() OVER(PARTITION BY CSI.CaseStudyID ORDER BY newid()) AS RowNumber\n FROM CaseStudyImage CSI\n)\nSELECT TOP (10) CS.CaseStudyID, CS.Title, CSI.ImageFileName\nFROM CaseStudy CS LEFT JOIN CSI On CS.CaseStudyID = CSI.CaseStudyID\nWHERE CSI.RowNumber = 1\nORDER BY CS.CaseStudyID ASC\n"
},
{
"answer_id": 377138,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 1,
"selected": false,
"text": "ORDER BY NEWID()"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11394/"
] |
371,064 | <p>I have unsorted map of key value pairs.</p>
<pre><code>input = {
"xa" => "xavalue",
"ab" => "abvalue",
"aa" => "aavalue",
"ba" => "bavalue",
}
</code></pre>
<p>Now I want to sort them by the key and cluster them into sections by the first character of the key. Similar to this:</p>
<pre><code>output1 = {
"a" => {
"aa" => "aavalue",
"ab" => "abvalue",
},
"b" => {
"ba" => "bavalue",
},
"x" => {
"xa" => "xavalue",
},
}
</code></pre>
<ol>
<li><p>While this is relatively trivial I am looking for a concise way to express this transformation from input to output1 in ruby. (My approach is probably too verbose as to ruby standards)</p></li>
<li><p>You might also have noticed that maps are (usually) not ordered. So the above data structure will not work appropriately unless I manually sort the keys and wrap the access to the map. So how would I create a key ordered map in ruby? Or is there one already?</p></li>
<li><p>If the ordered map approach is not that easy I would have to change the final structure into something like the following. Again I am looking for some concise ruby code to come from input to output2.</p></li>
</ol>
<p>.</p>
<pre><code>output2 = [
{
"name" => "a",
"keys" => [ "aa", "ab" ],
"values" => [ "aavalue", "abvalue" ],
},
{
"name" => "b",
"keys" => [ "ba" ],
"values" => [ "bavalue" ],
},
{
"name" => "x",
"keys" => [ "xa" ],
"values" => [ "xavalue" ],
}
]
</code></pre>
| [
{
"answer_id": 371234,
"author": "ttepasse",
"author_id": 46657,
"author_profile": "https://Stackoverflow.com/users/46657",
"pm_score": 1,
"selected": false,
"text": "class Hash\n def clustered\n clustered = Hash.new\n sort.each do | key, value |\n first = key[0,1]\n unless clustered.has_key?(first)\n clustered[first] = Hash.new \n end\n clustered[first][key] = value\n end\n clustered\n end\nend\n"
},
{
"answer_id": 371381,
"author": "Bkkbrad",
"author_id": 44476,
"author_profile": "https://Stackoverflow.com/users/44476",
"pm_score": 1,
"selected": false,
"text": "output = input.inject({}){ |h, p| k,v=p; (h[k[0..0]] ||= {})[k] = v; h}\n"
},
{
"answer_id": 371400,
"author": "Thiago Arrais",
"author_id": 17801,
"author_profile": "https://Stackoverflow.com/users/17801",
"pm_score": 3,
"selected": true,
"text": "output = input.inject({}) { |acc, pair|\n letter = pair.first[0].chr\n acc[letter] ||= {}\n acc[letter][pair.first] = pair.last\n acc\n}.sort\n [ [\"a\", {\"aa\"=>\"aavalue\",\n \"ab\"=>\"abvalue\"}],\n [\"b\", {\"ba\"=>\"bavalue\"}],\n [\"x\", {\"xa\"=>\"xavalue\"}]]\n output.map {|pair| {pair.first => pair.last}}\n [{\"a\"=>{\"aa\"=>\"aavalue\",\n \"ab\"=>\"abvalue\"}},\n {\"b\"=>{\"ba\"=>\"bavalue\"}},\n {\"x\"=>{\"xa\"=>\"xavalue\"}}]\n output2 = output.map { |pair|\n hash = pair.last\n { 'name' => pair.first,\n 'keys' => hash.keys,\n 'values' => hash.values }\n}\n"
},
{
"answer_id": 408459,
"author": "tcurdt",
"author_id": 33165,
"author_profile": "https://Stackoverflow.com/users/33165",
"pm_score": 1,
"selected": false,
"text": "output1 = input.inject({}) { |acc, pair|\n letter = pair.first[0].chr\n acc[letter] ||= {}\n acc[letter][pair.first] = pair.last\n acc\n}.sort\n\noutput2 = output1.inject([]) { |acc, pair|\n acc << {\n 'name' => pair.first,\n 'keys' => pair.last.keys(),\n 'values' => pair.last.values()\n }\n acc\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33165/"
] |
371,072 | <p>I have the code pasted below, which servers as the core of a small ajax application. This was working fine previously, with makewindows actually displaying a popup containing the rsult of artcile_desc. I seem to have an error before that function however, as now only the actual php code is outputted. This is not a problem with my server setup, as I am the administrator and this has not changed.</p>
<p>I get the following errors with Firebug, but I am not sure what they mean.</p>
<pre><code>unterminated string literal
onclick(click clientX=52, clientY=50)1GmRZ%2F...D9g%3D%3D (line 2)
[Break on this error] child1.document.write("<br />\n
1GmRZ%2F...D9g%3D%3D (line 2)
updateByQuery is not defined
onclick(click clientX=29, clientY=17)CLQWYjW1...WlQ%3D%3D (line 2)
[Break on this error] updateByQuery("Layer3", "Ed Hardy");
var xmlHttp
var layername
var url
function update(layer, url) {
var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
//etc
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function updateByPk(layer, pk) {
url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random();
update(layer, url);
}
function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}
</code></pre>
<p>Which whatever I try the makewindows function simply outputs the php code as the html source, and not the result of the php code. This was previously working fine, and I am not sure what I have changed to result in this behavior.</p>
<p>I have pasted all the code now. An error is generated by a link that calls updateByQuery, preventing makewindows from being parsed correctly..I think. </p>
<p>edit: the php is getting parsed when I use this code:</p>
<pre><code>function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}
</code></pre>
<p>But not the code above</p>
<p>the result of the php is this:</p>
<pre><code>child1.document.write("<br />
58<b>Notice</b>: Undefined variable: row2 in <b>C:\Programme\EasyPHP 2.0b1\www\records4\fetchlayers.js</b> on line <b>57</b><br />
59null");
</code></pre>
<p>which cuases an error</p>
| [
{
"answer_id": 371284,
"author": "Jay",
"author_id": 41690,
"author_profile": "https://Stackoverflow.com/users/41690",
"pm_score": 2,
"selected": true,
"text": "child1.document.write(\"<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>\");\n child1.document.write(\"<?php echo json_encode(htmlspecialchars($row2['ARTICLE_DESC'], ENT_QUOTES)); ?>\");\n child1.document.write(\"<?php echo htmlspecialchars($row2['ARTICLE_DESC']), ENT_QUOTES); ?>\");\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
371,079 | <p>I have a problem with the jQuery-UI dialog in my ASP.NET form:</p>
<pre><code>$("#pnlReceiverDialog").dialog({
autoOpen:false,
modal: true,
height:220,
width:500,
resizable :false,
overlay: { opacity: 0.5,background: "black" },
buttons: {
"Cancel": function() {
$(this).dialog("close");
},
"Ok": function() {
__doPostBack('ctl00$phContent$ctl00$LetterLocation$pupNewReceiver','')
}
}
});
</code></pre>
<p><code>pnlReceiverDialog</code> contains an ASP.NET <code>TextBox</code>.</p>
<p>When I click on the OK button, the form posts back but the textbox doesn't have a value.</p>
| [
{
"answer_id": 4193284,
"author": "Lars Thorén",
"author_id": 372208,
"author_profile": "https://Stackoverflow.com/users/372208",
"pm_score": 0,
"selected": false,
"text": "$(\"#ModalId\").parent().appendTo(jQuery(\"form:first\"));\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,107 | <p>Different iPhones have different published memory 4GB, 8GB and 16GB. The touch can have 32GB. My understanding is this is the off-line memory (disk alike). </p>
<p>How much actual fast ram is there in the device available for my Cocoa Application? </p>
<p>Is there a preconfigured virtual amount?</p>
| [
{
"answer_id": 3085744,
"author": "AnthonyLambert",
"author_id": 31762,
"author_profile": "https://Stackoverflow.com/users/31762",
"pm_score": 5,
"selected": true,
"text": "iPhone = 128 MB\niPhone 3G = 128 MB\niPhone 3GS = 256 MB\niPhone 4 = 512 MB\niPhone 4S = 512 MB \niPhone 5 = 1024 MB\niPhone 5S = 1024 MB\n\niPod Touch 1G = 128 MB\niPod Touch 2G = 128 MB\niPod Touch 3G = 256 MB\niPod Touch 4G = 256 MB\niPod Touch 5G = 512 MB\n\niPad = 256 MB\niPad 2 = 512 MB\niPad (3) = 1024 MB\niPad (4) = 1024 MB\niPad Air = 1024 MB\n\niPad mini (1G) = 512 MB\niPad mini (2G) = 1024 MB\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31762/"
] |
371,109 | <p><strong>UPDATE</strong> </p>
<p>I have combined various answers from here into a 'definitive' answer on a <a href="https://stackoverflow.com/questions/1747235/weak-event-handler-model-for-use-with-lambdas/1747236#1747236">new question</a>.</p>
<p><strong>Original question</strong></p>
<p>In my code I have an event publisher, which exists for the whole lifetime of the application (here reduced to bare essentials):</p>
<pre><code>public class Publisher
{
//ValueEventArgs<T> inherits from EventArgs
public event EventHandler<ValueEventArgs<bool>> EnabledChanged;
}
</code></pre>
<p>Because this publisher can be used all over the place, I was quite pleased with myself for creating this little helper class to avoid re-writing the handling code in all subscribers:</p>
<pre><code>public static class Linker
{
public static void Link(Publisher publisher, Control subscriber)
{
publisher.EnabledChanged += (s, e) => subscriber.Enabled = e.Value;
}
//(Non-lambda version, if you're not comfortable with lambdas)
public static void Link(Publisher publisher, Control subscriber)
{
publisher.EnabledChanged +=
delegate(object sender, ValueEventArgs<bool> e)
{
subscriber.Enabled = e.Value;
};
}
}
</code></pre>
<p>It worked fine, until we started using it on smaller machines, when I started getting the occasional:</p>
<pre><code>System.ComponentModel.Win32Exception
Not enough storage is available to process this command
</code></pre>
<p>As it turns out, there is one place in the code where subscribers controls are being dynamically created, added and removed from a form. Given my advanced understanding of garbage collection etc (i.e. none, until yesterday), I never thought to clear up behind me, as in the vast majority of cases, the subscribers also live for the lifetime of the application.</p>
<p>I've fiddled around a while with <a href="http://diditwith.net/CommentView,guid,aacdb8ae-7baa-4423-a953-c18c1c7940ab.aspx#commentstart" rel="nofollow noreferrer">Dustin Campbell's WeakEventHandler</a>, but it <em>doesn't work with anonymous delegates</em> (not for me anyway).</p>
<p>Is there anyway out of this problem? I really would like to avoid having to copy-paste boiler-plate code all over the shop.</p>
<p>(Oh, and don't bother with asking me WHY we are creating and destroying controls all the time, it wasn't my design decision...)</p>
<p>(PS: It's a winforms application, but we've upgraded to VS2008 and .Net 3.5, should I consider using the <a href="http://msdn.microsoft.com/en-us/library/aa970850.aspx" rel="nofollow noreferrer">Weak Event pattern</a>?)</p>
<p>(PPS: Good <a href="http://#371150" rel="nofollow noreferrer">answer from Rory</a>, but if anyone can come up with an equivalent to the WeakEventHandler which avoids me having to remember to explicitly UnLink/Dispose, that would be cool...)</p>
<p><strong>EDIT</strong> I must admit that I worked around this problem by "recycling" the controls in question. However the workaround has come back to haunt me as the 'key' I was using is apparently non-unique (sob). I've just discovered other links <a href="http://danylaporte.blogspot.com/2008/09/weakeventhandler.html" rel="nofollow noreferrer">here</a> (tried this - seems to be a bit <em>too</em> weak - GC clears delegates even if target is still alive, same problem with <a href="https://stackoverflow.com/questions/371109/garbage-collection-when-using-anonymous-delegates-for-event-handling/955928#955928">s,oɔɯǝɹ answer</a> below), <a href="http://code.logos.com/blog/2008/08/event_subscription_using_weak_references.html" rel="nofollow noreferrer">here</a> (forces you to modify publisher, and doesn't really work with anonymous delegates) and <a href="http://joshsmithonwpf.wordpress.com/2009/04/06/a-mediator-prototype-for-wpf-apps/" rel="nofollow noreferrer">here</a> (cited-as-incomplete by Dustin Campbell). </p>
<p>It occurs to me that what I'm looking for may be semantically impossible - closures are designed to 'hang around even after I'm gone'. </p>
<p>I've found another workaround, so I'll stick with that, pending a <a href="http://blogs.msdn.com/ericlippert/" rel="nofollow noreferrer">voice from the gods</a>.</p>
| [
{
"answer_id": 371150,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 3,
"selected": false,
"text": "public static class Linker\n{\n\n //(Non-lambda version, I'm not comfortable with lambdas:)\n public static EventHandler<ValueEventArgs<bool>> Link(Publisher publisher, Control subscriber)\n {\n EventHandler<ValueEventArgs<bool>> handler = delegate(object sender, ValueEventArgs<bool> e)\n {\n subscriber.Enabled = e.Value;\n };\n publisher.EnabledChanged += handler;\n return handler;\n }\n\n public static void UnLink(Publisher publisher, EventHandler<ValueEventArgs<bool>> handler)\n {\n publisher.EnabledChanged -= handler;\n }\n\n}\n"
},
{
"answer_id": 955928,
"author": "oɔɯǝɹ",
"author_id": 62662,
"author_profile": "https://Stackoverflow.com/users/62662",
"pm_score": 1,
"selected": false,
"text": "// strongly typed weak reference\npublic class WeakReference<T> : WeakReference\n where T : class\n{\n public WeakReference(T target)\n : base(target)\n { }\n\n public WeakReference(T target, bool trackResurrection)\n : base(target, trackResurrection)\n { }\n\n public new T Target\n {\n get { return base.Target as T; }\n set { base.Target = value; }\n }\n}\n\n// weak referenced generic event handler\npublic class WeakEventHandler<TEventArgs> : WeakReference<EventHandler<TEventArgs>>\n where TEventArgs : EventArgs\n{\n public WeakEventHandler(EventHandler<TEventArgs> target)\n : base(target)\n { }\n\n protected void Invoke(object sender, TEventArgs e)\n {\n if (Target != null)\n {\n Target(sender, e);\n }\n }\n\n public static implicit operator EventHandler<TEventArgs>(WeakEventHandler<TEventArgs> weakEventHandler)\n {\n if (weakEventHandler != null)\n {\n if (weakEventHandler.IsAlive)\n {\n return weakEventHandler.Invoke;\n }\n }\n\n return null;\n }\n}\n\n// weak reference common event handler\npublic class WeakEventHandler : WeakReference<EventHandler>\n{\n public WeakEventHandler(EventHandler target)\n : base(target)\n { }\n\n protected void Invoke(object sender, EventArgs e)\n {\n if (Target != null)\n {\n Target(sender, e);\n }\n }\n\n public static implicit operator EventHandler(WeakEventHandler weakEventHandler)\n {\n if (weakEventHandler != null)\n {\n if (weakEventHandler.IsAlive)\n {\n return weakEventHandler.Invoke;\n }\n }\n\n return null;\n }\n}\n\n// observable class, fires events\npublic class Observable\n{\n public Observable() { Console.WriteLine(\"new Observable()\"); }\n ~Observable() { Console.WriteLine(\"~Observable()\"); }\n\n public event EventHandler OnChange;\n\n protected virtual void DoOnChange()\n {\n EventHandler handler = OnChange;\n\n if (handler != null)\n {\n Console.WriteLine(\"DoOnChange()\");\n handler(this, EventArgs.Empty);\n }\n }\n\n public void Change()\n {\n DoOnChange();\n }\n}\n\n// observer, event listener\npublic class Observer\n{\n public Observer() { Console.WriteLine(\"new Observer()\"); }\n ~Observer() { Console.WriteLine(\"~Observer()\"); }\n\n public void OnChange(object sender, EventArgs e)\n {\n Console.WriteLine(\"-> Observer.OnChange({0}, {1})\", sender, e);\n }\n}\n\n// sample usage and test code\npublic static class Program\n{\n static void Main()\n {\n Observable subject = new Observable();\n Observer watcher = new Observer();\n\n Console.WriteLine(\"subscribe new WeakEventHandler()\\n\");\n subject.OnChange += new WeakEventHandler(watcher.OnChange);\n subject.Change();\n\n Console.WriteLine(\"\\nObserver = null, GC\");\n watcher = null;\n GC.Collect(0, GCCollectionMode.Forced);\n GC.WaitForPendingFinalizers();\n\n subject.Change();\n\n if (Debugger.IsAttached)\n {\n Console.Write(\"Press any key to continue . . . \");\n Console.ReadKey(true);\n }\n }\n}\n new Observable()\nnew Observer()\nsubscribe new WeakEventHandler()\n\nDoOnChange()\n-> Observer.OnChange(ConsoleApplication4.Observable, System.EventArgs)\n\nObserver = null, GC\n~Observer()\nDoOnChange()\n~Observable()\nPress any key to continue . . .\n"
},
{
"answer_id": 1447619,
"author": "Egor",
"author_id": 175823,
"author_profile": "https://Stackoverflow.com/users/175823",
"pm_score": 4,
"selected": true,
"text": "\npublic static class Linker {\n public static void Link(Publisher publisher, Control subscriber) {\n // anonymous method references the subscriber only through weak \n // references,so its existance doesn't interfere with garbage collection\n var subscriber_weak_ref = new WeakReference(subscriber);\n\n // this instance variable will stay in memory as long as the anonymous\n // method holds a reference to it we declare and initialize it to \n // reserve the memory (also, compiler complains about uninitialized\n // variable otherwise)\n EventHandler<ValueEventArgs<bool>> handler = null;\n\n // when the handler is created it will grab references to the local \n // variables used within, keeping them in memory after the function \n // scope ends\n handler = delegate(object sender, ValueEventArgs<bool> e) {\n var subscriber_strong_ref = subscriber_weak_ref.Target as Control;\n\n if (subscriber_strong_ref != null) \n subscriber_strong_ref.Enabled = e.Value;\n else {\n // unsubscribing the delegate from within itself is risky, but\n // because only one instance exists and nobody else has a\n // reference to it we can do this\n ((Publisher)sender).EnabledChanged -= handler;\n\n // by assigning the original instance variable pointer to null\n // we make sure that nothing else references the anonymous\n // method and it can be collected. After this, the weak\n // reference and the handler pointer itselfwill be eligible for\n // collection as well.\n handler = null; \n }\n };\n\n publisher.EnabledChanged += handler;\n }\n}\n"
},
{
"answer_id": 1687255,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 0,
"selected": false,
"text": "where T : delegate private static void SetAnyGenericHandler<S, T>(\n Action<EventHandler<T>> add, //to add event listener to publisher\n Action<EventHandler<T>> remove, //to remove event listener from publisher\n S subscriber, //ref to subscriber (to pass to consume)\n Action<S, T> consume) //called when event is raised*\n where T : EventArgs \n where S : class\n{\n var subscriber_weak_ref = new WeakReference(subscriber);\n EventHandler<T> handler = null;\n handler = delegate(object sender, T e)\n {\n var subscriber_strong_ref = subscriber_weak_ref.Target as S;\n if(subscriber_strong_ref != null)\n {\n Console.WriteLine(\"New event received by subscriber\");\n consume(subscriber_strong_ref, e);\n }\n else\n {\n remove(handler);\n handler = null;\n }\n };\n add(handler);\n}\n EventHandler<T> consume SetAnyGenericHandler(\n h => publisher.EnabledChanged += h, \n h => publisher.EnabledChanged -= h, \n subscriber, \n (Subscriber s, ValueEventArgs<bool> e) => s.Enabled = e.Value);\n SetAnyGenericHandler<Subscriber, ValueEventArgs<bool>>(\n h => publisher.EnabledChanged += h, \n h => publisher.EnabledChanged -= h, \n subscriber, \n (s, e) => s.Enabled = e.Value);\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
371,112 | <p>Using the CRM views, is there a way to retrieve a list of all of the activities linked to a specific account?</p>
<p>I want it to retrieve not only those associated with the account directly, but also those associated with the account's contacts, cases, etc. I am trying to replicate the list generated when you click the Activities option from within an account.</p>
<p>So far I have retrieved the contacts for the account and their activities. I also noticed that CRM doesn't seem to always return what I expect. Sometimes activities related to contacts of the account are not displayed. Other times, emails / appointments that are logically related to the account but have nothing in their regardingobjectid field are shown.</p>
<p>I am hoping this doesn't mean creating the mother of all joins or querying each activity type separately. Particularly because I need all of the related case activities, opportunity activities, etc.</p>
| [
{
"answer_id": 398242,
"author": "brendan",
"author_id": 225,
"author_profile": "https://Stackoverflow.com/users/225",
"pm_score": 1,
"selected": true,
"text": "Declare @account_guid varchar(200)\nSelect @account_guid = 'insert some guid here'\n\nDeclare @GUIDS as Table(id varchar(200), fullname varchar(200), objecttype char(2)) \nDeclare @ActivityIds as Table(id varchar(200))\n\n--grab all guids we need activities for\n Insert Into @GUIDS\n Select contactid, fullname, 'C'\n From FilteredContact\n Where accountid = @account_guid\n UNION ALL\n Select accountid, [name], 'A'\n From FilteredAccount\n Where accountid = @account_guid \n\n--find all activities where the account/contact are referred to\nInsert Into @ActivityIds\nSelect activityid\nFrom FilteredActivityParty fap\nJoin @GUIDS g on g.id=fap.partyid\nGroup By activityid\n\nSelect *\nFrom FilteredActivityPointer fap\nJoin @ActivityIds a on fap.activityid = a.id\nWhere statecode<>2 --hide canceled items\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44938/"
] |
371,115 | <p>I have a bunch of log files. I need to find out how many times a string occurs in all files.</p>
<pre><code>grep -c string *
</code></pre>
<p>returns</p>
<pre><code>...
file1:1
file2:0
file3:0
...
</code></pre>
<p>Using a pipe I was able to get only files that have one or more occurrences:</p>
<pre><code>grep -c string * | grep -v :0
...
file4:5
file5:1
file6:2
...
</code></pre>
<p>How can I get only the combined count? (If it returns <code>file4:5, file5:1, file6:2</code>, I want to get back 8.)</p>
| [
{
"answer_id": 371124,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 5,
"selected": false,
"text": "grep string * | wc -l\n"
},
{
"answer_id": 371130,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 9,
"selected": true,
"text": "cat * | grep -c string\n"
},
{
"answer_id": 371132,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 4,
"selected": false,
"text": "cat * | grep -c string\n cat"
},
{
"answer_id": 3249761,
"author": "Jeremy Lavine",
"author_id": 391985,
"author_profile": "https://Stackoverflow.com/users/391985",
"pm_score": 8,
"selected": false,
"text": "grep -o string * | wc -l\n"
},
{
"answer_id": 7597293,
"author": "mumrah",
"author_id": 321379,
"author_profile": "https://Stackoverflow.com/users/321379",
"pm_score": 4,
"selected": false,
"text": "grep -c string * | awk 'BEGIN{FS=\":\"}{x+=$2}END{print x}'\n"
},
{
"answer_id": 14529561,
"author": "Kreuvf",
"author_id": 2012224,
"author_profile": "https://Stackoverflow.com/users/2012224",
"pm_score": 3,
"selected": false,
"text": "grep -c string * | sed -r 's/^.*://' | awk 'BEGIN{}{x+=$1}END{print x}'\n string"
},
{
"answer_id": 15106593,
"author": "Kaofu",
"author_id": 2114353,
"author_profile": "https://Stackoverflow.com/users/2114353",
"pm_score": 5,
"selected": false,
"text": "grep -oh string * | wc -w\n"
},
{
"answer_id": 15106899,
"author": "Vijay",
"author_id": 134713,
"author_profile": "https://Stackoverflow.com/users/134713",
"pm_score": 4,
"selected": false,
"text": "perl -lne '$count++ for m/<pattern>/g;END{print $count}' *\n"
},
{
"answer_id": 20543368,
"author": "azmeuk",
"author_id": 2180332,
"author_profile": "https://Stackoverflow.com/users/2180332",
"pm_score": 4,
"selected": false,
"text": "-R -I grep -RIc string .\n"
},
{
"answer_id": 21313880,
"author": "NTwoO",
"author_id": 2220599,
"author_profile": "https://Stackoverflow.com/users/2220599",
"pm_score": 0,
"selected": false,
"text": " cat * |sed s/string/\\\\\\nstring\\ /g |grep string |wc -l\n"
},
{
"answer_id": 24170629,
"author": "Excalibur",
"author_id": 513739,
"author_profile": "https://Stackoverflow.com/users/513739",
"pm_score": 2,
"selected": false,
"text": "<url> awk '/<url>/{m=gsub(\"<url>\",\"\");total+=m}END{print total}' some_directory/*.xml\n"
},
{
"answer_id": 30804157,
"author": "Mitul Patel",
"author_id": 5003019,
"author_profile": "https://Stackoverflow.com/users/5003019",
"pm_score": 3,
"selected": false,
"text": "grep -i STRING/StrING/string grep -oci string * | grep -v :0\n grep -ochi string *\n"
},
{
"answer_id": 34297371,
"author": "Quantic",
"author_id": 5095502,
"author_profile": "https://Stackoverflow.com/users/5095502",
"pm_score": 2,
"selected": false,
"text": "grep -ro \"pattern to find in files\" \"Directory to recursively search\" | grep -c \"pattern to find in files\"\n -r -o -c"
},
{
"answer_id": 45149208,
"author": "Dmitry Tarashkevich",
"author_id": 6816107,
"author_profile": "https://Stackoverflow.com/users/6816107",
"pm_score": 2,
"selected": false,
"text": "find . -type f -exec cat {} + | grep -c 'string'\n"
},
{
"answer_id": 50103741,
"author": "Andriy Makukha",
"author_id": 5407270,
"author_profile": "https://Stackoverflow.com/users/5407270",
"pm_score": 4,
"selected": false,
"text": "grep -RIci \"tcp\" . | awk -v FS=\":\" -v OFS=\"\\t\" '$2>0 { print $2, $1 }' | sort -hr\n 53 ./HTTPClient/src/HTTPClient.cpp\n21 ./WiFi/src/WiFiSTA.cpp\n19 ./WiFi/src/ETH.cpp\n13 ./WiFi/src/WiFiAP.cpp\n4 ./WiFi/src/WiFiClient.cpp\n4 ./HTTPClient/src/HTTPClient.h\n3 ./WiFi/src/WiFiGeneric.cpp\n2 ./WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino\n2 ./WiFiClientSecure/src/ssl_client.cpp\n1 ./WiFi/src/WiFiServer.cpp\n grep -RIci NEEDLE . awk ... sort -hr -c grep -c \"tcp\" *.txt | awk -v FS=\":\" -v OFS=\"\\t\" '$2>0 { print $2, $1 }' | sort -hr\n"
},
{
"answer_id": 69168927,
"author": "Alan Tegel",
"author_id": 13282547,
"author_profile": "https://Stackoverflow.com/users/13282547",
"pm_score": 0,
"selected": false,
"text": "awk -v RS='' -v FPAT='fast' '{print NF,FILENAME}' <file1..N>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17469/"
] |
371,133 | <p>I have a class that contains a list of objects. What's the best way to run some code in the class when the list is modified?</p>
<pre><code>class MyManagerClass
{
ArrayList list = new ArrayList(); // will likely be a different collection class
private OnItemAddedToList(object o)
{
// how to call this?
}
private OnItemRemovedFromList(object o)
{
// how to call this?
}
}
</code></pre>
| [
{
"answer_id": 371163,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 1,
"selected": false,
"text": "CollectionChanged ItemAdded"
},
{
"answer_id": 371167,
"author": "Alex J",
"author_id": 27667,
"author_profile": "https://Stackoverflow.com/users/27667",
"pm_score": 3,
"selected": true,
"text": "System.Collections.ObjectModel.Collection<T> class MyManagerClass\n{\n private class MyCollection : System.Collections.ObjectModel.Collection<object>\n {\n private MyManagerClass manager;\n\n private MyCollection(MyManagerClass manager)\n {\n this.manager = manager;\n }\n\n protected override void InsertItem(int index, object item)\n {\n base.InsertItem(index, item);\n manager.OnItemAddedToList(item);\n }\n\n protected override void SetItem(int index, object item)\n {\n object oldItem = (index < base.Count) ? base[index] : null;\n base.SetItem(index, item);\n\n if (oldItem != null) {\n manager.OnItemRemovedFromList(oldItem);\n }\n\n manager.OnItemAddedToList(item);\n }\n\n protected override void RemoveItem(int index, object item)\n {\n base.RemoveItem(index, item);\n manager.OnItemRemovedFromList(item);\n }\n }\n\n private OnItemAddedToList(object o) \n {\n }\n\n private OnItemRemovedFromList(object o) \n {\n }\n}\n"
},
{
"answer_id": 371185,
"author": "Neil Barnwell",
"author_id": 26414,
"author_profile": "https://Stackoverflow.com/users/26414",
"pm_score": 0,
"selected": false,
"text": "IList<T> Added Removed Replaced List<T> OnBefore... OnAfter DataTable DataRow OnChanged ItemChanged"
},
{
"answer_id": 371186,
"author": "Davermouse",
"author_id": 46401,
"author_profile": "https://Stackoverflow.com/users/46401",
"pm_score": 2,
"selected": false,
"text": "System.Collections.ObjectModel.ObservableCollection<T>"
},
{
"answer_id": 371189,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 3,
"selected": false,
"text": "INotifyCollectionChanged INotifyPropertyChanged ObservableCollection<T> INotifyCollectionChanged ObservableCollection<T> IBindingList INotifyCollectionChanged"
},
{
"answer_id": 371330,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "BindingList<T> ObservableCollection<T> Collection<T> List<T>"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27667/"
] |
371,140 | <p>I'm using WinRAR SFX module to create an installation, and use its presetup option to run some preliminary tests.</p>
<p>Since wscript can only accept vbs file, and not the script itself, I first run "cmd /c echo {...script code...} > setup.vbs", and then I run "wscript setup.vbs". The run of the first cmd command opens a brief command window, and I would really like to avoid this. I thought of using RunDll32 to write this data, but couldn't find any suitable API to use.</p>
<p>Can anyone think of a way to bypass it and create a small file with a small VBScript text without opening a Command Prompt window?</p>
<p>Thanks a lot,</p>
<p>splintor</p>
| [
{
"answer_id": 371198,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 2,
"selected": false,
"text": "TYPE [script_file] > setup.vbs\n COPY [script_file] setup.vbs\n cmd START cmd /b START /B cmd /c echo {...script code...} > setup.vbs\n"
},
{
"answer_id": 393433,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 1,
"selected": false,
"text": "cmd /c echo {...script code...} > setup.vbs setup.vbs setup.vbs Set WSHShell = CreateObject(\"WScript.Shell\") \nWSHShell.Run \"wscript d:\\setup.vbs, ,True\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] |
371,147 | <p>So I've got a form in my Rails app which uses a custom FormBuilder to give me some custom field tags</p>
<pre><code><% form_for :staff_member, @staff_member, :builder => MyFormBuilder do |f| %>
[...]
<%= render :partial => "staff_members/forms/personal_details", :locals => {:f => f, :skill_groups => @skill_groups, :staff_member => @staff_member} %>
[...]
<% end %>
</code></pre>
<p>Now, this partial is in an area of the form which gets replaces by an AJAX callback. What I end up doing from the controller in response to the AJAX request is:</p>
<pre><code>render :partial => "staff_members/forms/personal_details", :locals => {:skill_groups => @skill_groups, :staff_member => @staff_member}
</code></pre>
<p>However, if I do that then the form breaks, as the FormBuilder object I used in the form_for is no longer available. Is there any way for me to use my custom FormBuilder object inside a partial used for an AJAX callback?</p>
| [
{
"answer_id": 405444,
"author": "nakajima",
"author_id": 39589,
"author_profile": "https://Stackoverflow.com/users/39589",
"pm_score": 1,
"selected": false,
"text": "# in the controller\nrender :partial => {\n :f => MyFormBuilder.new(:staff_member, @staff_member, template),\n :skill_groups => @skill_groups,\n :staff_member => @staff_member\n}\n"
},
{
"answer_id": 406697,
"author": "Edd",
"author_id": 50873,
"author_profile": "https://Stackoverflow.com/users/50873",
"pm_score": 5,
"selected": true,
"text": "fields_for"
},
{
"answer_id": 3964095,
"author": "David Lowenfels",
"author_id": 315970,
"author_profile": "https://Stackoverflow.com/users/315970",
"pm_score": 2,
"selected": false,
"text": " @template.with_output_buffer do\n @template.form_for @model_object do |f|\n f.fields_for :some_nested_attributes do |ff|\n render :partial => 'nested_attributes', :object => @model_object, :locals => {:form => ff}\n end\n end\n end\n"
},
{
"answer_id": 3998007,
"author": "Samo",
"author_id": 484342,
"author_profile": "https://Stackoverflow.com/users/484342",
"pm_score": 1,
"selected": false,
"text": "ActionView::Base.default_form_builder = MyFormBuilder\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31582/"
] |
371,153 | <p>I am using the program below to sort and eventually print out email messages. Some messages may contain attachments or HTML code, which would not be good for printing. Is there an easy way to strip attachments and strip HTML but not the text formatted by HTML from the messages?</p>
<pre><code>#!/usr/bin/perl
use warnings;
use strict;
use Mail::Box::Manager;
open (MYFILE, '>>data.txt');
binmode(MYFILE, ':encoding(UTF-8)');
my $file = shift || $ENV{MAIL};
my $mgr = Mail::Box::Manager->new(
access => 'r',
);
my $folder = $mgr->open( folder => $file )
or die "$file: Unable to open: $!\n";
for my $msg ( sort { $a->timestamp <=> $b->timestamp } $folder->messages)
{
my $to = join( ', ', map { $_->format } $msg->to );
my $from = join( ', ', map { $_->format } $msg->from );
my $date = localtime( $msg->timestamp );
my $subject = $msg->subject;
my $body = $msg->decoded->string;
# Strip all quoted text
$body =~ s/^>.*$//msg;
print MYFILE <<"";
From: $from
To: $to
Date: $date
Subject: $subject
\n
$body
}
</code></pre>
| [
{
"answer_id": 371179,
"author": "Nietzche-jou",
"author_id": 39892,
"author_profile": "https://Stackoverflow.com/users/39892",
"pm_score": 1,
"selected": false,
"text": "perldoc -q html"
},
{
"answer_id": 371192,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 3,
"selected": true,
"text": "Mail::Message::isMultipart Mail::Message::parts if ( $msg->isMultipart ) {\n foreach my $part ( $msg->parts ) {\n if ( $part->contentType eq 'text/html' ) {\n # deal with html here.\n }\n elsif ( $part->contentType eq 'text/plain' ) {\n # deal with text here.\n }\n else {\n # well?\n }\n }\n}\n"
},
{
"answer_id": 371205,
"author": "Colin Pickard",
"author_id": 12744,
"author_profile": "https://Stackoverflow.com/users/12744",
"pm_score": 0,
"selected": false,
"text": " # This is part of Mail::POP3Client to get the headers and body of the POP3 mail in question\n $body = $connection->HeadAndBody($i);\n # Parse the message with MIME::Parser, declare the body as an entitty\n $msg = $parser->parse_data($body);\n # Find out if this is a multipart MIME message or just a plaintext\n $num_parts=$msg->parts;\n # So its its got 0 parts i.e. is a plaintext\n if ($num_parts eq 0) {\n # Get the message by POP3Client\n $message = $connection->Body($i);\n # Use this series of regular expressions to verify that its ok for MySQL\n $message =~ s/</</g;\n $message =~ s/>/>/g;\n $message =~ s/'//g;\n }\n else {\n # If it is MIME the parse the first part (the plaintext) into a string\n $message = $msg->parts(0)->bodyhandle->as_string;\n }\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
371,155 | <p>I'm using Python 2.5. The DLL I imported is created using the CLR. The DLL function is returning a string. I'm trying to apply "partition" attribute to it. I'm not able to do it. Even the partition is not working. I think "all strings returned from CLR are returned as Unicode".</p>
| [
{
"answer_id": 371200,
"author": "sastanin",
"author_id": 25450,
"author_profile": "https://Stackoverflow.com/users/25450",
"pm_score": 3,
"selected": true,
"text": "type(yourvar) partition(sep) dir(yourvar) partition >>> us=u\"Привет, Unicode String!\"\n>>> us.partition(' ')\n(u'\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442,', u' ', u'Unicode String!')\n split partition >>> from string import split\n>>> split(us,' ',1)\n[u'\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442,', u'Unicode String!']\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46646/"
] |
371,174 | <p>I often find linq being problematic when working with custom collection object.
They are often defened as</p>
<p>The base collection</p>
<pre><code>abstract class BaseCollection<T> : List<T> { ... }
</code></pre>
<p>the collections is defined as</p>
<pre><code>class PruductCollection : BaseCollection<Product> { ... }
</code></pre>
<p>Is there a better way to add results from a linq expession to this collection than
addrange or concat?</p>
<pre><code>var products = from p in HugeProductCollection
where p.Vendor = currentVendor
select p;
PruductCollection objVendorProducts = new PruductCollection();
objVendorProducts.AddRange(products);
</code></pre>
<p>It would be nice if the object returned form the linq query was of my custom collection type. As you seem to need to enumerate the collection two times to do this.</p>
<p><strong>EDIT</strong> :
After reading the answers i think the best solution is to implementa a ToProduct() extention.
Wonder if the covariance/contravariance in c#4.0 will help solve these kinds of problems.</p>
| [
{
"answer_id": 371221,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "IEnumerable<T> IEnumerable<T> public static class MyExtensions\n{\n public static ProductCollection\n ToProducts( this IEnumerable<Product> collection )\n {\n return new ProductCollection( collection );\n }\n}\n\n\npublic class ProductCollection : BaseCollection<Product>\n{\n ...\n\n public ProductCollection( IEnumerable<Product> collection )\n : base( collection )\n {\n }\n\n ...\n }\n\n\nvar products = (from p in HugeProductCollection\n where p.Vendor = currentVendor\n select p).ToProducts();\n"
},
{
"answer_id": 371223,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "abstract class BaseCollection<T> : List<T>\n{\n public BaseCollection(IEnumerable<T> collection)\n : base(collection)\n {\n }\n}\n\nclass PruductCollection : BaseCollection<Product>\n{\n public PruductCollection(IEnumerable<Product> collection)\n : base(collection)\n {\n }\n}\n\nvar products = from p in HugeProductCollection\n where p.Vendor = currentVendor\n select p;\nPruductCollection objVendorProducts = new PruductCollection(products);\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24821/"
] |
371,181 | <p>WSPBuilder</p>
<p>Version: 0.9.8.0830
Created by Carsten Keutmann
GPL License 2007</p>
<p>Install and deploying [MYDLL]
Unable to deploy solution
Inner exception(1): This solution contains one or more assemblies targeted for the global assembly cache. You should use a strong name for any assembly that will be in the global assembly cache.</p>
| [
{
"answer_id": 371215,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 1,
"selected": false,
"text": "Delay sign only"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41291/"
] |
371,183 | <p>I'm developing an HTML newsletter system using PHP & PEAR. It sends out the emails fine.</p>
<p>However I cannot force Apple Mail to reload images from the server. I have tried:</p>
<ul>
<li>Restarting Mail</li>
<li>Clear ~/Library/MailDownloads </li>
<li>Clear ~/Library/Cache/Mail</li>
<li>Empty Safari cache</li>
</ul>
<p>Does any one know where Apple Mail caches the images ?</p>
| [
{
"answer_id": 485467,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 2,
"selected": false,
"text": "<img src=\"http://example.com/images/hello.png?343882881923\"/>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2725/"
] |
371,203 | <p>Can you recommend any tool to migrate sources (with history) from TFS to SVN?</p>
| [
{
"answer_id": 7591528,
"author": "Benjamin",
"author_id": 186606,
"author_profile": "https://Stackoverflow.com/users/186606",
"pm_score": 1,
"selected": false,
"text": "public Tfs2SvnConverter(string tfsPath, string svnPath, bool createSvnFileRepository, int fromChangeset, string workingCopyPath, string svnBinFolder, bool doInitialCheckout, string tfsUsername, string tfsPassword, string tfsDomain)\n {\n ParsePaths(tfsPath, svnPath);\n this._tfsServer = \"http://<tfs domain>:8080/tfs/<team project collection name>\";\n this._tfsRepository = \"<remote source location>\"; // \"$/<team project name>/...\"\n //this._tfsExporter = new TfsExporter(this._tfsServer, this._tfsRepository, workingCopyPath, fromChangeset, tfsUsername, tfsPassword, tfsDomain);\n TfsClient.Provider.Connect(this._tfsServer, this._tfsRepository, workingCopyPath, fromChangeset, tfsUsername, tfsPassword, tfsDomain);\n\n this._svnImporter = new SvnImporter(this._svnRepository, workingCopyPath, svnBinFolder);\n _createSvnFileRepository = createSvnFileRepository;\n _doInitialCheckout = doInitialCheckout;\n _workingCopyPath = workingCopyPath;\n\n HookupTfsExporterEventHandlers();\n }\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,204 | <p>I am writing a managed custom action. I am using the DTF Framework from Windows Installer Xml to wrap the managed dll into a usable CA dll. The CA does what it is supposed to, but I am still having trouble with error handling:</p>
<pre><code>Dim record As New Record(1)
' Field 0 intentionally left blank
' Field 1 contains error number
record(1) = 27533
session.Message(InstallMessage.Error, record)
</code></pre>
<p>The above code produces the following text shown in the MSI log:</p>
<blockquote>
<p>MSI (c) (C4 ! C6) [13:15:08:749]: Product: TestMSI -- Error 27533. The case-sensitive passwords do not match.</p>
</blockquote>
<p>The error number refers to the code contained in the Error table within the MSI. The Message shown above is correct.</p>
<p>My problem is: Why does Windows Installer NOT create a dialog notifying the user about the error?</p>
| [
{
"answer_id": 654840,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": " private void _handleSqlException(SqlException ex)\n {\n StringBuilder errorMessage = new StringBuilder();\n errorMessage.Append(\"A SQL error has occurred.\");\n for (int i = 0; i < ex.Errors.Count; i++)\n {\n errorMessage.Append(\"Index #\" + i + \"\\n\" +\n \"Message: \" + ex.Errors[i].Message + \"\\n\" +\n \"LineNumber: \" + ex.Errors[i].LineNumber + \"\\n\" +\n \"Source: \" + ex.Errors[i].Source + \"\\n\" +\n \"Procedure: \" + ex.Errors[i].Procedure + \"\\n\");\n }\n session.Log(errorMessage);\n if (session[\"UILevel\"] == \"5\")\n {\n MessageBox.Show(errorMessage);\n }\n }\n"
},
{
"answer_id": 780320,
"author": "David Gardiner",
"author_id": 25702,
"author_profile": "https://Stackoverflow.com/users/25702",
"pm_score": 4,
"selected": false,
"text": "Record record = new Record();\nrecord.FormatString = string.Format(\"Something has gone wrong!\");\n\nsession.Message(\n InstallMessage.Error | (InstallMessage) ( MessageBoxIcon.Error ) |\n (InstallMessage) MessageBoxButtons.OK,\n record );\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23369/"
] |
371,209 | <p>How can I blur a whole page using CSS?
Other elements such as images are allowed.</p>
| [
{
"answer_id": 371257,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 4,
"selected": false,
"text": "/* DIV-element with black background and 50% opacity set */\ndiv.overlay {\n position: absolute;\n width: 100%;\n top: 0;\n left: 0;\n background: #000;\n opacity: 0.5;\n filter: alpha(opacity = 50); /* required for opacity to work in IE */\n}\n"
},
{
"answer_id": 7734235,
"author": "Mike Burroughs",
"author_id": 990551,
"author_profile": "https://Stackoverflow.com/users/990551",
"pm_score": -1,
"selected": false,
"text": "<script type=\"text/javascript\">\n$(function(){\n $('.modal') .css({'height': (($(window).height()))});\n});\n$(window).resize(function(){\n $('.modal') .css({'height': (($(window).height()))});\n});\n</script>\n"
},
{
"answer_id": 7967261,
"author": "Joseph Lust",
"author_id": 564157,
"author_profile": "https://Stackoverflow.com/users/564157",
"pm_score": 2,
"selected": false,
"text": "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:svg=\"http://www.w3.org/2000/svg\">\n <div class=\"blurDiv\"></div>\n<svg:svg>\n <!-- Filter -->\n <svg:filter id=\"blurLayer\">\n <!-- Blur and attributes -->\n <svg:feGaussianBlur stdDeviation=\"0.9\"/>\n </svg:filter>\n</svg:svg>\n <style type=\"text/css\">\n div.blurDiv { filter:url(#blurLayer); }\n</style>\n"
},
{
"answer_id": 9041290,
"author": "coops",
"author_id": 1174557,
"author_profile": "https://Stackoverflow.com/users/1174557",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<title>Blur</title>\n<style type=\"text/css\">\n#f0,#f1,#f2{position:absolute;left:0px;top:0px;height:95%}\n#f0{filter:alpha(opacity=50);opacity: 0.15;-moz-opacity:0.15;z-index:15}\n#f1{filter:alpha(opacity=25);opacity: 0.25;-moz-opacity:0.25;z-index:2}\n#f2{filter:alpha(opacity=75);opacity: 0.75;-moz-opacity:0.75;}\n.fin{margin-right:auto;margin-left:auto}\nbody{display:none}\n</style>\n<script type=\"text/javascript\">\nvar winX=window.innerWidth-20;\nvar winY=screen.availHeight-10;\nvar count=0;\nvar maxCount=50;\nvar goBlur=true;\n\nfunction ele(id) {\n return document.getElementById(id);\n}\nfunction runBlur() {\n if(goBlur) {\n for(var i=0; i<2; i++) {\n var x = Math.random()<0.5?-1:1;\n var y = Math.random()<0.5?1:-1;\n if(ele(\"f\"+i).offsetLeft >3)\n x=-1;\n else if(ele(\"f\"+i).offsetLeft<-3)\n x=1;\n if(ele(\"f\"+i).offsetLeft >3)\n y=-1;\n else if(ele(\"f\"+i).offsetLeft<-3)\n y=1;\n\n ele(\"f\"+i).style.left = (ele(\"f\"+i).offsetLeft + x)+\"px\";\n ele(\"f\"+i).style.top = (ele(\"f\"+i).offsetTop + x)+\"px\";\n }\n }\n count++\n if(count>maxCount) {\n count=0;\n if(goBlur)\n goBlur=false;\n else\n goBlur=true;\n for(var i=0; i<3; i++) {\n ele(\"f\"+i).style.left = \"0px\";\n ele(\"f\"+i).style.top = \"0px\";\n }\n }\n setTimeout(\"runBlur()\",200);\n}\n\nfunction pageLoaded() {\n var content = document.body.innerHTML;\n var rewriteBody=\"\";\n for(var i=0; i<3; i++) {\n rewriteBody+='<div id=\"f'+i+'\"><div class=\"fin\">'+content+'</div></div>';\n }\n document.body.innerHTML=rewriteBody;\n setTimeout(\"setUp()\",200);\n}\nfunction setUp() {\n\n for(var i=0; i<3; i++) {\n ele(\"f\"+i).style.width=winX+\"px\";\n }\n\n document.body.style.display=\"block\";\n runBlur();\n}\n</script>\n </head>\n <body onload=\"pageLoaded()\">\n<h1 style=\"color:#900\">Page blur example</h1>\nYou can put any page content and html you want here.\n </body>\n</html>\n"
},
{
"answer_id": 12025098,
"author": "tobspr",
"author_id": 1608816,
"author_profile": "https://Stackoverflow.com/users/1608816",
"pm_score": 5,
"selected": false,
"text": "filter: blur(radius) .blurredElement {\n\n /* Any browser which supports CSS3 */\n filter: blur(1px);\n\n /* Firefox version 34 and earlier */\n filter: url(\"blur.svg#gaussian_blur\");\n\n /* Webkit in Chrome 52, Safari 9, Opera 39, and earlier */\n -webkit-filter: blur(1px);\n}\n <?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n <defs>\n <filter id=\"gaussian_blur\">\n <feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"1\" />\n </filter>\n </defs>\n</svg>\n"
},
{
"answer_id": 13095373,
"author": "pimvdb",
"author_id": 514749,
"author_profile": "https://Stackoverflow.com/users/514749",
"pm_score": 4,
"selected": false,
"text": "filter blur body {\n filter: blur(2px);\n}\n"
},
{
"answer_id": 14589319,
"author": "Jason Hibbs",
"author_id": 1453627,
"author_profile": "https://Stackoverflow.com/users/1453627",
"pm_score": 3,
"selected": false,
"text": "thickbox-open .thickbox-open #main-container {\n -webkit-filter: blur(2px);\n -moz-filter: blur(2px);\n -ms-filter: blur(2px);\n -o-filter: blur(2px);\n filter: blur(2px); \n}\n body"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,227 | <p>Is there anyway to change the ASPNETDB and also using SQLExpress (2005) user instance ?</p>
<p>I have changed my web.config's connectin string to </p>
<pre><code><remove name="LocalSqlServer"/>
<add name="LocalSqlServer"
connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Kooft.mdf;
User Instance=true;
Integrated Security=True;
Initial Catalog=Kooft;"
providerName="System.Data.SqlClient" />
</code></pre>
<p>but every time I using ASP.Net Configuration Tool, it will create another ASPNETDB.mdf file in my App_Data folder.</p>
| [
{
"answer_id": 371294,
"author": "Zhaph - Ben Duguid",
"author_id": 33051,
"author_profile": "https://Stackoverflow.com/users/33051",
"pm_score": 2,
"selected": false,
"text": "C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regsql.exe\n <connectionStrings>\n <remove name=\"LocalSqlServer\"/>\n <add name=\"LocalSqlServer\" \n connectionString=\"Data Source=[ComputerName]\\SQLEXPRESS;Initial Catalog=[DatabaseName];Integrated Security=True\" \n providerName=\"System.Data.SqlClient\"/>\n </connectionStrings>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,237 | <p>In F#, you can generate a set of numbers, just by saying [1..100].</p>
<p>I want to do something similar in C#. This is what I have come up with so far:</p>
<pre><code>public static int[] To(this int start, int end)
{
var result = new List<int>();
for(int i = start; i <= end; i++)
result.Add(i);
return result.ToArray();
}
</code></pre>
<p>By doing this, I can now create a set by saying 1.To(100)</p>
<p>Unfortunately, this is not nearly as readable as [1..100]. Has anyone come up with a better way to do this in C#? Is it more readable if it is lowercase? 1.to(100), for instance? Or, is "To" a bad word? Is something like 1.Through(100) more readable?</p>
<p>Just looking for some thoughts. Has anyone else come up with a more elegant solution?</p>
<p><strong>EDIT:</strong>
After reading the responses, I have re-written my To method using the range:</p>
<pre><code>public static int[] To(this int start, int end)
{
return Enumerable.Range(start, end - start + 1).ToArray();
}
</code></pre>
<p>I am still looking for thoughts on the readability of 1.To(100)</p>
| [
{
"answer_id": 371251,
"author": "lc.",
"author_id": 44853,
"author_profile": "https://Stackoverflow.com/users/44853",
"pm_score": 0,
"selected": false,
"text": "Set(1,100) IntSequence(1,100)"
},
{
"answer_id": 371273,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 3,
"selected": false,
"text": "To Enumerable.Range public IEnumerable<int> To(this int start, int stop)\n{\n while (start <= stop)\n yield return start++;\n}\n int[] .ToArray() int[] theSet = 1.To(100).ToArray();\n"
},
{
"answer_id": 371845,
"author": "Brian Rudolph",
"author_id": 33114,
"author_profile": "https://Stackoverflow.com/users/33114",
"pm_score": 0,
"selected": false,
"text": "public static int[] To(this int num)\n {\n //do work\n }\n"
},
{
"answer_id": 371970,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 0,
"selected": false,
"text": "public class RangedArray {\n public static int[] Generate(int from, into to, int by=1) { /* ... */ }\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36687/"
] |
371,246 | <p>I have a very simple Update statement that will update mail server settings and network credentials info... Query works fine when I run it in Access but C# keeps giving me the error stating that my SQL Syntax is wrong ... I have a dataaccess layer (dal class) and Update instance method pasted belows ... But the problem must be sth else cuz I have updated lots of stuff this way but this time it just won't do .. any clues will be greatly appreciated. Thx in advance.</p>
<p>Update instance method in DAL class .. (this is supposed to be a Data Access Layer :) I'm just a management graduate :P</p>
<pre><code>public int UpdateRow(string Query, bool isSP, params OleDbParameter[] args)
{
int affectedRows = -1;
using (con = new OleDbConnection(connStr))
{
using (cmd = con.CreateCommand())
{
cmd.CommandText = Query;
if (isSP)
{
cmd.CommandType = CommandType.StoredProcedure;
}
if (args != null)
{
foreach (OleDbParameter prm in args)
{
cmd.Parameters.Add(prm);
}
}
try
{
con.Open();
affectedRows = cmd.ExecuteNonQuery();
}
catch(OleDbException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
}
return affectedRows;
}
</code></pre>
<p>And the ASP.NEt codebehind that will do the updating =</p>
<pre><code>protected void Update_Click(object sender, EventArgs e) {
DAL dal = new DAL();
string upt = string.Format("UPDATE [MailConfig] SET Server='{0}', Username='{1}', Password='{2}', AddressFrom='{3}', DisplayName='{4}'",server.Text,username.Text,password.Text,replyto.Text,displayname.Text);
dal.UpdateRow(upt,false,null);
LoadData();
}
</code></pre>
<p>peace!</p>
| [
{
"answer_id": 371258,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "string.Format"
},
{
"answer_id": 371281,
"author": "Tony Peterson",
"author_id": 26140,
"author_profile": "https://Stackoverflow.com/users/26140",
"pm_score": 0,
"selected": false,
"text": "UPDATE [MailConfig] \nSET Server='{0}', \n Username='{1}', \n Password='{2}', \n AddressFrom='{3}', \n DisplayName='{4}'\"\n string sqlCommString = \"QCApp.dbo.ColumnSeek\";\nSqlCommand metaDataComm = new SqlCommand(sqlCommString, sqlConn);\nmetaDataComm.CommandType = CommandType.StoredProcedure;\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,266 | <p>I've found this piece of code on <a href="http://www.koders.com/csharp/fidACD7502AA845419FF59B7DA804D3C8FCA0E40138.aspx?s=basecodegeneratorwithsite#L76" rel="nofollow noreferrer">Koders</a>:</p>
<pre><code>private ServiceProvider SiteServiceProvider
{
get
{
if (serviceProvider == null)
{
serviceProvider = new ServiceProvider(site as VSOLE.IServiceProvider);
Debug.Assert(serviceProvider != null, "Unable to get ServiceProvider from site object.");
}
return serviceProvider;
}
}
</code></pre>
<p>I'm wondering, is there <em>any</em> possible way the <code>Debug.Assert(serviceProvider != null</code> could trigger? I'm under the impression that <code>new</code> could only be aborted by an exception, in which case the assert would never be reached.</p>
| [
{
"answer_id": 371310,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "SomeType provider = SomeFactory.CreateProvider();\nif(provider == null) // damn!! no factory implementation loaded...\n{ etc }\n Nullable<T> static void Test<T>() where T : new()\n{\n T x = new T();\n if (x == null) Console.WriteLine(\"wtf?\");\n}\nstatic void Main()\n{\n Test<int?>();\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
371,268 | <p>using the Code Snippet for sending email in VB.Net I have successfully sent an email from my local machine, but when I Upload it to my server I get a message that the email failed. We have a national relay server that is running SMTP and I am pointed at that server in both instances. The only differance that jump out at me between the two machines is that the server is not running SMTP. Do I need SMTP to be running on the server if I am using a relay server to send the email that is running SMTP?</p>
<pre><code> Dim message As New MailMessage("DoNotReply@faa.gov", My.Settings.NotifyList, "Starting FalconCMSOffloader @ " & My.Settings.FacID & " - " & Now, "NM")
Dim emailClient As New SmtpClient(My.Settings.EmailServerAddress)
emailClient.Send(message)
</code></pre>
| [
{
"answer_id": 371309,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 3,
"selected": true,
"text": "telnet RelayServerAddress 25\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38349/"
] |
371,272 | <p>Rails introduced some core extensions to Ruby like <code>3.days.from_now</code> which returns, as you'd expect a date three days in the future. With extension methods in C# we can now do something similar:</p>
<pre><code>static class Extensions
{
public static TimeSpan Days(this int i)
{
return new TimeSpan(i, 0, 0, 0, 0);
}
public static DateTime FromNow(this TimeSpan ts)
{
return DateTime.Now.Add(ts);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(
3.Days().FromNow()
);
}
}
</code></pre>
<p>Or how about:</p>
<pre><code>static class Extensions
{
public static IEnumerable<int> To(this int from, int to)
{
return Enumerable.Range(from, to - from + 1);
}
}
class Program
{
static void Main(string[] args)
{
foreach (var i in 10.To(20))
{
Console.WriteLine(i);
}
}
}
</code></pre>
<p>Is this fundamentally wrong, or are there times when it is a good idea, like in a framework like Rails?</p>
| [
{
"answer_id": 371291,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 3,
"selected": false,
"text": "TimeSpan.FromSeconds(4).FromNow()\n"
},
{
"answer_id": 371360,
"author": "Andrew Hare",
"author_id": 34211,
"author_profile": "https://Stackoverflow.com/users/34211",
"pm_score": 4,
"selected": true,
"text": "3.Days().FromNow()"
},
{
"answer_id": 371415,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 3,
"selected": false,
"text": "3.Minutes.from_now 3.Minutes 3.Minutes"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27782/"
] |
371,279 | <p>I've got the following Linq2Sql and it's doing more than one round trip for my 'SELECT' statement. I'm not sure why. First the code, then the explanation:-</p>
<pre><code>from p in db.Questions
select new Models.Question
{
Title = p.Title,
TagList = (from t in p.QuestionTags
select t.Tag.Name).ToList()
}
</code></pre>
<p>Now the database is</p>
<blockquote>
<p><em>Questions <-one to many-> QuestionTags <-many to one->Tag</em></p>
</blockquote>
<p>so one question has one to many Tags, with a link table in the middle. This way, i can reuse tags multiple times. (I'm open to a better schema if there's one).</p>
<p>Doing this does the following Sql code generated by Linq2Sql</p>
<pre><code>SELECT [t0].[QuestionId] AS [ID], etc.... <-- that's the good one
</code></pre>
<p>.</p>
<pre><code>exec sp_executesql N'SELECT [t1].[Name]
FROM [dbo].[QuestionTags] AS [t0]
INNER JOIN [dbo].[Tags] AS [t1] ON [t1].[TagId] = [t0].[TagId]
WHERE [t0].[QuestionId] = @x1',N'@x1 int',@x1=1
</code></pre>
<p>The second sql block is listed 2x .. i think that's because the first sql block returns TWO results, so the second one is fired for each result from the first.</p>
<p>Is there any way i can make this one sql statement instead of 1 + n, where n = the number of results from the first query?</p>
<h2>Update:</h2>
<p>I've tried both Eager and Lazy loading and there's no difference. </p>
<pre><code>DataLoadOptions dataLoadOptions = new DataLoadOptions();
dataLoadOptions.LoadWith<Question>(x => x.QuestionTags);
dataLoadOptions.LoadWith<QuestionTag>(x => x.Tag);
db.LoadOptions = dataLoadOptions;
</code></pre>
| [
{
"answer_id": 371297,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "DECLARE @foo varchar(max)\nSET @foo = ''\nSELECT @foo = @foo + [SomeColumn] + ',' -- CSV\nFROM [SomeTable]\nWHERE -- some condition\n @foo"
},
{
"answer_id": 371888,
"author": "Anderson Imes",
"author_id": 3244,
"author_profile": "https://Stackoverflow.com/users/3244",
"pm_score": 3,
"selected": false,
"text": "from p in db.Questions\nlet Tags = (from t in p.QuestionTags\n select t.Tag.Name)\nselect new Models.Question\n{\n Title = p.Title,\n TagList = Tags\n}\n"
},
{
"answer_id": 372263,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " var dlo = new DataLoadOptions();\n // Configure eager loading\n dlo.LoadWith<Question>(q => q.QuestionTags);\n\n _context = new WhateverContext();\n _context.LoadOptions = dlo;\n"
},
{
"answer_id": 2178143,
"author": "Jeremy Seekamp",
"author_id": 108933,
"author_profile": "https://Stackoverflow.com/users/108933",
"pm_score": 0,
"selected": false,
"text": "from p in db.Questions\nlet Tags = GetTags(Questions.Id)\nselect new Models.Question\n{\n Title = p.Title,\n TagList = LazyList<string>(Tags)\n}\n\npublic IQueryable<string> GetTags(int questionId) {\n from qt in db.QuestionTags\n join t in db.Tags on qt.TagId equals t.Id\n where qt.questionId = questionId\n select t.Name\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
371,300 | <p>In my domain model I have an abstract class CommunicationChannelSpecification, which has child classes like FTPChannelSpecification, EMailChannelSpecification and WebserviceChannelSpecification. Now I want to create an HQL query which contains a where clause that narrows down the result to certain types of channel specifications. E.g. (in plain English) select all CommunicationChannelSpecifications that whose types occur in the set {FTPChannelSpecification, WebserviceChannelSpecification}.</p>
<p>How can this be achieved in HQL? I'm using NHibernate 2.0.1 and a table per subclass inheritance mapping strategy...</p>
<p>Thanks!</p>
<p>Pascal</p>
| [
{
"answer_id": 371343,
"author": "bangroot",
"author_id": 45693,
"author_profile": "https://Stackoverflow.com/users/45693",
"pm_score": 4,
"selected": true,
"text": "from CommunicationChannelSpecifications spec where spec.class in (?)\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/414376/"
] |
371,302 | <p>I would like to implement a post build event that performs the following actions</p>
<ol>
<li>A relative path copy of the DLL output (1 file, not all the debug jazz)</li>
<li>A register the output DLL to GAC</li>
</ol>
<p>How is this done?</p>
| [
{
"answer_id": 371332,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 5,
"selected": true,
"text": "copy $(TargetPath) $(TargetDir)..\\..\\someFolder\\myoutput.dll\nregasm $(TargetPath) \n"
},
{
"answer_id": 371387,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "xcopy \"$(TargetPath)\" \"target path\" /Y && regasm \"$(TargetPath)\"\n <PropertyGroup>\n <PostBuildEvent>xcopy \"$(TargetPath)\" \"target path\" /Y && regasm \"$(TargetPath)\"</PostBuildEvent>\n</PropertyGroup>\n"
},
{
"answer_id": 6044106,
"author": "Valentino Vranken",
"author_id": 316194,
"author_profile": "https://Stackoverflow.com/users/316194",
"pm_score": 1,
"selected": false,
"text": "\"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\bin\\gacutil\" /f /i $(TargetPath)\n"
},
{
"answer_id": 10159151,
"author": "ForceMagic",
"author_id": 62921,
"author_profile": "https://Stackoverflow.com/users/62921",
"pm_score": 2,
"selected": false,
"text": "copy \"$(SolutionDir)SDL\\lib\\x86\\SDL.dll\" \"$(SolutionDir)$(Configuration)\\\"\n $(Configuration) \\"
},
{
"answer_id": 10655783,
"author": "John Spiegel",
"author_id": 612084,
"author_profile": "https://Stackoverflow.com/users/612084",
"pm_score": 0,
"selected": false,
"text": "delete $(SolutionDir)FileService\\$(ProjectName).dll\ncopy $(TargetPath) $(SolutionDir)FileService\\$(ProjectName).dll\n"
},
{
"answer_id": 73141054,
"author": "Tono Nam",
"author_id": 637142,
"author_profile": "https://Stackoverflow.com/users/637142",
"pm_score": 0,
"selected": false,
"text": "\n<Project>\n ...\n <!-- Upload to virtual machine -->\n <Target Name=\"rsync\" AfterTargets=\"Build\">\n <Exec Command=\"C:\\Windows\\System32\\wsl.exe rsync -azv -e 'ssh -i /path/to/my/private/key' --delete /mnt/c/repos/MyProject/bin/Debug/net7.0/ root@vm.ublux.com:/usr/share/foo/\" />\n </Target>\n</Project>\n\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41291/"
] |
371,320 | <p>I have a YouTube's player in the webpage. I need to change the video played by this player dynamicaly.</p>
<p>This is (relatively) easy using YouTube's chromeless player. It has method <a href="http://code.google.com/apis/youtube/chromeless_player_reference.html#loadVideoById" rel="noreferrer"><code>loadVideoById()</code></a> which works perfectly. The problem is, that the chromeless player doesn't have any controls (play/pause, etc.). The <a href="http://code.google.com/apis/youtube/js_api_reference.html#Functions" rel="noreferrer">regular YouTube player</a> has all this, but it doesn't have the <code>loadVideoById()</code> method.</p>
<p>Is there any way to include the controls of regular player into chromeless player, or to implement <code>loadVideoById()</code> method in the regular player?</p>
<p>Thanks.</p>
| [
{
"answer_id": 5130725,
"author": "asper",
"author_id": 636047,
"author_profile": "https://Stackoverflow.com/users/636047",
"pm_score": 1,
"selected": false,
"text": " * The mediaContentUrl must be a fully qualified YouTube player URL in the format http://www.youtube.com/e/VIDEO_ID. In YouTube Data API video feeds, the url attribute of the <media:content> tag contains a fully qualified player URL when the tag's format attribute has a value of 5.\n * startSeconds accepts a float/integer and specifies the time from which the video should start playing. If startSeconds (number can be a float) is specified, the video will start from the closest keyframe to the specified time.\"\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22920/"
] |
371,322 | <p>I have to read invoice ascii files that are structured in a really convoluted way, for example:</p>
<pre><code>55651108 3090617.10.0806:46:32101639Example Company Construction Company Example Road. 9 9524 Example City
</code></pre>
<p>There's actually additional stuff in there, but I don't want to confuse you any further.</p>
<p>I know I'm doomed if the client can't offer a better structure. For instance 30906 is an iterative number that grows. 101639 is the CustomerId. The whitespaces between "Example Company" and "Construction Company" are of variable length The field "Example Company" could have whitespaces of variable length too however, for instance "Microsoft Corporation Redmond". Same with the other fields. So there's no clear way to extract data from the latter part.</p>
<p>But that's not the question. I got taken away. My question is as follows:</p>
<p>If the input was somewhat structured and well defined, how would you guard against future changes in its structure. How would you design and implement a reader. </p>
<p>I was thinking of using a simple EAV Model in my DB, and use text or xml templates that describe the input, the entity names, and their valuetypes. I would parse the invoice files according to the templates.</p>
| [
{
"answer_id": 371344,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 0,
"selected": false,
"text": "unpack $ perl -MData::Dumper -e 'print Dumper(unpack(\"A8 x A5 A8 A8 A6 A30 A30\", \"55651108 3090617.10.0806:46:32101639Example Company Construction Company Example Road. 9 9524 Example City\"))'\n$VAR1 = '55651108';\n$VAR2 = '30906';\n$VAR3 = '17.10.08';\n$VAR4 = '06:46:32';\n$VAR5 = '101639';\n$VAR6 = 'Example Company';\n$VAR7 = 'Construction Company';\n"
},
{
"answer_id": 371383,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": true,
"text": "class Field( object ):\n def __init__( self, name, size ):\n self.name= name\n self.size = size\n self.offset= None\n\nclass Record( object ):\n def __init__( self, fieldList ):\n self.fields= fieldList\n self.fieldMap= {}\n offset= 0\n for f in self.fields: \n f.offset= offset\n offset += f.size\n self.fieldMap[f.name]= f\n def parse( self, aLine ):\n self.buffer= aLine\n def get( self, aField ):\n fld= self.fieldMap[aField]\n return self.buffer[ fld.offset:fld.offset+fld.size+1 ]\n def __getattr__( self, aField ):\n return self.get(aField)\n myRecord= Record( \n Field('aField',8), \n Field('filler',1), \n Field('another',5),\n Field('somethingElse',8),\n)\n myRecord.parse(input)\nmyRecord.get('aField')\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13466/"
] |
371,328 | <p>Given the following class</p>
<pre><code>public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
</code></pre>
<p>I have overridden the <code>Equals</code> method because <code>Foo</code> represent a row for the <code>Foo</code>s table. Which is the preferred method for overriding the <code>GetHashCode</code>?</p>
<p>Why is it important to override <code>GetHashCode</code>?</p>
| [
{
"answer_id": 371348,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 12,
"selected": true,
"text": "HashSet<T> IEqualityComparer<T> Equals Equals(...) == true GetHashCode() GetHashCode() Equals return FooId; GetHashCode() new Foo(3,5) new Foo(5,3) HashCode unchecked // only needed if you're compiling with arithmetic checks enabled\n{ // (the default compiler behaviour is *disabled*, so most folks won't need this)\n int hash = 13;\n hash = (hash * 7) + field1.GetHashCode();\n hash = (hash * 7) + field2.GetHashCode();\n ...\n return hash;\n}\n == != Equals GetHashCode"
},
{
"answer_id": 371350,
"author": "Trap",
"author_id": 7839,
"author_profile": "https://Stackoverflow.com/users/7839",
"pm_score": 6,
"selected": false,
"text": "public override int GetHashCode()\n{\n unchecked\n {\n var result = 0;\n result = (result * 397) ^ m_someVar1;\n result = (result * 397) ^ m_someVar2;\n result = (result * 397) ^ m_someVar3;\n result = (result * 397) ^ m_someVar4;\n return result;\n }\n}\n"
},
{
"answer_id": 384411,
"author": "Albic",
"author_id": 48120,
"author_profile": "https://Stackoverflow.com/users/48120",
"pm_score": 7,
"selected": false,
"text": "GetHashCode()"
},
{
"answer_id": 4272851,
"author": "Ludmil Tinkov",
"author_id": 519553,
"author_profile": "https://Stackoverflow.com/users/519553",
"pm_score": 5,
"selected": false,
"text": "public override int GetHashCode()\n{\n return string.Format(\"{0}_{1}_{2}\", prop1, prop2, prop3).GetHashCode();\n}\n"
},
{
"answer_id": 6487372,
"author": "ILoveFortran",
"author_id": 49955,
"author_profile": "https://Stackoverflow.com/users/49955",
"pm_score": 3,
"selected": false,
"text": " public override int GetHashCode()\n {\n return base.GetHashCode();\n }\n \n class A\n {\n public int Value;\n\n public override int GetHashCode()\n {\n return Value.GetHashCode(); //WRONG! Value is not constant during the instance's life time\n }\n } \n \n class A\n {\n public readonly int Value;\n\n public override int GetHashCode()\n {\n return Value.GetHashCode(); //OK Value is read-only and can't be changed during the instance's life time\n }\n }\n\n"
},
{
"answer_id": 8163666,
"author": "huha",
"author_id": 1051244,
"author_profile": "https://Stackoverflow.com/users/1051244",
"pm_score": 5,
"selected": false,
"text": "null Equals() public override bool Equals(object obj)\n{\n Foo fooItem = obj as Foo;\n\n if (fooItem == null)\n {\n return false;\n }\n\n return fooItem.FooId == this.FooId;\n}\n Equals null"
},
{
"answer_id": 20068780,
"author": "Ian Ringrose",
"author_id": 57159,
"author_profile": "https://Stackoverflow.com/users/57159",
"pm_score": 4,
"selected": false,
"text": "GetHashCode() GetHashCode() GetHashCode() GetHashCode() Equals() GetHashCode() public class Foo\n{\n public int FooId { get; set; }\n public string FooName { get; set; }\n\n public override bool Equals(object obj)\n {\n Foo fooItem = obj as Foo;\n\n if (fooItem == null)\n {\n return false;\n }\n\n return fooItem.FooId == this.FooId;\n }\n\n public override int GetHashCode()\n {\n // Some comment to explain if there is a real problem with providing GetHashCode() \n // or if I just don't see a need for it for the given class\n throw new Exception(\"Sorry I don't know what GetHashCode should do for this class\");\n }\n}\n"
},
{
"answer_id": 22412667,
"author": "Guanxi",
"author_id": 1938828,
"author_profile": "https://Stackoverflow.com/users/1938828",
"pm_score": -1,
"selected": false,
"text": " public int getHashCode()\n {\n PropertyInfo[] theProperties = this.GetType().GetProperties();\n int hash = 31;\n foreach (PropertyInfo info in theProperties)\n {\n if (info != null)\n {\n var value = info.GetValue(this,null);\n if(value != null)\n unchecked\n {\n hash = 29 * hash ^ value.GetHashCode();\n }\n }\n }\n return hash; \n }\n"
},
{
"answer_id": 61730200,
"author": "l33t",
"author_id": 419761,
"author_profile": "https://Stackoverflow.com/users/419761",
"pm_score": 5,
"selected": false,
"text": ".NET 4.7 GetHashCode() // C# 7.0+\npublic override int GetHashCode() => (FooId, FooName).GetHashCode();\n struct"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
371,329 | <p>I've several textboxes. I would like to make the Enter button act as Tab. So that when I will be in one textbox, pressing Enter will move me to the next one. Could you please tell me how to implement this approach without adding any code inside textbox class (no override and so on if possible)?</p>
| [
{
"answer_id": 371351,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": -1,
"selected": false,
"text": "// on enter event handler\nparentForm.GetNextControl().Focus();\n"
},
{
"answer_id": 371362,
"author": "JFV",
"author_id": 1391,
"author_profile": "https://Stackoverflow.com/users/1391",
"pm_score": -1,
"selected": false,
"text": "private void textBox_KeyPress(object sender, KeyPressEventArgs e)\n{\nif (e.KeyChar == ‘\\r’)\n{\ne.Handled = true;\nparentForm.GetNextControl().Focus()\n}\n}\n"
},
{
"answer_id": 371409,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 4,
"selected": false,
"text": " if (e.KeyCode == Keys.Enter)\n {\n\n if (this.GetNextControl(ActiveControl, true) != null)\n {\n e.Handled = true;\n this.GetNextControl(ActiveControl, true).Focus();\n\n }\n }\n System.Windows.Forms.SendKeys.Send(\"{TAB}\");\n"
},
{
"answer_id": 503814,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "private void General_KeyDown(object sender, KeyPressEventArgs e)\n {\n if (e.KeyCode == Keys.Enter)\n {\n\n if (this.GetNextControl(ActiveControl, true) != null)\n {\n e.Handled = true;\n this.GetNextControl(ActiveControl, true).Focus();\n }\n }\n}\n"
},
{
"answer_id": 1362325,
"author": "Mac",
"author_id": 85334,
"author_profile": "https://Stackoverflow.com/users/85334",
"pm_score": 0,
"selected": false,
"text": "Public Class NoReturnTextBox\n Inherits System.Windows.Forms.TextBox\n\n Const CARRIAGE_RETURN As Char = Chr(13)\n\n ' Trap for return key....\n Private Sub NoReturnTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress\n\n If e.KeyChar = CARRIAGE_RETURN Then\n e.Handled = True\n System.Windows.Forms.SendKeys.Send(vbTab)\n End If\n\n End Sub\n\nEnd Class\n"
},
{
"answer_id": 8522935,
"author": "Cadair Idris",
"author_id": 822587,
"author_profile": "https://Stackoverflow.com/users/822587",
"pm_score": 2,
"selected": false,
"text": "if (e.Key == Key.Enter)\n ((TextBox)sender).MoveFocus(new TraversalRequest(new FocusNavigationDirection()));\n"
},
{
"answer_id": 11601550,
"author": "Behzad",
"author_id": 478162,
"author_profile": "https://Stackoverflow.com/users/478162",
"pm_score": 6,
"selected": true,
"text": "if (e.KeyData == Keys.Enter)\n{\n e.SuppressKeyPress = true;\n SelectNextControl(ActiveControl, true, true, true, true);\n}\n protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{ \n if (keyData == (Keys.Enter))\n {\n SendKeys.Send(\"{TAB}\");\n }\n\n return base.ProcessCmdKey(ref msg, keyData);\n}\n"
},
{
"answer_id": 21903895,
"author": "FXX",
"author_id": 2969371,
"author_profile": "https://Stackoverflow.com/users/2969371",
"pm_score": 2,
"selected": false,
"text": " Private Sub frmStart_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown\n If e.KeyCode = Keys.Enter Then\n System.Windows.Forms.SendKeys.Send(\"{TAB}\")\n End If\nEnd Sub\n"
},
{
"answer_id": 26346704,
"author": "Greg",
"author_id": 4138603,
"author_profile": "https://Stackoverflow.com/users/4138603",
"pm_score": 2,
"selected": false,
"text": "e.Handled = true e.Handled = e.SuppressKeyPress = true;\n e.SuppressKeyPress"
},
{
"answer_id": 28430559,
"author": "Shahrzad Saeedi",
"author_id": 4550181,
"author_profile": "https://Stackoverflow.com/users/4550181",
"pm_score": 1,
"selected": false,
"text": "if (e.KeyData == Keys.Enter)\n{\n e.SuppressKeyPress = true;\n SelectNextControl(ActiveControl, true, true, true, true);\n}\n keydown"
},
{
"answer_id": 41119497,
"author": "Xabier Aberasturi",
"author_id": 4937699,
"author_profile": "https://Stackoverflow.com/users/4937699",
"pm_score": 0,
"selected": false,
"text": " If ActiveControl.Name = txtMyMutilineTextBox.Name Then Exit Sub \n\n e.SuppressKeyPress = True\n SelectNextControl(ActiveControl, True, True, True, True)\n"
},
{
"answer_id": 54810827,
"author": "glctig",
"author_id": 4950716,
"author_profile": "https://Stackoverflow.com/users/4950716",
"pm_score": 1,
"selected": false,
"text": " private void alltextBoxes_KeyDown(object sender, KeyEventArgs e)\n {\n try\n {\n if (e.KeyCode == Keys.Enter)\n {\n e.SuppressKeyPress = true;\n SelectNextControl(ActiveControl, true, true, true, true); \n }\n }\n catch\n {\n }\n }\n private void lastinput_KeyDown(object sender, KeyEventArgs e)\n {\n try\n {\n if (e.KeyCode == Keys.Enter)\n {\n e.SuppressKeyPress = true;\n System.Windows.Forms.SendKeys.Send(\"{TAB}\");\n }\n }\n catch\n {\n }\n }\n"
},
{
"answer_id": 69971622,
"author": "Ezra Edwin",
"author_id": 13442442,
"author_profile": "https://Stackoverflow.com/users/13442442",
"pm_score": 0,
"selected": false,
"text": "protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n {\n if (keyData == (Keys.Enter))\n {\n SelectNextControl(ActiveControl, true, true, true, true);\n }\n\n return base.ProcessCmdKey(ref msg, keyData);\n }\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38940/"
] |
371,333 | <p>What is the Ruby idiomatic way for retrieving a single character from a string as a one-character string? There is the <code>str[n]</code> method of course, but (as of Ruby 1.8) it returns a character code as a fixnum, not a string. How do you get to a single-character string?</p>
| [
{
"answer_id": 371341,
"author": "Thiago Arrais",
"author_id": 17801,
"author_profile": "https://Stackoverflow.com/users/17801",
"pm_score": 0,
"selected": false,
"text": "'abc'[1].chr # => \"b\"\n"
},
{
"answer_id": 371342,
"author": "Thiago Arrais",
"author_id": 17801,
"author_profile": "https://Stackoverflow.com/users/17801",
"pm_score": 2,
"selected": false,
"text": "'abc'[1..1] # => \"b\"\n"
},
{
"answer_id": 371357,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": false,
"text": "'Hello'[1].chr # => \"e\"\n 'Hello'[1] # => \"e\"\n"
},
{
"answer_id": 371528,
"author": "Brent.Longborough",
"author_id": 9634,
"author_profile": "https://Stackoverflow.com/users/9634",
"pm_score": 3,
"selected": false,
"text": "'Hello'[2,1] # => \"l\"\n"
},
{
"answer_id": 374299,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 5,
"selected": true,
"text": "'µsec'[0] => 'µ'\n 'µsec'[0] # => 194\n'µsec'[0].chr # => Garbage\n'µsec'[0,1] # => Garbage\n 'µsec'.split('')[0] # => 'µ'\n'µsec'.split(//u)[0] # => 'µ'\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17801/"
] |
371,337 | <p>An image set as the background of a DIV is displayed in IE, but not in Firefox.</p>
<p>CSS example:</p>
<pre><code>div.something {
background:transparent url(../images/table_column.jpg) repeat scroll 0 0;
}
</code></pre>
<p>(The issue is described in many places but haven't seen any conclusive explanation or fix.)</p>
| [
{
"answer_id": 371367,
"author": "Kablam",
"author_id": 42389,
"author_profile": "https://Stackoverflow.com/users/42389",
"pm_score": 0,
"selected": false,
"text": "div.something {\nbackground: transparent url(../images/table_column.jpg);\n}\n"
},
{
"answer_id": 371368,
"author": "Philip Morton",
"author_id": 21709,
"author_profile": "https://Stackoverflow.com/users/21709",
"pm_score": 2,
"selected": false,
"text": "background-image: url('image.jpg');\n"
},
{
"answer_id": 372538,
"author": "Olaf Kock",
"author_id": 13447,
"author_profile": "https://Stackoverflow.com/users/13447",
"pm_score": 0,
"selected": false,
"text": "<head>\n <base href=\"http://example.com/some/bizarre/directory\"/>\n</head>\n"
},
{
"answer_id": 394453,
"author": "Mike Geise",
"author_id": 43380,
"author_profile": "https://Stackoverflow.com/users/43380",
"pm_score": 1,
"selected": false,
"text": "background-color: transparent;\nbackground-image: url(\"/path/to/image/file.jpg\");\nbackground-repeat: repeat;\nbackground-position: top;\nbackground-attachment: scroll;\n"
},
{
"answer_id": 413467,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 4,
"selected": false,
"text": "public/\n css/\n global.css\n images/\n background.jpg\n something/\n index.html\n index.html\n public/index.html #1: <link href=\"./css/global.css\"\n#2: <link href=\"/css/global.css\"\n#3: <link href=\"css/global.css\"\n public/something/index.html http://localhost/controller/action/params url('./images/background.jpg') /* won't work */\nurl('../images/background.jpg') /* works: ../ == up one level */\n url() div div.something {\n display: block; /* for verification */\n min-height: 50px;\n min-width: 50px;\n}\n"
},
{
"answer_id": 3457534,
"author": "Astravagrant",
"author_id": 275655,
"author_profile": "https://Stackoverflow.com/users/275655",
"pm_score": 1,
"selected": false,
"text": "\n/* Relative to Stylesheet (Works in Firefox) */\nbackground: url('../images/logo.gif');\n/* Relative to Page (Works in IE, Chrome etc.) */\nbackground: url('images/logo.gif');\n/* Absolute path (Fine, unless you change domains)*/\nbackground: url('http://www.webby.com/myproduct/images/factsheet.gif');\n/* Domain Root-relative path (Works in Firefox, IE, Chrome and Opera) */\nbackground: url('/myproduct/images/factsheet.gif');\n"
},
{
"answer_id": 6006740,
"author": "valk",
"author_id": 400745,
"author_profile": "https://Stackoverflow.com/users/400745",
"pm_score": 0,
"selected": false,
"text": "background: transparent url(\"/my/image.png\") right 60% no-repeat;\n background: transparent url(\"/my/image.png\") 100% 60% no-repeat;\n"
},
{
"answer_id": 10322188,
"author": "PeterM",
"author_id": 1357037,
"author_profile": "https://Stackoverflow.com/users/1357037",
"pm_score": 0,
"selected": false,
"text": "overflow:auto; display:block;"
},
{
"answer_id": 18341662,
"author": "REDFOX",
"author_id": 529802,
"author_profile": "https://Stackoverflow.com/users/529802",
"pm_score": 0,
"selected": false,
"text": "#hwrap {\nbackground-color: #d5b75a;\nbackground: url(\"..//design/bg_header_daddy.png\"), url(\"..//design/nasty_fabric.png\");\nbackground-position: 50% 50%, top left;\nbackground-origin: border-box, border-box;\nbackground-repeat: no-repeat, repeat;\n}\n"
},
{
"answer_id": 27789215,
"author": "WoodrowShigeru",
"author_id": 2126442,
"author_profile": "https://Stackoverflow.com/users/2126442",
"pm_score": 0,
"selected": false,
"text": "style.css pageMod contentStyleFile background-image: url(/img/editlist.png); contentStyle"
},
{
"answer_id": 47220189,
"author": "Erwan Clügairtz",
"author_id": 7616414,
"author_profile": "https://Stackoverflow.com/users/7616414",
"pm_score": 0,
"selected": false,
"text": "background-image:url('dead.beef');\nbackground-size: 100% 100%;\nbackground-origin:border-box;\n"
},
{
"answer_id": 54157758,
"author": "Haim",
"author_id": 7487159,
"author_profile": "https://Stackoverflow.com/users/7487159",
"pm_score": 2,
"selected": false,
"text": ".left-bg-image {\n display: block; // add this line\n\n background-image: url('../images/profile.jpeg');\n background-repeat: no-repeat;\n background-size: cover;\n background-position: center center;\n opacity: .6;\n min-width: 100%;\n min-height: 100vh;\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46665/"
] |
371,371 | <p>I'd like a C library that can serialize my data structures to disk, and then load them again later. It should accept arbitrarily nested structures, possibly with circular references.</p>
<p>I presume that this tool would need a configuration file describing my data structures. The library is allowed to use code generation, although I'm fairly sure it's possible to do this without it. </p>
<p>Note I'm not interested in data portability. I'd like to use it as a cache, so I can rely on the environment not changing.</p>
<p>Thanks.</p>
<hr>
<p><em>Results</em></p>
<p>Someone suggested <a href="http://tpl.sourceforge.net/" rel="noreferrer">Tpl</a> which is an awesome library, but I believe that it does not do arbitrary object graphs, such as a tree of Nodes that each contain two other Nodes.</p>
<p>Another candidate is <a href="http://www.enlightenment.org/p.php?p=about/efl/eet&l=en" rel="noreferrer">Eet</a>, which is a project of the Enlightenment window manager. Looks interesting but, again, seems not to have the ability to serialize nested structures.</p>
| [
{
"answer_id": 372113,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 3,
"selected": false,
"text": "typedef char *name; enum {\n mask_none = 0x00,\n mask_something = 0x01,\n mask_another = 0x02,\n /* ... */\n mask_all = 0xff\n};\ntypedef struct mask_map {\n int mask_val;\n char *mask_name;\n} mask_map_t;\nmask_map_t mask_list[] = {\n {mask_something, \"mask_something\"},\n {mask_another, \"mask_another\"},\n /* ... */\n};\nstruct saved_setup {\n char* name;\n /* various configuration data */\n char* mask_name;\n /* ... */\n};\n struct saved_setup mask_name mask_list[foo].mask_name struct saved_setup.mask_name"
},
{
"answer_id": 15064199,
"author": "Amith Chinthaka",
"author_id": 2106802,
"author_profile": "https://Stackoverflow.com/users/2106802",
"pm_score": 3,
"selected": false,
"text": "mmap munmap"
},
{
"answer_id": 33686951,
"author": "Bernardo Ramos",
"author_id": 4626775,
"author_profile": "https://Stackoverflow.com/users/4626775",
"pm_score": 1,
"selected": false,
"text": " binn *obj;\n\n // create a new object\n obj = binn_object();\n\n // add values to it\n binn_object_set_int32(obj, \"id\", 123);\n binn_object_set_str(obj, \"name\", \"Samsung Galaxy Charger\");\n binn_object_set_double(obj, \"price\", 12.50);\n binn_object_set_blob(obj, \"picture\", picptr, piclen);\n\n // send over the network\n send(sock, binn_ptr(obj), binn_size(obj));\n\n // release the buffer\n binn_free(obj);\n binn *list;\n\n // create a new list\n list = binn_list();\n\n // add values to it\n binn_list_add_int32(list, 123);\n binn_list_add_double(list, 2.50);\n\n // add the list to the object\n binn_object_set_list(obj, \"items\", list);\n\n // or add the object to the list\n binn_list_add_object(list, obj);\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11951/"
] |
371,372 | <p>I am using ruby on rails with a MySQL backend. I have a table called notes and here is the migration I use to create it:</p>
<pre><code>def self.up
create_table(:notes, :options => 'ENGINE=MyISAM') do |t|
t.string :title
t.text :body
t.timestamps
end
execute "alter table notes ADD FULLTEXT(title, body)"
end
</code></pre>
<p>I want to do full text searches on the title and body fields. The problem is that the full text searches always come back empty. For example if I add this row into the database: <code>Title: test, Body: test</code>. Then I run this query <code>SELECT * FROM notes WHERE MATCH(title, body) AGAINST('test')</code>. It returns a nil set. Can anybody tell me what I am doing wrong and how to get full text search working?</p>
| [
{
"answer_id": 371408,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 4,
"selected": true,
"text": "SELECT * FROM notes WHERE MATCH(title, body) AGAINST('test' IN BOOLEAN MODE)\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
371,378 | <p>Working with VS.NET 2008, output type Class Library, Target Framework .NET 2.0</p>
<p>I've come up with a simplified scenario to ask this question.</p>
<p>I have a <code>Button</code> user control, its a simple panel with a single big button on it.</p>
<p>I want to create a <code>RedButton</code> control that extends <code>Button</code>, and similarly, a <code>GreenButton</code>.<br/>e.g. <code>Class RedButton : Button</code></p>
<p>Ideally, when I open up <code>RedButton</code>'s designer I will see the button that I created in <code>Button</code> and be able to modify it, for example make it Red, or change font, etc.</p>
<p>I've tried to do this once, but when I open up the <code>RedButton</code>'s designer I just get a bunch of errors. </p>
<p>In this case, doing all this work programatically isn't an option for us, as in the real case this would be a pain.</p>
<p>Could someone shed some light on this?
Thanks Very Much.</p>
| [
{
"answer_id": 371459,
"author": "Jacob Adams",
"author_id": 32518,
"author_profile": "https://Stackoverflow.com/users/32518",
"pm_score": 0,
"selected": false,
"text": "btnTheButton.BackGround=Color.Red; \n"
},
{
"answer_id": 6429536,
"author": "AndyClaw",
"author_id": 586835,
"author_profile": "https://Stackoverflow.com/users/586835",
"pm_score": 0,
"selected": false,
"text": "public class RedButton : Button\n <UserControl></UserControl>\n <Button></Button>\n <radDock:RadPane ... \n xmlns:radDock=\"clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Docking\"\n ...\n Title=\"{Binding Path=StudyTitle}\"...\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,384 | <p>What is the best way to print stuff from c#/.net?</p>
<p>The question is in regard to single pages as well as to reports containing lots of pages. </p>
<p>It would be great to get a list of the most common printing libs containing the main features and gotchas of each of them.</p>
<p>[Update] for standard windows clients (or servers), not for web apps, please.</p>
| [
{
"answer_id": 371399,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 4,
"selected": true,
"text": "Sub MyMethod()\n Dim x as New PrintDocument\n AddHandler x.PrintPage, AddressOf printDoc_PrintPage\n x.Print\nEnd Sub\nSub printDoc_PrintPage( sender as Object, e as PrintPageEventArgs)\n Dim textToPrint as String= \".NET Printing is easy\"\n dim printFont as new Font(\"Courier New\", 12)\n dim leftMargin as int= e.MarginBounds.Left\n dim topMargin as int = e.MarginBounds.Top\n e.Graphics.DrawString(textToPrint, printFont, Brushes.Black, leftMargin, topMargin)\nEnd Sub\n"
},
{
"answer_id": 20772147,
"author": "S.Serpooshan",
"author_id": 2803565,
"author_profile": "https://Stackoverflow.com/users/2803565",
"pm_score": 2,
"selected": false,
"text": " using System.Drawing.Printing;\n\n PrintDocument printDoc = new PrintDocument();\n printDoc.DefaultPageSettings.Landscape = true;\n printDoc.DefaultPageSettings.Margins.Left = 100; //100 = 1 inch = 2.54 cm\n printDoc.DocumentName = \"My Document Name\"; //this can affect name of output PDF file if printer is a PDF printer\n //printDoc.PrinterSettings.PrinterName = \"CutePDF\";\n printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);\n\n PrintDialog printDialog = new PrintDialog();\n printDialog.Document = printDoc; //Document property must be set before ShowDialog()\n\n DialogResult dialogResult = printDialog.ShowDialog();\n if (dialogResult == DialogResult.OK)\n {\n printDoc.Print(); //start the print\n } \n\n void printDoc_PrintPage(object sender, PrintPageEventArgs e)\n {\n Graphics g = e.Graphics;\n string textToPrint = \".NET Printing is easy\";\n Font font = new Font(\"Courier New\", 12);\n // e.PageBounds is total page size (does not consider margins)\n // e.MarginBounds is the portion of page inside margins\n int x1 = e.MarginBounds.Left;\n int y1 = e.MarginBounds.Top;\n int w = e.MarginBounds.Width;\n int h = e.MarginBounds.Height;\n\n g.DrawRectangle(Pens.Red, x1, y1, w, h); //draw a rectangle around the margins of the page, also we can use: g.DrawRectangle(Pens.Red, e.MarginBounds)\n g.DrawString(textToPrint, font, Brushes.Black, x1, y1);\n\n e.HasMorePages = false; //set to true to continue printing next page\n }\n"
},
{
"answer_id": 51506066,
"author": "John Doe",
"author_id": 5569922,
"author_profile": "https://Stackoverflow.com/users/5569922",
"pm_score": 0,
"selected": false,
"text": " // Sample fileName = System.Environment.GetFolderPath(\n // System.Environment.SpecialFolder.CommonApplicationData)\n // + @\"\\MyCompany\\MyProject\\TestPrint.pdf\"\n private void SendPrintJob(string fileName)\n {\n try\n {\n // Start by finding Acrobat from the Registry.\n // This supposedly gets whichever you have of free or paid\n string processFilename = Microsoft.Win32.Registry.LocalMachine\n .OpenSubKey(\"Software\")\n .OpenSubKey(\"Microsoft\")\n .OpenSubKey(\"Windows\")\n .OpenSubKey(\"CurrentVersion\")\n .OpenSubKey(\"App Paths\")\n .OpenSubKey(\"AcroRd32.exe\")\n .GetValue(String.Empty).ToString();\n\n ProcessStartInfo info = new ProcessStartInfo();\n info.Verb = \"print\";\n info.FileName = processFilename;\n info.Arguments = String.Format(\"/p /h {0}\", fileName);\n info.CreateNoWindow = true;\n info.WindowStyle = ProcessWindowStyle.Hidden;\n info.UseShellExecute = false;\n\n Process p = new Process();\n p.StartInfo = info;\n p.Start();\n\n p.WaitForInputIdle();\n\n // Recommended to add a time-out feature. Mine is coded here.\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Error sending print job. \" + e.Message);\n }\n PDFsharp-MigraDocs PDFsharp-MigraDocs-WPF PDFsharp-MigraDocs-GDI"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
] |
371,386 | <p>Having an odd problems with ASP MVC deployed on IIS6 (Windows 2003). I've simplified the controller code to the below;</p>
<pre><code><AcceptVerbs(HttpVerbs.Get)> _
Public Function CloseBatches() As ActionResult
ViewData("Title") = "Close Batches"
ViewData("Message") = Session("Message")
Return View()
End Function
<AcceptVerbs(HttpVerbs.Post)> _
Public Function CloseBatches(ByVal RequestId As String) As ActionResult
Session("Message") = "Yadda yadda blah"
Return RedirectToAction("CloseBatches")
End Function
</code></pre>
<p>The controller did originally do more, of course, but stripped it to this to try to troubleshoot. The page has the basic ViewPage html (master page reference, etc) and then;</p>
<pre><code><p><%=ViewData("Message")%></p>
<%Using Html.BeginForm("CloseBatches", "Home", New With {.RequestId = "Close"})%>
<input type="submit" id="Close" value="Close"/>
<%End Using%>
</code></pre>
<p>As you can see I'm trying to go with the Post-Redirect-Display pattern which seems to be the way to go at the moment. The trouble is the when you click the button the message doesn't appear, no matter how many times you click the button. However, if you do a refresh/F5 the text does appear - then refresh again and it disappears - refresh again and it appears - repeat!</p>
<p>I've had breakpoints on both controller functions and it hits them at the correct points, I've stepped through the code and no errors are happening so the ViewData should be populated, but the page just doesn't always show it!</p>
<p>Tested with IE7 and FF3 - the latter seems a bit more intermittent in that it does occasionally work!</p>
<p>Any ideas? Something obvious I'm missing? Could some weird caching be going on?</p>
<p>Thanks.</p>
| [
{
"answer_id": 371433,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 2,
"selected": false,
"text": "<AcceptVerbs(HttpVerbs.Get)> _\nPublic Function CloseBatches() As ActionResult\n ViewData(\"Title\") = \"Close Batches\"\n Return View()\nEnd Function\n\n<AcceptVerbs(HttpVerbs.Post)> _\nPublic Function CloseBatches(ByVal RequestId As String) As ActionResult\n TempData(\"Message\") = \"Yadda yadda blah\"\n Return RedirectToAction(\"CloseBatches\")\nEnd Function\n\n<p><%=ViewData.Eval(\"Message\")%></p>\n<%Using Html.BeginForm(\"CloseBatches\", \"Home\", New With {.RequestId = \"Close\"})%>\n <input type=\"submit\" id=\"Close\" value=\"Close\"/>\n<%End Using%>\n"
},
{
"answer_id": 371536,
"author": "tsquillario",
"author_id": 45509,
"author_profile": "https://Stackoverflow.com/users/45509",
"pm_score": 0,
"selected": false,
"text": "TempData.ContainsKey(\"Error\") \n ViewData.Eval(\"Error\")\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,404 | <p>I have an Access 2003 file that contains 200 queries, and I want to print out their representation in SQL. I can use Design View to look at each query and cut and paste it to a file, but that's tedious. Also, I may have to do this again on other Access files, so I definitely want to write a program to do it.</p>
<p>Where are queries stored an Access db? I can't find anything saying how to get at them. I'm unfamiliar with Access, so I'd appreciate any pointers. Thanks!</p>
| [
{
"answer_id": 371811,
"author": "Mark Bell",
"author_id": 43140,
"author_profile": "https://Stackoverflow.com/users/43140",
"pm_score": 4,
"selected": true,
"text": "OleDbConnection conn = new OleDbConnection(connectionString);\nconn.Open();\n\nDataTable queries = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Procedures, null);\n\nconn.Close();\n foreach(DataRow row in queries.Rows)\n{\n // Do what you want with the values here\n queryName = row[\"PROCEDURE_NAME\"].ToString();\n sql = row[\"PROCEDURE_DEFINITION\"].ToString();\n}\n"
},
{
"answer_id": 7604233,
"author": "joshgo",
"author_id": 160146,
"author_profile": "https://Stackoverflow.com/users/160146",
"pm_score": 1,
"selected": false,
"text": "SELECT MSysObjects.Name\nFROM MSysObjects\nWHERE type = 5\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1121861/"
] |
371,417 | <p>I'm working on mapping two objects in .NET. </p>
<p>I would like to be able to print the items in the properties list from the Object Browser window in Visual Studio 2008. Is there a way to print that information out to the console?</p>
<p>If that is not possible, what is a good method to print a general definition of a class (property names, method names)?</p>
| [
{
"answer_id": 371494,
"author": "R. Martinho Fernandes",
"author_id": 46642,
"author_profile": "https://Stackoverflow.com/users/46642",
"pm_score": 2,
"selected": true,
"text": "System.Reflection"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283/"
] |
371,418 | <p>I've recently found out about protocol buffers and was wondering if they could be applied to my specific problem.</p>
<p>Basically I have some CSV data that I need to convert to a more compact format for storage as some of the files are several gig. </p>
<p>Each field in the CSV has a header, and there are only two types, strings and decimals (because sometimes there are alot of significant digits and I need to handle all numbers the same way). But each file will have different column names for each field.</p>
<p>As well as capturing the original CSV data I need to be able to add extra information to the file before saving. And I was hoping to make this future proof by handling different file versions.</p>
<p>So, is it possible to use protocol buffers to capture a random number of randomly named columns of data, like a CSV file?</p>
| [
{
"answer_id": 371508,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "message CsvFile {\n repeated CsvHeader header = 1;\n repeated CsvRow row = 2;\n}\n\nmessage CsvHeader {\n require string name = 1;\n require ColumnType type = 2;\n}\n\nenum ColumnType {\n DECIMAL = 1;\n STRING = 2;\n}\n\nmessage CsvRow {\n repeated CsvValue value = 1;\n}\n\n// Note that the column is implicit based on position within row \nmessage CsvValue {\n optional string string_value = 1;\n optional Decimal decimal_value = 2;\n}\n\nmessage Decimal {\n // However you want to represent it (there are various options here)\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3820/"
] |
371,419 | <p>I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it.</p>
<p>My first instinct is to cast inputs as floats from within a try-except block.</p>
<pre><code>try:
myinput = float(input)
except:
raise ValueError("input is not a well-formed number")
</code></pre>
<p>I could also call <code>isinstance(mydata, (float, int, long) )</code> but the list of "all these could be numbers" seems a bit inelegant to me.</p>
<p>What's the most pythonic way of going about it? Is there another option I overlooked?</p>
| [
{
"answer_id": 371436,
"author": "Mapad",
"author_id": 28165,
"author_profile": "https://Stackoverflow.com/users/28165",
"pm_score": 2,
"selected": false,
"text": "assert isinstance number = (float, int, long)\nassert isinstance(mydata, (float, int, long))\n"
},
{
"answer_id": 371573,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": ">>> import numbers\n>>> isValid = isinstance(myinput , numbers.Real)\n >>> [isinstance(x, numbers.Real) for x in [4, 4.5, \"some string\", 3+2j]]\n[True, True, False, False]\n"
},
{
"answer_id": 372346,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "__float__ try:\n myinput = float(input)\nexcept:\n raise ValueError(\"input is not a well-formed number\")\n# at this point, input may not be numeric at all\n# it may, however, have produced a numeric value\n isinstance(input, (float, int, long) )\n# at this point, input is one of a known list of numeric types\n float class MyStrangeThing( object ):\n def __init__( self, aString ):\n # Some fancy parsing \n def __float__( self ):\n # extract some numeric value from my thing\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8027/"
] |
371,422 | <p>I'm looking to build a query that will use the non-clustered indexing plan on a street address field that is built with a non-clustered index. The problem I'm having is that if I'm searching for a street address I will most likely be using the 'like' eval function. I'm thinking that using this function will cause a table scan instead of using the index. How would I go about writing one in this case? Is it just pointless to put a non-clustered index on an address3 field? Thanks in advance.</p>
| [
{
"answer_id": 371447,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "Address LIKE 'Blah%' Address LIKE '%Blah%'"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491425/"
] |
371,426 | <p>When running a web application project, at seemingly random times a page may fail with a CS0433 error: type exists in multiple DLL's. The DLL's are all generated DLL's residing in the "Temporary ASP.NET Files" directory.</p>
| [
{
"answer_id": 714320,
"author": "Mike Powell",
"author_id": 205,
"author_profile": "https://Stackoverflow.com/users/205",
"pm_score": 2,
"selected": false,
"text": "compilation batch=\"false\" compilation batch=\"true\" batch=\"true\""
},
{
"answer_id": 10241054,
"author": "Amrinder Singh",
"author_id": 1345731,
"author_profile": "https://Stackoverflow.com/users/1345731",
"pm_score": 4,
"selected": false,
"text": "inherits= <@page language=......inherits=> inherits="
},
{
"answer_id": 17891117,
"author": "Saliba",
"author_id": 1555603,
"author_profile": "https://Stackoverflow.com/users/1555603",
"pm_score": 0,
"selected": false,
"text": " <%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"controllerName.ascx.cs\" Inherits=\"Controls.controllerName\" %>\n <%@ Control Language=\"C#\" AutoEventWireup=\"true\" Src=\"controllerName.ascx.cs\" Inherits=\"Controls.controllerName\" %>\n using System;\nusing System.Web.UI;\n\n/// <summary>\n/// My controller\n/// </summary>\npublic partial class controllerName: UserControl\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n }\n}\n using System;\nusing System.Web.UI;\n\nnamespace Controles\n{\n /// <summary>\n /// My controller\n /// </summary>\n public class controllerName : UserControl\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n }\n }\n}\n"
},
{
"answer_id": 74601363,
"author": "Mustafa Bazghandi",
"author_id": 7826774,
"author_profile": "https://Stackoverflow.com/users/7826774",
"pm_score": 0,
"selected": false,
"text": ".csproj <ItemGroup>\n <Reference Include=\"temp1.dll\">\n <Aliases>MyAssembly</Aliases>\n </Reference>\n</ItemGroup>\n MyAssembly temp1.dll foo temp1.dll using MyAssembly.foo;\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6902/"
] |
371,439 | <p>Normally when you update an object in linq2sql you get the object from a datacontext and use the same datacontext to save the object, right?</p>
<p>What's the best way to update a object that hasn't been retreived by that datacontext that you use to perform the save operation, i.e. I'm using flourinefx to pass data between flex and asp.net and when object return from the client to be saved I don't know how to save the object?</p>
<pre><code> public static void Save(Client client)
{
CompanyDataContext db = new CompanyDataContext();
Validate(client);
if(client.Id.Equals(Guid.Empty))
{
//Create (right?):
client.Id = Guid.NewGuid();
db.Clients.InsertOnSubmit(client);
db.SubmitChanges();
}
else
{
//Update:
OffertaDataContext db = new OffertaDataContext();
db.Clients.????
}
}
</code></pre>
<p>Update: different approaches to use Attach doens't work in this case. So I guess a reflection based approach is required.</p>
| [
{
"answer_id": 371493,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "ctx.Customers.Attach(customer); // optional bool to treat as modified\n"
},
{
"answer_id": 725967,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public override IEnumerable(memberState) GetMembersByState(string @state)<br/>\n{<br/>\nusing (BulletinWizardDataContext context = DataContext)<br/>\n{<br/>\nIEnumerable(memberState) mems = (from m in context.Members<br/>\njoin ma in context.MemberAddresses<br/>\non m.UserId equals ma.UserId<br/>\njoin s in context.States<br/>\non ma.StateId equals s.StateId<br/>\nwhere s.StateName == @state<br/>\nselect new memberState<br/>\n{<br/>\nuserId = m.UserID,<br/>\nfirstName = m.FirstName,<br/>\nmiddleInitial = m.MiddleInitial,<br/>\nlastName = m.LastName,<br/>\ncreateDate = m.CreateDate,<br/>\nmodifyDate = m.ModifyDate<br/>\n}).ToArray(memberState)();<br/>\nreturn mems;\n}\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40939/"
] |
371,445 | <p>We have followed the approach below to get the data from multiple results using LINQ To SQL</p>
<pre><code>CREATE PROCEDURE dbo.GetPostByID
(
@PostID int
)
AS
SELECT *
FROM Posts AS p
WHERE p.PostID = @PostID
SELECT c.*
FROM Categories AS c
JOIN PostCategories AS pc
ON (pc.CategoryID = c.CategoryID)
WHERE pc.PostID = @PostID
</code></pre>
<p>The calling method in the class the inherits from DataContext should look like:</p>
<pre><code>[Database(Name = "Blog")]
public class BlogContext : DataContext
{
...
[Function(Name = "dbo.GetPostByID")]
[ResultType(typeof(Post))]
[ResultType(typeof(Category))]
public IMultipleResults GetPostByID(int postID)
{
IExecuteResult result =
this.ExecuteMethodCall(this,
((MethodInfo)(MethodInfo.GetCurrentMethod())),
postID);
return (IMultipleResults)(result.ReturnValue);
}
}
</code></pre>
<p>Notice that the method is decorated not only with the Function attribute that maps to the stored procedure name, but also with the ReturnType attributes with the types of the result sets that the stored procedure returns. Additionally, the method returns an untyped interface of IMultipleResults:</p>
<pre><code>public interface IMultipleResults : IFunctionResult, IDisposable
{
IEnumerable<TElement> GetResult<TElement>();
}
</code></pre>
<p>so the program can use this interface in order to retrieve the results:</p>
<pre><code>BlogContext ctx = new BlogContext(...);
IMultipleResults results = ctx.GetPostByID(...);
IEnumerable<Post> posts = results.GetResult<Post>();
IEnumerable<Category> categories = results.GetResult<Category>();
</code></pre>
<p>In the above stored procedures we had two select queries
1. Select query without join
2. Select query with Join</p>
<p>But in the above second select query the data which is displayed is from one of the table i.e. from Categories table. But we have used join and want to display the data table with the results from both the tables i.e. from Categories as well as PostCategories.</p>
<ol>
<li>Please if anybody can let me know how to achieve this using LINQ to SQL</li>
<li>What is the performance trade-off if we use the above approach vis-à-vis implement the above approach with simple SQL </li>
</ol>
| [
{
"answer_id": 460222,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<Post> posts;\nIEnumerable<Category> categories;\n\nusing (BlogContext ctx = new BlogContext(...))\n{\n ctx.DeferredLoadingEnabled = false; // THIS IS IMPORTANT.\n IMultipleResults results = ctx.GetPostByID(...);\n posts = results.GetResult<Post>().ToList();\n categories = results.GetResult<Category>().ToList();\n}\n// Now we need to associate each category to the post.\n// ASSUMPTION: Each post has only one category (1-1 mapping).\nif (posts != null)\n{\n foreach(var post in posts)\n {\n int postId = post.PostId;\n post.Category = categories\n .Where(p => p.PostId == postId)\n .SingleOrDefault();\n }\n}\n post.Category == blah Where(..) ToList()"
},
{
"answer_id": 4490252,
"author": "Carl J",
"author_id": 267472,
"author_profile": "https://Stackoverflow.com/users/267472",
"pm_score": 0,
"selected": false,
"text": "var rslt = from p in results.GetResult<Post>()\n join c in results.GetResult<Category>() on p.PostId = c.PostID\n ...\n p.Categories.Add(c)\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,455 | <p>I have a c# class which uses the WindowsIdentity namespace to return details of the current Active Directory user. This is accessible through a web part on SPS and sure enough returns the desired record values specific to that user. </p>
<p>I have a classic ASP application which I would like to have inherit this functionality. After wrapping it up as a COM and registering it to the server, I created a Classic ASP page from which to call and display the details to the browser window.</p>
<p>My problem is that when this page is accessed from an authenticated user on a client machine the only user details it displays is that of the local machine.</p>
<p>How do I therefore alter my code so I can display the details of the user accessing the page from a client machine?</p>
| [
{
"answer_id": 460222,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<Post> posts;\nIEnumerable<Category> categories;\n\nusing (BlogContext ctx = new BlogContext(...))\n{\n ctx.DeferredLoadingEnabled = false; // THIS IS IMPORTANT.\n IMultipleResults results = ctx.GetPostByID(...);\n posts = results.GetResult<Post>().ToList();\n categories = results.GetResult<Category>().ToList();\n}\n// Now we need to associate each category to the post.\n// ASSUMPTION: Each post has only one category (1-1 mapping).\nif (posts != null)\n{\n foreach(var post in posts)\n {\n int postId = post.PostId;\n post.Category = categories\n .Where(p => p.PostId == postId)\n .SingleOrDefault();\n }\n}\n post.Category == blah Where(..) ToList()"
},
{
"answer_id": 4490252,
"author": "Carl J",
"author_id": 267472,
"author_profile": "https://Stackoverflow.com/users/267472",
"pm_score": 0,
"selected": false,
"text": "var rslt = from p in results.GetResult<Post>()\n join c in results.GetResult<Category>() on p.PostId = c.PostID\n ...\n p.Categories.Add(c)\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,464 | <p>I have a non-visual component which manages other visual controls. </p>
<p>I need to have a reference to the form that the component is operating on, but i don't know how to get it.</p>
<p>I am unsure of adding a constructor with the parent specified as control, as i want the component to work by just being dropped into the designer.</p>
<p>The other thought i had was to have a Property of parent as a control, with the default value as 'Me'</p>
<p>any suggestions would be great</p>
<p><strong>Edit:</strong></p>
<p>To clarify, this is a <strong>component</strong>, not a <strong>control</strong>, see here :<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx" rel="noreferrer">ComponentModel.Component</a></p>
| [
{
"answer_id": 371559,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 3,
"selected": false,
"text": "public Form ParentForm\n{\n get { return GetParentForm( this.Parent ); }\n}\n\nprivate Form GetParentForm( Control parent )\n{\n Form form = parent as Form;\n if ( form != null )\n {\n return form;\n }\n if ( parent != null )\n {\n // Walk up the control hierarchy\n return GetParentForm( parent.Parent );\n }\n return null; // Control is not on a Form\n}\n"
},
{
"answer_id": 371829,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 6,
"selected": true,
"text": "public ContainerControl ContainerControl\n{\n get { return _containerControl; }\n set { _containerControl = value; }\n}\nprivate ContainerControl _containerControl = null;\n public override ISite Site\n{\n get { return base.Site; }\n set\n {\n base.Site = value;\n if (value == null)\n {\n return;\n }\n\n IDesignerHost host = value.GetService(\n typeof(IDesignerHost)) as IDesignerHost;\n if (host != null)\n {\n IComponent componentHost = host.RootComponent;\n if (componentHost is ContainerControl)\n {\n ContainerControl = componentHost as ContainerControl;\n }\n }\n }\n}\n"
},
{
"answer_id": 11311798,
"author": "Mark",
"author_id": 1498905,
"author_profile": "https://Stackoverflow.com/users/1498905",
"pm_score": 1,
"selected": false,
"text": "''' <summary>\n''' Returns the parent System.Windows.form of the control\n''' </summary>\n''' <param name=\"parent\"></param>\n''' <returns>First parent form or null if no parent found</returns>\n''' <remarks></remarks>\nPublic Shared Function GetParentForm(ByVal parent As Control) As Form\n Dim form As Form = TryCast(parent, Form)\n If form IsNot Nothing Then\n Return form\n End If\n\n If parent IsNot Nothing Then\n ' Walk up the control hierarchy\n Return GetParentForm(parent.Parent)\n End If\n\n ' Control is not on a Form\n Return Nothing\nEnd Function\n"
},
{
"answer_id": 12491919,
"author": "Vaclav Svara",
"author_id": 1682622,
"author_profile": "https://Stackoverflow.com/users/1682622",
"pm_score": 2,
"selected": false,
"text": "public partial class RegistryManager : Component, ISupportInitialize\n{\n\n private Form _parentForm;\n public Form ParentForm\n {\n get { return _parentForm; }\n set { _parentForm = value; }\n }\n\n // Etc....\n\n #region ISupportInitialize\n public void BeginInit() { }\n public void EndInit()\n {\n setUpParentForm();\n }\n private void setUpParentForm()\n {\n if (_parentForm != null) return; // do nothing if it is set\n IDesignerHost host;\n if (Site != null)\n {\n host = Site.GetService(typeof(IDesignerHost)) as IDesignerHost;\n if (host != null)\n {\n if (host.RootComponent is Form)\n {\n _parentForm = (Form)host.RootComponent;\n }\n }\n }\n }\n #endregion\n}\n"
},
{
"answer_id": 26034508,
"author": "sandipmatsagar",
"author_id": 885678,
"author_profile": "https://Stackoverflow.com/users/885678",
"pm_score": 2,
"selected": false,
"text": "private Form GetParentForm(Control parent)\n{\n if (parent is Form)\n return parent as Form;\n\n return parent.FindForm();\n}\n GetParentForm(this.Parent)"
},
{
"answer_id": 37370812,
"author": "GeoB",
"author_id": 4980979,
"author_profile": "https://Stackoverflow.com/users/4980979",
"pm_score": -1,
"selected": false,
"text": "public static Form ParentForm(this Control ctrl) => ctrl as Form ?? ctrl.FindForm();\n"
},
{
"answer_id": 41198742,
"author": "Pollitzer",
"author_id": 3135228,
"author_profile": "https://Stackoverflow.com/users/3135228",
"pm_score": -1,
"selected": false,
"text": "Form Form Form.ActiveForm"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1500/"
] |
371,468 | <p>I'm using jQuery UI's draggable and droppable libraries in a simple ASP.NET proof of concept application. This page uses the ASP.NET AJAX UpdatePanel to do partial page updates. The page allows a user to drop an item into a trashcan div, which will invoke a postback that deletes a record from the database, then rebinds the list (and other controls) that the item was drug from. All of these elements (the draggable items and the trashcan div) are inside an ASP.NET UpdatePanel.</p>
<p>Here is the dragging and dropping initialization script:</p>
<pre><code> function initDragging()
{
$(".person").draggable({helper:'clone'});
$("#trashcan").droppable({
accept: '.person',
tolerance: 'pointer',
hoverClass: 'trashcan-hover',
activeClass: 'trashcan-active',
drop: onTrashCanned
});
}
$(document).ready(function(){
initDragging();
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function()
{
initDragging();
});
});
function onTrashCanned(e,ui)
{
var id = $('input[id$=hidID]', ui.draggable).val();
if (id != undefined)
{
$('#hidTrashcanID').val(id);
__doPostBack('btnTrashcan','');
}
}
</code></pre>
<p>When the page posts back, partially updating the UpdatePanel's content, I rebind the draggables and droppables. When I then grab a draggable with my cursor, I get an "htmlfile: Unspecified error." exception. I can resolve this problem in the jQuery library by replacing <code>elem.offsetParent</code> with calls to this function that I wrote:</p>
<pre><code>function IESafeOffsetParent(elem)
{
try
{
return elem.offsetParent;
}
catch(e)
{
return document.body;
}
}
</code></pre>
<p>I also have to avoid calls to elem.getBoundingClientRect() as it throws the same error. For those interested, I only had to make these changes in the <code>jQuery.fn.offset</code> function in the <a href="http://plugins.jquery.com/project/dimensions" rel="nofollow noreferrer">Dimensions Plugin</a>.</p>
<p>My questions are: </p>
<ul>
<li>Although this works, are there better ways (cleaner; better performance; without having to modify the jQuery library) to solve this problem?</li>
<li>If not, what's the best way to manage keeping my changes in sync when I update the jQuery libraries in the future? For, example can I extend the library somewhere other than just inline in the files that I download from the jQuery website.</li>
</ul>
<p><b>Update:</b></p>
<p>@some It's not publicly accessible, but I will see if SO will let me post the relevant code into this answer. Just create an ASP.NET Web Application (name it <b>DragAndDrop</b>) and create these files. Don't forget to set Complex.aspx as your start page. You'll also need to download the <a href="http://ui.jquery.com/download_builder/" rel="nofollow noreferrer">jQuery UI drag and drop plug in</a> as well as <a href="http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.2.6.js" rel="nofollow noreferrer">jQuery core</a></p>
<p><b>Complex.aspx</b></p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Complex.aspx.cs" Inherits="DragAndDrop.Complex" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery-ui-personalized-1.5.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
function initDragging()
{
$(".person").draggable({helper:'clone'});
$("#trashcan").droppable({
accept: '.person',
tolerance: 'pointer',
hoverClass: 'trashcan-hover',
activeClass: 'trashcan-active',
drop: onTrashCanned
});
}
$(document).ready(function(){
initDragging();
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function()
{
initDragging();
});
});
function onTrashCanned(e,ui)
{
var id = $('input[id$=hidID]', ui.draggable).val();
if (id != undefined)
{
$('#hidTrashcanID').val(id);
__doPostBack('btnTrashcan','');
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="updContent" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:LinkButton ID="btnTrashcan" Text="trashcan" runat="server" CommandName="trashcan"
onclick="btnTrashcan_Click" style="display:none;"></asp:LinkButton>
<input type="hidden" id="hidTrashcanID" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
<table>
<tr>
<td style="width: 300px;">
<asp:DataList ID="lstAllPeople" runat="server" DataSourceID="odsAllPeople"
DataKeyField="ID">
<ItemTemplate>
<div class="person">
<asp:HiddenField ID="hidID" runat="server" Value='<%# Eval("ID") %>' />
Name:
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
<br />
<br />
</div>
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSource ID="odsAllPeople" runat="server" SelectMethod="SelectAllPeople"
TypeName="DragAndDrop.Complex+DataAccess"
onselecting="odsAllPeople_Selecting">
<SelectParameters>
<asp:Parameter Name="filter" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
</td>
<td style="width: 300px;vertical-align:top;">
<div id="trashcan">
drop here to delete
</div>
<asp:DataList ID="lstPeopleToDelete" runat="server"
DataSourceID="odsPeopleToDelete">
<ItemTemplate>
ID:
<asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
<br />
Name:
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSource ID="odsPeopleToDelete" runat="server"
onselecting="odsPeopleToDelete_Selecting" SelectMethod="GetDeleteList"
TypeName="DragAndDrop.Complex+DataAccess">
<SelectParameters>
<asp:Parameter Name="list" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
</code></pre>
<p><b>Complex.aspx.cs</b></p>
<pre><code>namespace DragAndDrop
{
public partial class Complex : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected List<int> DeleteList
{
get
{
if (ViewState["dl"] == null)
{
List<int> dl = new List<int>();
ViewState["dl"] = dl;
return dl;
}
else
{
return (List<int>)ViewState["dl"];
}
}
}
public class DataAccess
{
public IEnumerable<Person> SelectAllPeople(IEnumerable<int> filter)
{
return Database.SelectAll().Where(p => !filter.Contains(p.ID));
}
public IEnumerable<Person> GetDeleteList(IEnumerable<int> list)
{
return Database.SelectAll().Where(p => list.Contains(p.ID));
}
}
protected void odsAllPeople_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["filter"] = this.DeleteList;
}
protected void odsPeopleToDelete_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["list"] = this.DeleteList;
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (int id in DeleteList)
{
Database.DeletePerson(id);
}
DeleteList.Clear();
lstAllPeople.DataBind();
lstPeopleToDelete.DataBind();
}
protected void btnTrashcan_Click(object sender, EventArgs e)
{
int id = int.Parse(hidTrashcanID.Value);
DeleteList.Add(id);
lstAllPeople.DataBind();
lstPeopleToDelete.DataBind();
}
}
}
</code></pre>
<p><b>Database.cs</b></p>
<pre><code>namespace DragAndDrop
{
public static class Database
{
private static Dictionary<int, Person> _people = new Dictionary<int,Person>();
static Database()
{
Person[] people = new Person[]
{
new Person("Chad")
, new Person("Carrie")
, new Person("Richard")
, new Person("Ron")
};
foreach (Person p in people)
{
_people.Add(p.ID, p);
}
}
public static IEnumerable<Person> SelectAll()
{
return _people.Values;
}
public static void DeletePerson(int id)
{
if (_people.ContainsKey(id))
{
_people.Remove(id);
}
}
public static Person CreatePerson(string name)
{
Person p = new Person(name);
_people.Add(p.ID, p);
return p;
}
}
public class Person
{
private static int _curID = 1;
public int ID { get; set; }
public string Name { get; set; }
public Person()
{
ID = _curID++;
}
public Person(string name)
: this()
{
Name = name;
}
}
}
</code></pre>
| [
{
"answer_id": 516534,
"author": "CodeChef",
"author_id": 21786,
"author_profile": "https://Stackoverflow.com/users/21786",
"pm_score": 4,
"selected": true,
"text": "function IESafeOffsetParent(elem)\n{\n try\n {\n return elem.offsetParent;\n }\n catch(e)\n { \n return document.body;\n }\n}\n\n// The Offset Method\n// Originally By Brandon Aaron, part of the Dimension Plugin\n// http://jquery.com/plugins/project/dimensions\njQuery.fn.offset = function() {\n/// <summary>\n/// Gets the current offset of the first matched element relative to the viewport.\n/// </summary>\n/// <returns type=\"Object\">An object with two Integer properties, 'top' and 'left'.</returns>\n\nvar left = 0, top = 0, elem = this[0], results;\n\nif ( elem ) with ( jQuery.browser ) {\n var parent = elem.parentNode,\n offsetChild = elem,\n offsetParent = IESafeOffsetParent(elem),\n doc = elem.ownerDocument,\n safari2 = safari && parseInt(version) < 522 && !/adobeair/i.test(userAgent),\n css = jQuery.curCSS,\n fixed = css(elem, \"position\") == \"fixed\";\n\n // Use getBoundingClientRect if available\n if (false && elem.getBoundingClientRect) {\n var box = elem.getBoundingClientRect();\n\n // Add the document scroll offsets\n add(box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),\n box.top + Math.max(doc.documentElement.scrollTop, doc.body.scrollTop));\n\n // IE adds the HTML element's border, by default it is medium which is 2px\n // IE 6 and 7 quirks mode the border width is overwritable by the following css html { border: 0; }\n // IE 7 standards mode, the border is always 2px\n // This border/offset is typically represented by the clientLeft and clientTop properties\n // However, in IE6 and 7 quirks mode the clientLeft and clientTop properties are not updated when overwriting it via CSS\n // Therefore this method will be off by 2px in IE while in quirksmode\n add( -doc.documentElement.clientLeft, -doc.documentElement.clientTop );\n\n // Otherwise loop through the offsetParents and parentNodes\n } else {\n\n // Initial element offsets\n add( elem.offsetLeft, elem.offsetTop );\n\n // Get parent offsets\n while ( offsetParent ) {\n // Add offsetParent offsets\n add( offsetParent.offsetLeft, offsetParent.offsetTop );\n\n // Mozilla and Safari > 2 does not include the border on offset parents\n // However Mozilla adds the border for table or table cells\n if ( mozilla && !/^t(able|d|h)$/i.test(offsetParent.tagName) || safari && !safari2 )\n border( offsetParent );\n\n // Add the document scroll offsets if position is fixed on any offsetParent\n if ( !fixed && css(offsetParent, \"position\") == \"fixed\" )\n fixed = true;\n\n // Set offsetChild to previous offsetParent unless it is the body element\n offsetChild = /^body$/i.test(offsetParent.tagName) ? offsetChild : offsetParent;\n // Get next offsetParent\n offsetParent = offsetParent.offsetParent;\n }\n\n // Get parent scroll offsets\n while ( parent && parent.tagName && !/^body|html$/i.test(parent.tagName) ) {\n // Remove parent scroll UNLESS that parent is inline or a table to work around Opera inline/table scrollLeft/Top bug\n if ( !/^inline|table.*$/i.test(css(parent, \"display\")) )\n // Subtract parent scroll offsets\n add( -parent.scrollLeft, -parent.scrollTop );\n\n // Mozilla does not add the border for a parent that has overflow != visible\n if ( mozilla && css(parent, \"overflow\") != \"visible\" )\n border( parent );\n\n // Get next parent\n parent = parent.parentNode;\n }\n\n // Safari <= 2 doubles body offsets with a fixed position element/offsetParent or absolutely positioned offsetChild\n // Mozilla doubles body offsets with a non-absolutely positioned offsetChild\n if ( (safari2 && (fixed || css(offsetChild, \"position\") == \"absolute\")) ||\n (mozilla && css(offsetChild, \"position\") != \"absolute\") )\n add( -doc.body.offsetLeft, -doc.body.offsetTop );\n\n // Add the document scroll offsets if position is fixed\n if ( fixed )\n add(Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),\n Math.max(doc.documentElement.scrollTop, doc.body.scrollTop));\n }\n\n // Return an object with top and left properties\n results = { top: top, left: left };\n}\n\nfunction border(elem) {\n /// <summary>\n /// This method is internal.\n /// </summary>\n /// <private />\n add( jQuery.curCSS(elem, \"borderLeftWidth\", true), jQuery.curCSS(elem, \"borderTopWidth\", true) );\n}\n\nfunction add(l, t) {\n /// <summary>\n /// This method is internal.\n /// </summary>\n /// <private />\n left += parseInt(l, 10) || 0;\n top += parseInt(t, 10) || 0;\n}\n\nreturn results;\n};\n"
},
{
"answer_id": 3021835,
"author": "Raghunathan",
"author_id": 364427,
"author_profile": "https://Stackoverflow.com/users/364427",
"pm_score": 1,
"selected": false,
"text": "var box = elem.getBoundingClientRect(), \nvar box = null;\ntry \n{\n box = elem.getBoundingClientRect();\n}\ncatch(e)\n{\n box = { top : elem.offsetTop, left : elem.offsetLeft } ;\n}\n"
},
{
"answer_id": 3056713,
"author": "Dilbert",
"author_id": 368620,
"author_profile": "https://Stackoverflow.com/users/368620",
"pm_score": 1,
"selected": false,
"text": "var box = null; \ntry { \n box = elem.getBoundingClientRect(); \n} catch(e) { \n box = { \n top : elem.offsetTop, \n left : elem.offsetLeft \n }; \n}\n"
},
{
"answer_id": 3702881,
"author": "Dejan nenov",
"author_id": 446592,
"author_profile": "https://Stackoverflow.com/users/446592",
"pm_score": 2,
"selected": false,
"text": "var d=b.getBoundingClientRect(),\n var d = null; \ntry { d = b.getBoundingClientRect(); }\ncatch(e) { d = { top : b.offsetTop, left : b.offsetLeft } ; }\n"
},
{
"answer_id": 3707537,
"author": "Konstantin",
"author_id": 447162,
"author_profile": "https://Stackoverflow.com/users/447162",
"pm_score": 1,
"selected": false,
"text": "function getOffsetSum(elem) {\n var top = 0, left = 0\n while (elem) {\n top = top + parseInt(elem.offsetTop)\n left = left + parseInt(elem.offsetLeft)\n try {\n elem = elem.offsetParent\n }\n catch (e) {\n return { top: top, left: left }\n }\n }\n return { top: top, left: left }\n};\n var box = this[0].getBoundingClientRect()\n var box = getOffsetSum(this[0])\n"
},
{
"answer_id": 10483390,
"author": "nelsonpecora",
"author_id": 516719,
"author_profile": "https://Stackoverflow.com/users/516719",
"pm_score": 1,
"selected": false,
"text": "element.getBoundingClientRect() ...\nif(el != bd){\n hasAbsolute = fly(el).isStyle(\"position\", \"absolute\");\n\n if (el.getBoundingClientRect) {\n b = el.getBoundingClientRect();\n scroll = fly(document).getScroll();\n ret = [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)];\n } else {\n...\n ...\nif(el != bd){\n hasAbsolute = fly(el).isStyle(\"position\", \"absolute\");\n\n if (el.getBoundingClientRect) {\n try {\n b = el.getBoundingClientRect();\n scroll = fly(document).getScroll();\n ret = [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)];\n } catch(e) {\n ret = [0,0];\n }\n } else {\n...\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21786/"
] |
371,471 | <p>I am trying to get some <code>JavaScript</code> to programmatically adjust a HTML <code>img</code> tag's width to display various sized images correctly.</p>
<p>I have a fixed width <code>img</code> tag at <code>800px</code> to display an image, this is the max width.</p>
<p>If the image is wider then <code>800px</code> I want to display it at <code>800px</code> wide;</p>
<p>If the image is less than <code>800px</code> wide I want to preserve its width to avoid stretching it.</p>
<p>I use this html/javacript code to get a partial solution:</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-js lang-js prettyprint-override"><code>function resize_image(id) {
var img = document.getElementById(id);
var normal_width = img.width;
img.removeAttribute("width");
var real_width = img.width;
if (real_width < normal_width) {
img.width = real_width;
} else {
img.width = normal_width;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="myimage" onload="resize_image(self.id);" src="https://via.placeholder.com/350x150" width="800" /></code></pre>
</div>
</div>
</p>
<p>The above code seems to work on all browsers I have tested except <code>Safari</code> (images don't display unless you refresh the page).</p>
<p>I know I can use CSS <code>max-width</code> but that wont work on <code>IE</code> < 7 which is a show stopper.</p>
<p>How can I get this working for all browsers? Many thanks in advance.</p>
| [
{
"answer_id": 371504,
"author": "bezmax",
"author_id": 43677,
"author_profile": "https://Stackoverflow.com/users/43677",
"pm_score": 2,
"selected": false,
"text": ".dynamic_img {\n width: expression(document.body.clientWidth <= 800? \"auto\" : \"800px\");\n max-width: 800px; //For normal browsers\n}\n"
},
{
"answer_id": 371509,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "img.style.width"
},
{
"answer_id": 371564,
"author": "bezmax",
"author_id": 43677,
"author_profile": "https://Stackoverflow.com/users/43677",
"pm_score": 3,
"selected": true,
"text": "onload=\"resize_image(self.id);return true\"\n"
},
{
"answer_id": 2380407,
"author": "mroztn",
"author_id": 211541,
"author_profile": "https://Stackoverflow.com/users/211541",
"pm_score": 1,
"selected": false,
"text": "...\n function resize_image( img )\n {\n //var img = document.getElementById( id );\n...\n <img onload=\"resize_image(this);\" src=\"IMAGE.JPG\" width=\"800\" />\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14260/"
] |
371,490 | <p>Does anyone know how to turn this string: "Smith, John R"<br>
Into this string: "jsmith" ?</p>
<p>I need to lowercase everything with lower()<br>
Find where the comma is and track it's integer location value<br>
Get the first character after that comma and put it in front of the string<br>
Then get the entire last name and stick it after the first initial.<br><br>
Sidenote - instr() function is not compatible with my version<br><br>
Thanks for any help!</p>
| [
{
"answer_id": 386658,
"author": "Gabe",
"author_id": 48143,
"author_profile": "https://Stackoverflow.com/users/48143",
"pm_score": 1,
"selected": false,
"text": "with name_list as\n (select ' Parisi, Kenneth R' name from dual)\nselect name\n -- There may be a space after the comma. This will strip an arbitrary\n -- amount of whitespace from the first name, so we can easily extract\n -- the first initial.\n , substr(trim(substr(name, instr(name, ',') + 1)), 1, 1) AS first_init\n -- a simple substring function, from the first character until the\n -- last character before the comma.\n , substr(trim(name), 1, instr(trim(name), ',') - 1) AS last_name\n -- put together what we have done above to create the output field \n , lower(substr(trim(substr(name, instr(name, ',') + 1)), 1, 1)) ||\n lower(substr(trim(name), 1, instr(trim(name), ',') - 1)) AS init_plus_last\n from name_list; \n"
},
{
"answer_id": 407654,
"author": "Stew S",
"author_id": 50943,
"author_profile": "https://Stackoverflow.com/users/50943",
"pm_score": 2,
"selected": false,
"text": "SELECT LOWER(regexp_replace('Smith, John R', \n '(.+)(, )([A-Z])(.+)', \n '\\3\\1', 1, 1)) \n FROM DUAL;\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42229/"
] |
371,497 | <p>Is there any way (in Javascript) to download a remote website (i.e. like with Curl), read it into a string variable and further process it?</p>
| [
{
"answer_id": 371524,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": " var xhReq = createXMLHttpRequest();\n xhReq.open(\"GET\", \"page.html\", true);\n xhReq.onreadystatechange = onResponse;\n xhReq.send(null);\n ...\n function onResponse() {\n if (xhReq.readyState != 4) { return; }\n var serverResponse = xhReq.responseText;\n ...\n }\n"
},
{
"answer_id": 371542,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 1,
"selected": false,
"text": "\nvar xmlhttp = new XMLHttpRequest();\nxmlhttp.open(\"POST\",\"http://localhost/proxy.php?url=http://google.com\", true);\nxmlhttp.onreadystatechange = function() {\n if (request.readyState == 4 && request.status == 200) {\n // ensure we have a response...\n if (xmlhttp.responseText) {\n var html = xmlhttp.responseText;\n // do your processing here...\n }\n }\n};\nxmlhttp.send();\n \n<?php\n\n// proxy.php\n\n$ch = curl_init();\n\ncurl_setopt($ch, CURLOPT_URL,$_GET[\"url\"]);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER,1);\n$result=curl_exec ($ch);\ncurl_close ($ch);\necho $result;\n\n?>\n\n"
},
{
"answer_id": 371760,
"author": "pottedmeat",
"author_id": 2120,
"author_profile": "https://Stackoverflow.com/users/2120",
"pm_score": 0,
"selected": false,
"text": "select * from html where url=\"http://google.com\" and xpath='/html' limit 1\n"
},
{
"answer_id": 371907,
"author": "Rik Heywood",
"author_id": 4012,
"author_profile": "https://Stackoverflow.com/users/4012",
"pm_score": 0,
"selected": false,
"text": "$.getJSON(\"http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?\",\n function(data){\n $.each(data.items, function(i,item){\n $(\"<img/>\").attr(\"src\", item.media.m).appendTo(\"#images\");\n if ( i == 4 ) return false;\n });\n });\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,503 | <p>Why is ++i is l-value and i++ not?</p>
| [
{
"answer_id": 371533,
"author": "Renaud Bompuis",
"author_id": 3811,
"author_profile": "https://Stackoverflow.com/users/3811",
"pm_score": 2,
"selected": false,
"text": "C ++i i++ C++ i++ ++i ++i i += 1 i = i + 1 i int i = 0;\n++i = 3; \n// is understood as\ni = i + 1; // i now equals 1\ni = 3;\n i++ i i int i = 0;\ni++ = 3; \n// would be understood as \n0 = 3 // Wrong!\ni = i + 1;\n"
},
{
"answer_id": 371540,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": -1,
"selected": false,
"text": "public void test(int n)\n{\n Console.WriteLine(n++);\n Console.WriteLine(++n);\n}\n\n/* Output:\nn\nn+2\n*/\n"
},
{
"answer_id": 371547,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "class Node // Simple Example\n{\n /*\n * Pre-Increment:\n * To make the result non-mutable return an object\n */\n Node operator++(int)\n {\n Node result(*this); // Make a copy\n operator++(); // Define Post increment in terms of Pre-Increment\n\n return result; // return the copy (which looks like the original)\n }\n\n /*\n * Post-Increment:\n * To make the result an l-value return a reference to this object\n */\n Node& operator++()\n {\n /*\n * Update the state appropriatetly */\n return *this;\n }\n};\n"
},
{
"answer_id": 371553,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "i++ = 2;\n ++i = 2;\n for(int i=0; i<limit; i++)\n...\n for(int i=0; i<limit; ++i)\n...\n int i = 0;\nint a = i++;\n int i = 0;\nint a = ++i;\n"
},
{
"answer_id": 371574,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 5,
"selected": false,
"text": "i++ i++ = 5;\ni + 0 = 5;\n ++i"
},
{
"answer_id": 371669,
"author": "Nietzche-jou",
"author_id": 39892,
"author_profile": "https://Stackoverflow.com/users/39892",
"pm_score": 3,
"selected": false,
"text": "++i i ++i = 10 i"
},
{
"answer_id": 374151,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": true,
"text": "++i int v = 0;\nint const & rcv = ++v; // would work if ++v is an rvalue too\nint & rv = ++v; // would not work if ++v is an rvalue\n void taking_refc(int const& v);\ntaking_refc(10); // valid, 10 is an rvalue though!\n i++ i i++ ++i i int a = ++i; int &a = ++i; rvalue references Object& Object Object o1(++a); // lvalue => can't steal. It will deep copy.\nObject o2(a++); // rvalue => steal resources (like just swapping pointers)\n"
},
{
"answer_id": 51429451,
"author": "Galaxy",
"author_id": 5500589,
"author_profile": "https://Stackoverflow.com/users/5500589",
"pm_score": 0,
"selected": false,
"text": "a++ a a a a a a (5 + a) * b for (int i = 0; i != 5; i++) {...}\n i++ i i mov i, eax\ninc i\n eax i i ++a a a a a a a a a a++ ++a ++a a a++"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
371,513 | <p>We have a database that persist our metadata and data.</p>
<p>Our metadata is produced buy a dedicated team, using a Web application on the development server, and is a critical part of our application.</p>
<p>Then the customer generates data according to this metadata.</p>
<p>We already version the database schema, and all schema change. The next step is to put our metadata under version control.</p>
Naive solution
<p>A naive solution would be to dump all the metadata, and commit it under version control before generating the corresponding packages. Since it's a dump, it can easily be restored. But there is probably a better way, like an incremental solution (only version diffs).</p>
Text dumps
<p>Another solution is to export all metadata tables in text format (like XML), and then version those text files. But then you have to find a way to reimport them.</p>
<p>So, is your metadata under version control? Why? How?</p>
| [
{
"answer_id": 371533,
"author": "Renaud Bompuis",
"author_id": 3811,
"author_profile": "https://Stackoverflow.com/users/3811",
"pm_score": 2,
"selected": false,
"text": "C ++i i++ C++ i++ ++i ++i i += 1 i = i + 1 i int i = 0;\n++i = 3; \n// is understood as\ni = i + 1; // i now equals 1\ni = 3;\n i++ i i int i = 0;\ni++ = 3; \n// would be understood as \n0 = 3 // Wrong!\ni = i + 1;\n"
},
{
"answer_id": 371540,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": -1,
"selected": false,
"text": "public void test(int n)\n{\n Console.WriteLine(n++);\n Console.WriteLine(++n);\n}\n\n/* Output:\nn\nn+2\n*/\n"
},
{
"answer_id": 371547,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "class Node // Simple Example\n{\n /*\n * Pre-Increment:\n * To make the result non-mutable return an object\n */\n Node operator++(int)\n {\n Node result(*this); // Make a copy\n operator++(); // Define Post increment in terms of Pre-Increment\n\n return result; // return the copy (which looks like the original)\n }\n\n /*\n * Post-Increment:\n * To make the result an l-value return a reference to this object\n */\n Node& operator++()\n {\n /*\n * Update the state appropriatetly */\n return *this;\n }\n};\n"
},
{
"answer_id": 371553,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "i++ = 2;\n ++i = 2;\n for(int i=0; i<limit; i++)\n...\n for(int i=0; i<limit; ++i)\n...\n int i = 0;\nint a = i++;\n int i = 0;\nint a = ++i;\n"
},
{
"answer_id": 371574,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 5,
"selected": false,
"text": "i++ i++ = 5;\ni + 0 = 5;\n ++i"
},
{
"answer_id": 371669,
"author": "Nietzche-jou",
"author_id": 39892,
"author_profile": "https://Stackoverflow.com/users/39892",
"pm_score": 3,
"selected": false,
"text": "++i i ++i = 10 i"
},
{
"answer_id": 374151,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": true,
"text": "++i int v = 0;\nint const & rcv = ++v; // would work if ++v is an rvalue too\nint & rv = ++v; // would not work if ++v is an rvalue\n void taking_refc(int const& v);\ntaking_refc(10); // valid, 10 is an rvalue though!\n i++ i i++ ++i i int a = ++i; int &a = ++i; rvalue references Object& Object Object o1(++a); // lvalue => can't steal. It will deep copy.\nObject o2(a++); // rvalue => steal resources (like just swapping pointers)\n"
},
{
"answer_id": 51429451,
"author": "Galaxy",
"author_id": 5500589,
"author_profile": "https://Stackoverflow.com/users/5500589",
"pm_score": 0,
"selected": false,
"text": "a++ a a a a a a (5 + a) * b for (int i = 0; i != 5; i++) {...}\n i++ i i mov i, eax\ninc i\n eax i i ++a a a a a a a a a a++ ++a ++a a a++"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] |
371,534 | <p>I'm running into an issue with an ASP.NET 2.0 application. Our network folks just upped our security, and now I get the floowing error whenever I try to access the app:</p>
<blockquote>
<p>"This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms."</p>
</blockquote>
<p>I've done a little research, and it sounds like ASP.NET uses the RijndaelManaged AES encryption algorithm to encrypt the ViewState of pages... and RijndaelManaged is on the list of algorithms that aren't FIPS compliant. We're certainly not explicitly calling <em>any</em> encryption algorithm... much less anything on the non-compliant list. </p>
<p>This ViewState business makes sense to me, I guess. The thing I can't muddle out, though, is what to do about it. I've found a <a href="http://support.microsoft.com/kb/911722" rel="noreferrer">KB article</a> that suggests using a web.config setting to specify a different algorithm... but either that didn't stick, or that algorithm isn't up to snuff, either.</p>
<p>So: </p>
<p>1) Is the RijndaelManaged / ViewState thing actually the problem? Or am I barking up the wrong tree?</p>
<p>2) How to I specify what algorithm to use instead of RijndaelManaged? I've got a list of algorithms that are and aren't compliant; I'm just not sure where to plug that information in.</p>
<p>Thanks!</p>
<p>Richard</p>
| [
{
"answer_id": 380866,
"author": "kay.herzam",
"author_id": 47093,
"author_profile": "https://Stackoverflow.com/users/47093",
"pm_score": 2,
"selected": false,
"text": "<machineKey \n validationKey=\"AutoGenerate,IsolateApps\"\n decryptionKey=\"AutoGenerate,IsolateApps\"\n validation=\"3DES\"\n decryption=\"3DES\"/>\n"
},
{
"answer_id": 1618641,
"author": "Paul Alexander",
"author_id": 76456,
"author_profile": "https://Stackoverflow.com/users/76456",
"pm_score": 3,
"selected": false,
"text": "<compilation debug=\"true\" />"
},
{
"answer_id": 2910317,
"author": "WWC",
"author_id": 311749,
"author_profile": "https://Stackoverflow.com/users/311749",
"pm_score": 2,
"selected": false,
"text": "<configuration> \n\n <runtime>\n <enforceFIPSPolicy enabled=\"false\"/>\n </runtime>\n <configuration>\n<system.web>\n <authentication mode=\"Windows\" />\n <machineKey decryption=\"3DES\" decryptionKey=\"AutoGenerate,IsolateApps\" validation=\"SHA1\" validationKey=\"AutoGenerate,IsolateApps\" />\n</system.web>\n</configuration>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46692/"
] |
371,546 | <pre><code>select Table1.colID, Table1.colName,
(select * from Table2 where Table2.colID = Table1.colID) as NestedRows
from Table1
</code></pre>
<p>The above query gives you this error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used..... </p>
<p>Can anybody explain why this limitation exist? </p>
<p>I had this idea that this kind of multidimentional queries would be nice for building OO objects directly from the database with 1 query</p>
<p>EDIT:</p>
<p>This question is pretty theoretical. To solve this practical I would use a join or simply done 2 queries, but I wondered if there was anything stopping you from returning a column as a table type (In sql server 2008 you can create table types).</p>
<p>Say you have corrensponding classes in code, think Linq2Sql</p>
<pre><code>public class Table1
{
public int colID,
public string colName,
public List<Table2> table2s;
}
</code></pre>
<p>I would like to be able to fill instances of this class directly with 1 query</p>
| [
{
"answer_id": 371575,
"author": "DCNYAM",
"author_id": 30419,
"author_profile": "https://Stackoverflow.com/users/30419",
"pm_score": 0,
"selected": false,
"text": "SELECT tab1.colID, tab1.colName, tab2.Column1, tab2.column2\nFROM dbo.Table1 AS tab1\n INNER JOIN dbo.Table2 AS tab2\n ON tab1.colID = tab2.colID\n"
},
{
"answer_id": 371584,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 0,
"selected": false,
"text": "select Table1.colID, Table1.colName,Table2.*\nfrom Table1 inner join Table2 ON Table1.colID = Table2.colID\n"
},
{
"answer_id": 371619,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 2,
"selected": false,
"text": "select Table1.colID, Table1.colName, Table2.*\nfrom Table1\n Inner Join Table2\n On Table1.ColId = Table2.ColId\nOrder By Table1.ColId\nFor XML Auto\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29519/"
] |
371,551 | <p>When I try to build my projects in Visual Studio 2008, web sites won't build anymore, they hang on this stage: </p>
<pre><code>------ Build started: Project: C:\...\Web\, Configuration: Debug Any CPU ------
Validating Web Site
Building directory '/Web/Admin/Secure/'.
Building directory '/Web/Admin/'.
Building directory '/Web/Students/'.
Building directory '/Web/'.
Validation Complete
</code></pre>
<p>And I have to cancel it as it doesn't complete even after leaving it for an hour. Does anyone have any ideas on what's going on? Class libraries build fine.</p>
| [
{
"answer_id": 371655,
"author": "NikolaiDante",
"author_id": 39643,
"author_profile": "https://Stackoverflow.com/users/39643",
"pm_score": 3,
"selected": false,
"text": "C:\\WINDOWS\\Microsoft.NET\\Framework\\<Framework Version>\\Temporary ASP.NET Files\n"
},
{
"answer_id": 11958397,
"author": "Jim Lahman",
"author_id": 584962,
"author_profile": "https://Stackoverflow.com/users/584962",
"pm_score": -1,
"selected": false,
"text": "regsvr32 \"C:\\Program Files (x86)\\Internet Explorer\\ieproxy.dll\"\n"
},
{
"answer_id": 67804416,
"author": "Paul Rogero",
"author_id": 5632070,
"author_profile": "https://Stackoverflow.com/users/5632070",
"pm_score": 2,
"selected": false,
"text": ".suo .suo .vs .vs old.vs.old"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33137/"
] |
371,554 | <p>I have the following code:</p>
<pre><code>if ($_POST['submit'] == "Next") {
foreach($_POST['info'] as $key => $value) {
echo $value;
}
}
</code></pre>
<p>How do I get the foreach function to start from the 2nd key in the array?</p>
| [
{
"answer_id": 371560,
"author": "Irmantas",
"author_id": 43182,
"author_profile": "https://Stackoverflow.com/users/43182",
"pm_score": 2,
"selected": false,
"text": "if ($key == 0) //or whatever\n continue;\n"
},
{
"answer_id": 371563,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 5,
"selected": false,
"text": "foreach(array_slice($_POST['info'], 1) as $key=>$value) {\n echo $value;\n}\n $isFirst = true;\nforeach($_POST['info'] as $key=>$value) {\n if ($isFirst) {\n $isFirst = false;\n continue;\n } \n echo $value;\n}\n"
},
{
"answer_id": 371566,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 8,
"selected": true,
"text": "foreach(array_slice($_POST['info'],1) as $key=>$value)\n{\n echo $value;\n}\n"
},
{
"answer_id": 372122,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\n\nforeach($_POST['info'] as $key=>$value) {\n if ($key == 0) { //or what ever the first key you're using is\n continue;\n } else { \n echo $value;\n }\n}\n"
},
{
"answer_id": 372155,
"author": "Sean McSomething",
"author_id": 39413,
"author_profile": "https://Stackoverflow.com/users/39413",
"pm_score": 3,
"selected": false,
"text": "foreach (array_slice($ome_array, 1) as $k => $v {... unset continue"
},
{
"answer_id": 373811,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " <input type='text' name='quiz[first]' value=\"\"/>\n <input type='text' name='quiz[second]' value=\"\"/>\n if( isset($_POST['quiz']) AND \n is_array($_POST['quiz'])) {\n\n //...and we'll skip $_POST['quiz']['first'] \n foreach($_POST['quiz'] as $key => $val){\n if($key == \"first\") continue;\n print $val; \n }\n}\n"
},
{
"answer_id": 376157,
"author": "alexn",
"author_id": 41596,
"author_profile": "https://Stackoverflow.com/users/41596",
"pm_score": 1,
"selected": false,
"text": "<?php\nfunction slice($a)\n{\n foreach(array_slice($a, 1) as $key)\n {\n\n }\n\n return true;\n}\n\nfunction skip($a)\n{\n $first = false;\n\n foreach($a as $key)\n {\n if($first)\n {\n $first = false;\n continue;\n }\n }\n\n return true;\n}\n\n$array = array_fill(0, 1000, 'test');\n\n$t1 = time() + microtime(true);\n\nfor ($i = 0; $i < 1000; $i++)\n{\n slice($array);\n}\n\nvar_dump((time() + microtime(true)) - $t1);\n\necho '<hr />';\n\n$t2 = time() + microtime(true);\n\nfor ($i = 0; $i < 1000; $i++)\n{\n skip($array);\n}\n\nvar_dump((time() + microtime(true)) - $t2);\n?>\n"
},
{
"answer_id": 376568,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 2,
"selected": false,
"text": "array_shift() reset($a);\nunset(key($a));\n"
},
{
"answer_id": 2870917,
"author": "bobobobo",
"author_id": 111307,
"author_profile": "https://Stackoverflow.com/users/111307",
"pm_score": 0,
"selected": false,
"text": "key() current() array_shift() array_shift()"
},
{
"answer_id": 5484409,
"author": "Organic SEO Services",
"author_id": 683638,
"author_profile": "https://Stackoverflow.com/users/683638",
"pm_score": 5,
"selected": false,
"text": "unset($array[0]);\n"
},
{
"answer_id": 13899798,
"author": "zb'",
"author_id": 815386,
"author_profile": "https://Stackoverflow.com/users/815386",
"pm_score": 2,
"selected": false,
"text": "reset($_POST['info']); //set pointer to zero\nwhile ($value=next($_POST['info']) //ponter+1, return value\n{\n echo key($_POST['info']).\":\".$value.\"\\n\";\n}\n"
},
{
"answer_id": 34945257,
"author": "Dheeraj Verma",
"author_id": 5825937,
"author_profile": "https://Stackoverflow.com/users/5825937",
"pm_score": 1,
"selected": false,
"text": "<?php \n\n$counter = 0;\n\nforeach ($categoriest as $category) { if ($counter++ == 0) continue; ?>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37667/"
] |
371,555 | <p>My team is developing a large java application which extensively queries a MySQL database (in different classes and modules).
I'd like to known if there is a pattern that allows me to be notified at compile time if there are queries that refer to a wrong table structure (for instance if I remove or add a field on a table and the query string refers to it), in order to prevent runtime errors.
This should work also for JOIN queries.</p>
| [
{
"answer_id": 532425,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "select count(*) from test where name = null\n long count = query.from(test).where(test.name.isnull()).count();\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17934/"
] |
371,571 | <p>I'm running a simple batch file which is generated by a vbscript to delete individual files, however when I execute it, it is deleting entire subdirectories. Anyone have any ideas on this? Below is the batch file. </p>
<pre><code>rem 2008-12-15D:\DP-Production\Administrative\BUSINESS\FileLink
del D:\DP-Production\Administrative\BUSINESS\FileLink\.-1003067260 /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\.-997208891 /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\.-998224323 /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._proofing.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Sample1.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Shortcut (2) to PDFProofs.lnk /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Shortcut to Art.lnk /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Shortcut to Filelink on 'Admin-srv' (I).lnk /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Shortcut to LeadGen program.lnk /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Shortcut to Mail.lnk /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Shortcut to Maintained on 'Data Pro (Pmi41)' (H).lnk /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Shortcut to Openjobs on 'SRV-srv02' (J).lnk /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._SHRP.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._skyphone2.bmp /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Smokey Bones Solo_Mailer.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._steakhouseback.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._steakhousefront.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Summercamp.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._taxsampleback.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._taxsamplefront.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Temporary Items /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Beta.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Trurdy.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Trash /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._trishwenrick.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._Tulane.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._valpak_price.mdb /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\._WasteM.jpg /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\weekly_deletions.vbs /q/f
rem 2008-12-15D:\DP-Production\Administrative\BUSINESS\FileLink\Art
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\._+.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\._0805_NJGolf 12-44-24.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\._806857.eps /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\._ADPLogo.JPG /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\._FranchiseLtr_MM.doc /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\._REPAIR-SMA.doc /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\._Safety.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\._Summer 2008 Donor V1.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Art\desktop.ini /q/f
rem 2008-12-15D:\DP-Production\Administrative\BUSINESS\FileLink\Mail
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\ BOBBSS LIST COUNT - DRIBOX 2008-06 ejs.msg /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\#7608 GHA MD Mailing.ZIP /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\2008 Adel List.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\2008 mailing-BREAK OUT.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\2008 Password Letter to GM (R).doc /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\2008 RL Mailing.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\2008DLRCRICKPage1.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\805026.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\805442_Breakfast.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\806330_Letter.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\806778.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\806785 JONES WORLD VIEW DHL.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\807364-807117.csv /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8522435_INTDELIVERY.zip /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8674252_INTDELIVERY.zip /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8674856_INTDELIVERY.zip /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8675351_INTDELIVERY.zip /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8694521_INTDELIVERY.zip /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8720608_INTDELIVERY.zip /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8cletoy0903_1.csv /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8roncar0657.csv /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\8vanhyu0531.zip /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\addressfile0605.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\All Active Employee Address 070808.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\APPA_Mailing_List-FINAL-XLS4.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\Aug 08 Coupon Data.txt /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\BMA.pdf /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\BODYCOPY.doc /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\BOISE JUNE SALON MASTER LIST rev 6-9-08 (6).xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\Broward Committe REVISED.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\CAW Tournament Letter (2).doc /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\detroit lasalle delete list.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\CHIROPRACTOR 300.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\CMTFV08204macroed.bak /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\Comm Ltr#2.doc /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\Contact Directory.rtf-MA /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\Copy of Jones Newsletter 0708.xls /q/f
del D:\DP-Production\Administrative\BUSINESS\FileLink\Mail\Copy of MD L-Listing 07_11_08.xls /q/f
</code></pre>
| [
{
"answer_id": 371594,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "del D:\\DP-Production\\Administrative\\BUSINESS\\FileLink\\Mail\\ BOBBSS LIST COUNT - DRIBOX 2008-06 ejs.msg /q/\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18853/"
] |
371,591 | <p>I am trying to get simple jQuery to execute on my Content page with no luck below is what I am trying to do:</p>
<pre><code><asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
alert("hi");
});
</script>
</asp:Content>
</code></pre>
<p>I have also tried getting the following to work:</p>
<pre><code><asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
function onload()
{
$("#myDiv").css("border", "1px solid green");
}
</script>
<div id="myDive">
Hello
</div>
</asp:Content>
</code></pre>
| [
{
"answer_id": 371603,
"author": "Kieron",
"author_id": 5791,
"author_profile": "https://Stackoverflow.com/users/5791",
"pm_score": 6,
"selected": true,
"text": "<script src=\"<%= Url.Content (\"~/Scripts/jquery-1.2.6.js\") %>\" type=\"text/javascript\"></script>\n <% if (false) { %>\n <!-- Don't wrap this is a Url.Content call, it's like this so we get intellisense! -->\n <script src=\"../../Scripts/jquery-1.2.6-vsdoc.js\" type=\"text/javascript\"></script>\n<% } %>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3111/"
] |
371,599 | <p>In my app have a window splitted by a QSplitter, and I need to remove an widget. </p>
<p>How can I do that? I can't find useful methods </p>
| [
{
"answer_id": 371649,
"author": "Caleb Huitt - cjhuitt",
"author_id": 9876,
"author_profile": "https://Stackoverflow.com/users/9876",
"pm_score": 2,
"selected": false,
"text": "setParent( NULL )"
},
{
"answer_id": 17196052,
"author": "thrichard",
"author_id": 1506390,
"author_profile": "https://Stackoverflow.com/users/1506390",
"pm_score": 0,
"selected": false,
"text": "frameA->setVisible(conditionA);\nframeB->setVisible(conditionB);\nif ( !(conditionA && conditionB) ) // if only 1 frame is visible\n{\n splitter->handle(0)->setVisible(false);\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39339/"
] |
371,604 | <p>Following on from <a href="https://stackoverflow.com/questions/371418/can-you-represent-csv-data-in-googles-protocol-buffer-format">this</a> question, what would be the best way to represent a System.Decimal object in a Protocol Buffer?</p>
| [
{
"answer_id": 371690,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "message Decimal {\n\n // 96-bit mantissa broken into two chunks\n optional uint64 mantissa_msb = 1;\n optional uint32 mantissa_lsb = 2;\n\n required sint32 exponent_and_sign = 3;\n}\n"
},
{
"answer_id": 371856,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "decimal decimal decimal message Decimal {\n optional uint64 lo = 1; // the first 64 bits of the underlying value\n optional uint32 hi = 2; // the last 32 bis of the underlying value\n optional sint32 signScale = 3; // the number of decimal digits, and the sign\n}\n"
},
{
"answer_id": 56551852,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 1,
"selected": false,
"text": "sint32 message ProtoDecimal {\n sint32 v1 = 1;\n sint32 v2 = 2;\n sint32 v3 = 3;\n sint32 v4 = 4;\n}\n public decimal ConvertToDecimal(AbideDecimal value)\n{\n return new decimal(new int[] { value.V1, value.V2, value.V3, value.V4 });\n}\n\npublic ProtoDecimal ConvertFromDecimal(decimal value)\n{\n var bits = decimal.GetBits(value);\n return new ProtoDecimal \n {\n V1 = bits[0],\n V2 = bits[1],\n V3 = bits[2],\n V4 = bits[3]\n }\n}\n"
},
{
"answer_id": 58478064,
"author": "Bruno Zell",
"author_id": 5185376,
"author_profile": "https://Stackoverflow.com/users/5185376",
"pm_score": 1,
"selected": false,
"text": "2 0.02"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3820/"
] |
371,606 | <p>i am trying to fix a site I am helping a friend with, and in IE it is displaying the navigation bar like it is stacking on top of each other.</p>
<p>Is that a part of the double float bug, I tried adding display:inline, but I still have that problem.</p>
<p>URL: <a href="http://www.flanels.com/RadiantecHOME.html" rel="nofollow noreferrer">http://www.flanels.com/RadiantecHOME.html</a><br>
CSS: <a href="http://www.flanels.com/style.css" rel="nofollow noreferrer">http://www.flanels.com/style.css</a>`</p>
| [
{
"answer_id": 371690,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "message Decimal {\n\n // 96-bit mantissa broken into two chunks\n optional uint64 mantissa_msb = 1;\n optional uint32 mantissa_lsb = 2;\n\n required sint32 exponent_and_sign = 3;\n}\n"
},
{
"answer_id": 371856,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "decimal decimal decimal message Decimal {\n optional uint64 lo = 1; // the first 64 bits of the underlying value\n optional uint32 hi = 2; // the last 32 bis of the underlying value\n optional sint32 signScale = 3; // the number of decimal digits, and the sign\n}\n"
},
{
"answer_id": 56551852,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 1,
"selected": false,
"text": "sint32 message ProtoDecimal {\n sint32 v1 = 1;\n sint32 v2 = 2;\n sint32 v3 = 3;\n sint32 v4 = 4;\n}\n public decimal ConvertToDecimal(AbideDecimal value)\n{\n return new decimal(new int[] { value.V1, value.V2, value.V3, value.V4 });\n}\n\npublic ProtoDecimal ConvertFromDecimal(decimal value)\n{\n var bits = decimal.GetBits(value);\n return new ProtoDecimal \n {\n V1 = bits[0],\n V2 = bits[1],\n V3 = bits[2],\n V4 = bits[3]\n }\n}\n"
},
{
"answer_id": 58478064,
"author": "Bruno Zell",
"author_id": 5185376,
"author_profile": "https://Stackoverflow.com/users/5185376",
"pm_score": 1,
"selected": false,
"text": "2 0.02"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,608 | <p>GCC 3.4.5 (MinGW version) produces a warning: parameter has incomplete type for line 2 of the following C code:</p>
<pre><code>struct s;
typedef void (* func_t)(struct s _this);
struct s { func_t method; int dummy_member; };
</code></pre>
<p>Is there a way to fix this (or at least hide the warning) without changing the method argument's signature to (struct s *)?</p>
<p><strong>Note:</strong> <br>
As to why something like this would be useful: I'm currently tinkering with an object-oriented framework; 'method' is an entry in a dispatch table and because of the particular design of the framework, it makes sense to pass '_this' by value and not by reference (as it is usually done)...</p>
| [
{
"answer_id": 371870,
"author": "HUAGHAGUAH",
"author_id": 38809,
"author_profile": "https://Stackoverflow.com/users/38809",
"pm_score": -1,
"selected": false,
"text": "typedef void (*func_t)(void*);\n typedef void (*func_t)(void (*)());\n"
},
{
"answer_id": 371962,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "typedef void (* func_t)(struct s*); // Pointer to struct\ntypedef void (* func_t)(void *); // Eww - this is inferior to above option in every way\ntypedef void (* func_t)(); // Unspecified parameters\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48015/"
] |
371,637 | <p>I am trying to use the following code, which I have not been able to test yet, because I get the following errors:</p>
<pre><code>#!/usr/bin/perl
use warnings;
use strict;
use Text::Wrap;
use Mail::Box::Manager;
use HTML::Obliterate qw(extirpate_html);
open (MYFILE, '>>data.txt');
binmode(MYFILE, ':encoding(UTF-8)');
my $file = shift || $ENV{MAIL};
my $mgr = Mail::Box::Manager->new(
access => 'r',
);
my $folder = $mgr->open( folder => $file )
or die "$file: Unable to open: $!\n";
for my $msg ( sort { $a->timestamp <=> $b->timestamp } $folder->messages)
{
my $to = join( ', ', map { $_->format } $msg->to );
my $from = join( ', ', map { $_->format } $msg->from );
my $date = localtime( $msg->timestamp );
my $subject = $msg->subject;
my $body = $msg->decoded->string;
if ( $msg->isMultipart ) {
foreach my $part ( $msg->parts ) {
if ( $part->contentType eq 'text/html' ) {
my $nohtml = extirpate_html( $msg );
$body =~ s/^>.*$//msg;
$Text::Wrap::columns=80;
print MYFILE wrap("", "", <<"");
\n
From: $from
To: $to
Date: $date
Subject: $subject
\n
$body
}
else {
$body =~ s/^>.*$//msg;
$Text::Wrap::columns=80;
print MYFILE wrap("", "", <<"");
\n
From: $from
To: $to
Date: $date
Subject: $subject
\n
$body
}
}}
</code></pre>
<p>All the braces seem to match up, so I am unsure what the problem is</p>
<pre><code>syntax error at x.pl line 46, near "else"
(Might be a runaway multi-line << string starting on line 36)
Missing right curly or square bracket at x.pl line 63, at end of line
syntax error at x.pl line 63, at EOF
Execution of x.pl aborted due to compilation errors.
</code></pre>
<p>edit:</p>
<p>it now works, but the html is not striped: instead a few emails with stuff like <BR>> <BR>> interlaced throughout, causing it to be many more pages than it should. Is there a better way to do this</p>
| [
{
"answer_id": 371658,
"author": "Tuminoid",
"author_id": 40657,
"author_profile": "https://Stackoverflow.com/users/40657",
"pm_score": 3,
"selected": true,
"text": "print MYFILE wrap(\"\", \"\", <<\"\");\n \"\" else {\n if \"\" (Might be a runaway multi-line << string starting on line 36)\n \"\" }"
},
{
"answer_id": 371772,
"author": "Tuminoid",
"author_id": 40657,
"author_profile": "https://Stackoverflow.com/users/40657",
"pm_score": 1,
"selected": false,
"text": "my $nohtml = extirpate_html( $msg );\n$body =~ s/^>.*$//msg;\n$Text::Wrap::columns=80;\nprint MYFILE wrap(\"\", \"\", <<\"\");\n\\n\nFrom: $from\nTo: $to\nDate: $date\nSubject: $subject\n\\n\n$body\n my $nohtml = extirpate_html( $body );\n$nohtml =~ s/^>.*$//msg;\n $nohtml"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
371,638 | <p>I'm in the design stage for an app which will utilize a REST web service and sort of have a dilemma in as far as using asynchronous vs synchronous vs threading. Here's the scenario.</p>
<p>Say you have three options to drill down into, each one having its own REST-based resource. I can either lazily load each one with a synchronous request, but that'll block the UI and prevent the user from hitting a back navigation button while data is retrieved. This case applies almost anywhere <em>except</em> for when your application requires a login screen. I can't see any reason to use synchronous HTTP requests vs asynchronous because of that reason alone. The only time it makes sense is to have a worker thread make your synchronous request, and notify the main thread when the request is done. This will prevent the block. The question then is bench marking your code and seeing which has more overhead, a threaded synchronous request or an asynchronous request.</p>
<p>The problem with asynchronous requests is you need to either setup a smart notification or delegate system as you can have multiple requests for multiple resources happening at any given time. The other problem with them is if I have a class, say a singleton which is handling all of my data, I can't use asynchronous requests in a getter method. Meaning the following won't go:</p>
<pre><code> - (NSArray *)users {
if(users == nil)
users = do_async_request // NO GOOD
return users;
}
</code></pre>
<p>whereas the following:</p>
<pre><code> - (NSArray *)users {
if(users == nil)
users == do_sync_request // OK.
return users;
}
</code></pre>
<p>You also might have priority. What I mean by priority is if you look at Apple's Mail application on the iPhone, you'll notice they first suck down your entire POP/IMAP tree before making a second request to retrieve the first 2 lines (the default) of your message.</p>
<p>I suppose my question to you experts is this. When are you using asynchronous, synchronous, threads -- and when are you using either async/sync in a thread? What kind of delegation system do you have setup to know what to do when a async request completes? Are you prioritizing your async requests?</p>
<p>There's a gamut of solutions to this all too common problem. It's simple to hack something out. The problem is, I don't want to hack and I want to have something that's simple and easy to maintain.</p>
| [
{
"answer_id": 373906,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": -1,
"selected": false,
"text": "- (NSArray *)users {\n if(users == nil && !didLaunchRequestAlready )\n users = do_async_request // Looks good to me\n return users;\n }\n"
},
{
"answer_id": 12148885,
"author": "Nate Symer",
"author_id": 1207863,
"author_profile": "https://Stackoverflow.com/users/1207863",
"pm_score": 0,
"selected": false,
"text": "- (NSArray *)users {\n if(users == nil) {\n users = do_sync_request();\n }\n\n return users;\n}\n\n// now when calling the users method, do this\n\n- (NSArray *)getUsers {\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n NSArray *users = [self users];\n dispatch_sync(dispatch_get_main_queue(), ^{\n return users;\n }\n }\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
371,644 | <p>In a mysqli prepared statement, a NULL gets turned into '' (in the case of a string) or 0 (in the case of an integer). I would like to store it as a true NULL. Is there any way of doing this?</p>
| [
{
"answer_id": 371782,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "mysqli_stmt::bind_param NULL \"?\" \"NULL\" null function preparse_prepared($sQuery, &$saParams)\n{\n $nPos = 0;\n\n $sRetval = $sQuery;\n foreach ($saParams as $x_Key => $Param)\n {\n //if we find no more ?'s we're done then\n if (($nPos = strpos($sQuery, '?', $nPos + 1)) === false)\n {\n break;\n }\n\n //this test must be done second, because we need to \n //increment offsets of $nPos for each ?.\n //we have no need to parse anything that isn't NULL.\n if (!is_null($Param))\n {\n continue;\n }\n\n\n //null value, replace this ? with NULL.\n $sRetval = substr_replace($sRetval, 'NULL', $nPos, 1);\n\n //unset this element now\n unset($saParams[$x_Key]);\n }\n return $sRetval;\n} \n"
},
{
"answer_id": 1235102,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "bind_param array_shift($myArray)"
},
{
"answer_id": 6892491,
"author": "creatio",
"author_id": 333243,
"author_profile": "https://Stackoverflow.com/users/333243",
"pm_score": 7,
"selected": true,
"text": "<?php\n $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');\n\n // person is some object you have defined earlier\n $name = $person->name();\n $age = $person->age();\n $nickname = ($person->nickname() != '') ? $person->nickname() : NULL;\n\n // prepare the statement\n $stmt = $mysqli->prepare(\"INSERT INTO Name, Age, Nickname VALUES (?, ?, ?)\");\n\n $stmt->bind_param('sis', $name, $age, $nickname);\n?>\n"
},
{
"answer_id": 10340795,
"author": "random_user_name",
"author_id": 870729,
"author_profile": "https://Stackoverflow.com/users/870729",
"pm_score": 5,
"selected": false,
"text": "WHERE <=> <?php\n$price = NULL; // NOTE: no quotes - using php NULL\n$stmt = $mysqli->prepare(\"SELECT id FROM product WHERE price <=> ?\"); // Will select products where the price is null\n$stmt->bind_param($price);\n?>\n"
},
{
"answer_id": 27726456,
"author": "Robert",
"author_id": 2748984,
"author_profile": "https://Stackoverflow.com/users/2748984",
"pm_score": -1,
"selected": false,
"text": "<?php\n$mysqli=new mysqli('localhost','root','','test');\n$mysqli->query(\"CREATE TABLE test_NULL (id int(11))\");\nif($query=$mysqli->prepare(\"insert into test_NULL VALUES(?)\")){\n $query->bind_param('i',$null); //note that $null is undefined\n $query->execute();\n}else{\n echo __LINE__.' '.$mysqli->error;\n}\n?>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902010/"
] |
371,656 | <p>Are there any O/R mappers out there that will automatically create or modify the database schema when you update the business objects? After looking around it seems that most libraries work the other way by creating business object from the database schema.</p>
<p>The reason I'd like to have that capability is that I am planning a product that stores its data in a database on the customer's machine. So I may have to update the database schema when a new version comes out.</p>
<p>Another requirement is that the mapper supports a file based database like SQLite or JET, not only SQL server.</p>
<p>I know XPO from Developer Express has that capability but I was wondering if there are any alternatives out there.</p>
<p>Thanks</p>
| [
{
"answer_id": 374028,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 2,
"selected": true,
"text": "namespace MyApps.Migrations\n{\n public class _001_Initial : Migration\n {\n public override void Up()\n {\n //Execute your upgrade query here\n }\n public override void Down()\n {\n //Execute your downgrade query here\n }\n }\n}\n using System;\nusing System.Collections.Generic;\nusing SubSonic;\nusing SubSonic.Migrations;\n\nnamespace MyApps.Migrations\n{\n internal static class MigrationHelper\n {\n const string NameSpace = \"MyApps.Migrations\";\n private const string SCHEMA_INFO = \"SubSonicSchemaInfo\";\n public static int CurrentVersion { get { return currentVersion; } }\n public static int AppVersion { get { return latestVersion; } }\n public static bool IsUpdateAvailable { get { return (updateVersion.Count > 0); } }\n public static bool IsAppVersionOlder { get; private set; }\n public static bool Checked { get; internal set; }\n private static int currentVersion;\n private static int latestVersion;\n private static List<string> updateVersion;\n private static List<string> availableVersion;\n\n static MigrationHelper()\n {\n Checked = false;\n }\n\n /// <summary>\n /// Migrates the specified migration directory.\n /// </summary>\n public static void CheckForMigration()\n {\n currentVersion = Migrator.GetCurrentVersion(\"YourProviderName\");\n Type[] allTypes =\n System.Reflection.Assembly.GetExecutingAssembly().GetTypes();\n availableVersion = new List<string>();\n foreach (Type type in allTypes)\n {\n if (type.Namespace == NameSpace)\n if (type.Name.Substring(0, 1) == \"_\")\n availableVersion.Add(type.Name);\n }\n\n availableVersion.Sort();\n updateVersion = new List<string>();\n foreach (string s in availableVersion)\n {\n int version = 0;\n if (int.TryParse(s.Substring(1,3), out version))\n {\n if (version > currentVersion)\n {\n updateVersion.Add(s);\n }\n latestVersion = version;\n }\n }\n IsAppVersionOlder = (latestVersion < currentVersion);\n //log.WriteLine(string.Format(\n ///\"CheckForMigration: DbVer = {0}, AppVer = {1}, UpdateAvailable = {2}, IsAppOlder = {3}\",\n //currentVersion, latestVersion, updateVersion.Count, IsAppVersionOlder));\n Checked = true;\n }\n\n internal static void Migrate()\n {\n foreach (string s in updateVersion)\n {\n Migration _migration = (Migration)Activator.CreateInstance(\n System.Reflection.Assembly.GetExecutingAssembly().GetType(\n \"MyApps.Migrations.\" + s));\n _migration.Migrate(\"YourProviderName\", Migration.MigrationDirection.Up);\n IncrementVersion();\n }\n }\n\n private static void IncrementVersion()\n {\n new Update(SCHEMA_INFO, \n \"YourProviderName\").SetExpression(\"version\").EqualTo(\"version+1\").Execute();\n }\n\n }\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46703/"
] |
371,702 | <p>I have made some code which exports some details of a journal article to a reference manager called <a href="http://www.endnote.com/enhome.asp" rel="nofollow noreferrer">Endnote</a></p>
<p>The format of which is a list of items like below (an author):</p>
<pre><code>%A Schortgen Frédérique
</code></pre>
<p>Unfortunately, I am having some encoding problems somewhere, as when endnote opens the file, this is what it makes of the above author:</p>
<blockquote>
<p>Schortge Frédérique</p>
</blockquote>
<p>I have frantically tried playing around with the encoding and stuff that I am outputting and I am at a loss, here is the code:</p>
<pre><code> Response.ContentType = _citation.ContentType;
string fileExtension = "";
if (_citation.GetFileExtension() != null)
fileExtension = "." + _citation.GetFileExtension();
Response.AddHeader("content-disposition", "attachment; filename=citation" + fileExtension);
Response.ContentType = _citation.GetFileReferrer();
Response.Charset = "UTF-8";
Response.write(-snip-);
Response.End();
</code></pre>
| [
{
"answer_id": 374287,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": 0,
"selected": false,
"text": "Response.Charset = \"ISO-8859-1\"; \nResponse.ContentEncoding = System.Text.Encoding.GetEncoding(28591);\nResponse.HeaderEncoding = System.Text.Encoding.GetEncoding(28591);\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3193/"
] |
371,708 | <p>I have two classes that each need an instance of each other to function. Ordinarily if an object needs another object to run, I like to pass it in the constructor. But I can't do that in this case, because one object has to be instantiated before the other, and so therefore the second object does not exist to be passed to the first object's constructor.</p>
<p>I can resolve this by passing the first object to the second object's constructor, then calling a setter on the first object to pass the second object to it, but that seems a little clunky, and I'm wondering if there's a better way:</p>
<pre><code>backend = new Backend();
panel = new Panel(backend);
backend.setPanel();
</code></pre>
<p>I've never put any study into MVC; I suppose I'm dealing with a model here (the Backend), and a view or a controller (the Panel). Any insights here I can gain from MVC?</p>
| [
{
"answer_id": 371768,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "backend = new Backend();\npanel = new Panel(backend);\nbackend.setPanel(panel);\n"
},
{
"answer_id": 371779,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 0,
"selected": false,
"text": "panel = new Panel(backend);\n Public Sub Panel(ByVal BackEnd as BackEnd)\n Me.MyBackEnd = BackEnd\n BackEnd.MyPanel = Me\n End Sub\n Public Sub Panel(ByVal BackEnd as BackEnd)\n Me.MyBackEnd = BackEnd.Proxy\n BackEnd.MyPanel = Me\n End Sub\n\n Public Property MyBackEnd() as BackEnd\n Set (ByVal Value as BackEnd)\n priBackEndProxy = BackEnd.Proxy\n End Set\n Get\n Return priBackEndProxy.GetRef\n End Get\n End Property\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18103/"
] |
371,716 | <p>When we serialize an enum from C# to SQL Server we use a NCHAR(3) datatype with mnemonic values for each value of the enum.
That way we can easily read a SELECT qry.</p>
<p>How do you save enum to your database?</p>
<p>What datatype do you use?</p>
| [
{
"answer_id": 371748,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": false,
"text": "public enum ActionType\n{\n Insert = 1,\n Update = 2,\n Delete = 3\n}\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28207/"
] |
371,721 | <p>I have a simple question and wish to hear others' experiences regarding which is the best way to replicate images across multiple hosts.</p>
<p>I have determined that storing images in the database and then using database replication over multiple hosts would result in maximum availability.</p>
<p>The worry I have with the filesystem is the difficulty synchronising the images (e.g I don't want 5 servers all hitting the same server for images!).</p>
<p>Now, the only concerns I have with storing images in the database is the extra queries hitting the database and the extra handling i'd have to put in place in apache if I wanted 'virtual' image links to point to database entries. (e.g AddHandler)</p>
<p>As far as my understanding goes:</p>
<ul>
<li>If you have a script serving up the
images: Each image would require a
database call.</li>
<li>If you display the images inline as
binary data: Which could be done in
a single database call.</li>
<li>To provide external / linkable
images you would have to add a
addHandler for the extension you
wish to 'fake' and point it to your
scripting language (e.g php, asp).</li>
</ul>
<p>I might have missed something, but I'm curious if anyone has any better ideas?</p>
<hr>
<p>Edit:
Tom has suggested using mod_rewrite to save using an AddHandler, I have accepted as a proposed solution to the AddHandler issue; however I don't yet feel like I have a complete solution yet so please, please, keep answering ;)</p>
<p>A few have suggested using lighttpd over Apache. How different are the ISAPI modules for lighttpd?</p>
| [
{
"answer_id": 371806,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 1,
"selected": false,
"text": "$_SERVER['PATH_INFO']"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41690/"
] |
371,725 | <p>In Pseudo code</p>
<pre><code>If Domain inList(GB,US,ES,FR Then
Print This Html
Else
Print This HTML
EndIf
</code></pre>
| [
{
"answer_id": 371880,
"author": "mtruesdell",
"author_id": 6479,
"author_profile": "https://Stackoverflow.com/users/6479",
"pm_score": 1,
"selected": false,
"text": "<xsl:choose>\n <xsl:when test=\"domain = 'GB' or domain = 'US' or domain = 'ES' or domain = 'FR'\">\n print this html\n </xsl:when>\n <xsl:otherwise>\n print other html\n </xsl:otherwise>\n</xsl:choose>\n"
},
{
"answer_id": 371914,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 3,
"selected": true,
"text": "<xsl:when test=\"$listset/item[@property=$variable]\">\n <?xml version=\"1.0\"?>\n<foo>\n <bar property=\"gb\" />\n <list>\n <item property=\"gb\"/>\n <item property=\"us\"/>\n </list>\n</foo>\n"
},
{
"answer_id": 373192,
"author": "BeWarned",
"author_id": 37110,
"author_profile": "https://Stackoverflow.com/users/37110",
"pm_score": 0,
"selected": false,
"text": "\n<xsl:template match=\"list/item\">\nProperty [<xsl:value-of select=\"@property\"/>] html\n</xsl:template>\n\n<xsl:template match=\"list/item[some $x in ('us', 'gb') satisfies $x eq @property ]\">\nProperty [<xsl:value-of select=\"@property\"/>] HTML\n</xsl:template>\n"
},
{
"answer_id": 373302,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 0,
"selected": false,
"text": "domain @test <xsl:if> <xsl:when> true() domain contains(' GB US ES ', concat(' ', domain, ' ')) domain not(contains(domain, ' ')) and contains(' GB US ES ', concat(' ', domain, ' '))"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87783/"
] |
371,728 | <p>Every time I create a new excel sheet, I have to go in and change it's cell reference mode to the familiar A1, B1, etc. I can't seem to find a way to permanently set it to A1 style.</p>
<p>Is there a macro I can write or a way to use templates or something, so that I don't have to keep changing the R1C1 setting?</p>
| [
{
"answer_id": 371757,
"author": "Ian G",
"author_id": 31765,
"author_profile": "https://Stackoverflow.com/users/31765",
"pm_score": 4,
"selected": true,
"text": "personal.xls Personal.xls excel /regserver"
},
{
"answer_id": 371765,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": " Sub useA1references ()\n Application.ReferenceStyle = xlA1\n End Sub\n"
},
{
"answer_id": 371812,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 0,
"selected": false,
"text": "R1C1 reference"
},
{
"answer_id": 372526,
"author": "KnomDeGuerre",
"author_id": 24233,
"author_profile": "https://Stackoverflow.com/users/24233",
"pm_score": 0,
"selected": false,
"text": "With Application\n If .ReferenceStyle = xlA1 Then\n .ReferenceStyle = xlR1C1\n Else\n .ReferenceStyle = xlA1\n End If\n\nEnd With ' Application\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
] |
371,739 | <p>I want to develop a plug-in that does this:</p>
<p><em>A button, when clicked, opens the new mail window but has a certain phrase in the subject line, for e.g. when I click a button called 'PROJ123', the new mail window opens with the subject line "[PROJ123]"</em></p>
<p>Other functionality it would need:</p>
<ul>
<li>Ability to Create/Update/Delete Buttons as needed</li>
</ul>
<p>What is the best way to do this? </p>
<p>Any and all tips, references, online resources, examples are greatly appreciated!</p>
| [
{
"answer_id": 371971,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "Private Sub cmdCommand_Click()\n Dim eml As MailItem\n\n Set eml = Application.CreateItem(olMailItem)\n eml.Subject = \"Proj1\"\n UserForm1.Hide\n eml.Display\nEnd Sub\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
371,753 | <p>I want to override access to one variable in a class, but return all others normally. How do I accomplish this with <code>__getattribute__</code>?</p>
<p>I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:</p>
<pre><code>class D(object):
def __init__(self):
self.test=20
self.test2=21
def __getattribute__(self,name):
if name=='test':
return 0.
else:
return self.__dict__[name]
>>> print D().test
0.0
>>> print D().test2
...
RuntimeError: maximum recursion depth exceeded in cmp
</code></pre>
| [
{
"answer_id": 371833,
"author": "Egil",
"author_id": 44606,
"author_profile": "https://Stackoverflow.com/users/44606",
"pm_score": 8,
"selected": true,
"text": "self.__dict__ __getattribute__ __getattribute__ object __getattribute__ class D(object):\n def __init__(self):\n self.test=20\n self.test2=21\n def __getattribute__(self,name):\n if name=='test':\n return 0.\n else:\n return object.__getattribute__(self, name)\n object __getattribute__ In [1]: from foo import *\n\nIn [2]: d = D()\n\nIn [3]: d.test\nOut[3]: 0.0\n\nIn [4]: d.test2\nOut[4]: 21\n"
},
{
"answer_id": 371844,
"author": "Singletoned",
"author_id": 46715,
"author_profile": "https://Stackoverflow.com/users/46715",
"pm_score": 4,
"selected": false,
"text": "__getattribute__ class D(object):\n def __init__(self):\n self.test = 20\n self.test2 = 21\n\n test = 0\n class D(object):\n def __init__(self):\n self.test = 20\n self.test2 = 21\n\n @property\n def test(self):\n return 0\n D test d.test __init__ class D(object):\n def __init__(self):\n self.test = 20\n self.test2 = 21\n\n _test = 0\n\n def get_test(self):\n return self._test\n\n def set_test(self, value):\n self._test = value\n\n test = property(get_test, set_test)\n"
},
{
"answer_id": 371864,
"author": "ttepasse",
"author_id": 46657,
"author_profile": "https://Stackoverflow.com/users/46657",
"pm_score": 4,
"selected": false,
"text": "object.__getattribute__(self, name) def __getattribute__(self,name):\n ...\n return self.__dict__[name]\n __dict__ __getattribute__ __dict__ __getattribute__ return object.__getattribute__(self, name)\n __getattribute__"
},
{
"answer_id": 372919,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": false,
"text": "__getattr__ __getattr__( self, name) name AttributeError __getattr__() __getattr__() __setattr__() __setattr__() __getattribute__() test self.test=20"
},
{
"answer_id": 16811277,
"author": "ElmoVanKielmo",
"author_id": 2431997,
"author_profile": "https://Stackoverflow.com/users/2431997",
"pm_score": 3,
"selected": false,
"text": "class D(object):\n def __init__(self):\n self.test = 20\n self.test2 = 21\n def __getattribute__(self, name):\n if name == 'test':\n return 0.\n else:\n return super(D, self).__getattribute__(name)\n"
},
{
"answer_id": 28356216,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 4,
"selected": false,
"text": "__getattribute__ AttributeError __getattr__ $ grep -Erl \"def __getattribute__\\(self\" cpython/Lib | grep -v \"/test/\"\ncpython/Lib/_threading_local.py\ncpython/Lib/importlib/util.py\n property D class D(object):\n def __init__(self):\n self.test2=21\n\n @property\n def test(self):\n return 0.\n\n @test.setter\n def test(self, value):\n '''dummy function to avoid AttributeError on setting property'''\n\n @test.deleter\n def test(self):\n '''dummy function to avoid AttributeError on deleting property'''\n >>> o = D()\n>>> o.test\n0.0\n>>> o.test = 'foo'\n>>> o.test\n0.0\n>>> del o.test\n>>> o.test\n0.0\n __getattribute__ __getattribute__ AttributeError __getattr__ super object __getattr__ class NoisyAttributes(object):\n def __init__(self):\n self.test=20\n self.test2=21\n def __getattribute__(self, name):\n print('getting: ' + name)\n try:\n return super(NoisyAttributes, self).__getattribute__(name)\n except AttributeError:\n print('oh no, AttributeError caught and reraising')\n raise\n def __getattr__(self, name):\n \"\"\"Called if __getattribute__ raises AttributeError\"\"\"\n return 'close but no ' + name \n\n\n>>> n = NoisyAttributes()\n>>> nfoo = n.foo\ngetting: foo\noh no, AttributeError caught and reraising\n>>> nfoo\n'close but no foo'\n>>> n.test\ngetting: test\n20\n class D(object):\n def __init__(self):\n self.test=20\n self.test2=21\n def __getattribute__(self,name):\n if name=='test':\n return 0.\n else:\n return super(D, self).__getattribute__(name)\n >>> o = D()\n>>> o.test = 'foo'\n>>> o.test\n0.0\n>>> del o.test\n>>> o.test\n0.0\n>>> del o.test\n\nTraceback (most recent call last):\n File \"<pyshell#216>\", line 1, in <module>\n del o.test\nAttributeError: test\n __getattribute__ \"__dict__\" super __slots__ class D(object):\n def __init__(self):\n self.test=20\n self.test2=21\n def __getattribute__(self,name):\n if name=='test':\n return 0.\n else: # v--- Dotted lookup on self in __getattribute__\n return self.__dict__[name]\n\n>>> print D().test\n0.0\n>>> print D().test2\n...\nRuntimeError: maximum recursion depth exceeded in cmp\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
371,762 | <p>What exactly is GUID? Why and where I should use it? <br/>
I've seen references to GUID in a lot of places, and in wikipedia,
but it is not very clear telling you where to use it.
If someone could answer this, it would be nice.
Thanks</p>
| [
{
"answer_id": 371868,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "com.example.jpackage\n xmlns=\"http://www.w3.org/1999/xhtml\"\n"
},
{
"answer_id": 67889504,
"author": "N Djel Okoye",
"author_id": 4170558,
"author_profile": "https://Stackoverflow.com/users/4170558",
"pm_score": 0,
"selected": false,
"text": "[guid]::NewGuid() powershell [guid]::NewGuid()"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37650/"
] |
371,781 | <p>There are 3 parts to the page. </p>
<ol>
<li><p>Header, which has unknown content at design time as it is populated with text at runtime. All the text must be displayed, no scroll bars.( I think <code>height: 100%</code> does this) </p></li>
<li><p>Content, the content should fill the page below the bottom of the header to the top of the footer. if there is more text in the content that can be shown, then scroll bars should be available. </p></li>
<li><p>Footer. Footer should be <code>25px</code> high and always sit at the bottom of the viewport. </p></li>
</ol>
<p>The window is a popup and it should never have window scroll bars, it can be resized but no scrollbars. The contents scroll bars should be the only one available. </p>
<p>The content area should resize when resizing the window, but the footer stay the same, ie fixed to the bottom. </p>
<p>The widths would all be <code>100%</code></p>
| [
{
"answer_id": 371868,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "com.example.jpackage\n xmlns=\"http://www.w3.org/1999/xhtml\"\n"
},
{
"answer_id": 67889504,
"author": "N Djel Okoye",
"author_id": 4170558,
"author_profile": "https://Stackoverflow.com/users/4170558",
"pm_score": 0,
"selected": false,
"text": "[guid]::NewGuid() powershell [guid]::NewGuid()"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46716/"
] |
371,796 | <p>If I'm adding a column via MySQL, I can specify where in the table that column will be using the AFTER modifier. But if I do the add_column via a Rails migration, the column will be created at the end of the table.</p>
<p>Is there any functionality for rails migrations to specify the position of an added column?</p>
| [
{
"answer_id": 371949,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": false,
"text": "add_column class AddColumnAfterOtherColumn < ActiveRecord::Migration\n def self.up\n execute \"ALTER TABLE table_name ADD COLUMN column_name INTEGER \n AFTER other_column\"\n end\n\n def self.down\n remove_column :table_name, :column_name\n end\nend\n"
},
{
"answer_id": 9946311,
"author": "Tamik Soziev",
"author_id": 429649,
"author_profile": "https://Stackoverflow.com/users/429649",
"pm_score": 5,
"selected": false,
"text": "add_column :users, :gender, :string, :after => :column_name\n rails g migration AddGenderToUser gender:string class AddSlugToDictionary < ActiveRecord::Migration\n def change\n add_column :users, :gender, :string, :after => :username\n end\nend\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2177/"
] |
371,807 | <p>I've been looking for a component that would allow me to pass an arbitrary C# object to an XSL transform.</p>
<p>The naive way of doing this is to serialise the object graph using an XmlSerializer; however, if you have a large object graph, this could cause problems as far as performance is concerned. Issues such as circular references, lazy loading, proxies etc may further muddy the waters here.</p>
<p>A better approach is to have some kind of Adapter class that implements IXPathNavigable and XPathNavigator. One such example that I've encountered is the <a href="http://blogs.byte-force.com/media/g/objectxpathnavigator/default.aspx" rel="noreferrer">ObjectXPathNavigator from Byte-Force</a> -- however, most of its key documentation is in Russian, and my initial tests seem to indicate that it has a few quirks and idiosyncrasies.</p>
<p>Does anyone know of either (a) any resources (overviews, tutorials, blog posts etc) about this particular in <strong>English</strong> or (b) any other alternatives that offer the same or similar functionality?</p>
| [
{
"answer_id": 431924,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 2,
"selected": false,
"text": "XPathNavigator // XPathNavigator"
},
{
"answer_id": 466511,
"author": "Adam Hawkes",
"author_id": 6703,
"author_profile": "https://Stackoverflow.com/users/6703",
"pm_score": 0,
"selected": false,
"text": "public class SomeType {\n public int myInt { get; set; }\n}\n\npublic class AnotherType {\n public string myString { get; set; }\n public SomeType mySomeType { get; set; }\n}\n\npublic class LastType {\n public SomeType mySomeType { get; set; }\n public AnotherType myAnotherType { get; set; }\n}\n\npublic class UserTypes{\n static void Main()\n {\n LastType lt = new LastType();\n SomeType st = new SomeType();\n AnotherType atype = new AnotherType();\n\n st.myInt = 7;\n atype.myString = \"BOB\";\n atype.mySomeType = st;\n lt.mySomeType = st;\n lt.myAnotherType = atype;\n\n string xmlOutput = YourAwesomeFunction(lt);\n }\n}\n <ObjectMap>\n <LastType id=\"0\">\n <mySomeType idref=\"1\" />\n <myAnotherType idref=\"2\" />\n </LastType>\n\n <SomeType id=\"1\">\n <myInt>7</myInt>\n </SomeType>\n\n <AnotherType id=\"2\">\n <myString>BOB</myString>\n <mySomeType idref=\"1\" />\n </AnotherType>\n</ObjectMap>\n"
}
] | 2008/12/16 | [
"https://Stackoverflow.com/questions/371807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/886/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.