qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
367,030 | <p>Is it possible to get a list of all descendant classes of a particular class in objective-c?</p>
<p>Something like:</p>
<pre><code> @interface A : NSObject
@end
@interface B : A
@end
@interface C : A
@end
NSArray *descendants = [A allDescendants]; // descendants = [B, C]
</code></pre>
| [
{
"answer_id": 367078,
"author": "Matt Gallagher",
"author_id": 36103,
"author_profile": "https://Stackoverflow.com/users/36103",
"pm_score": 3,
"selected": false,
"text": "objc_getClassList isKindOfClass:A"
},
{
"answer_id": 367189,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 0,
"selected": false,
"text": "[[A class] superclass] Class Class"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,040 | <p>In Matlab, how can I find value of K, in a system that has oscillation?</p>
<blockquote>
<p>(system's tf, if needed: (K * (s +
25))/(s^3 + 24 s^2 + 100 s) )</p>
</blockquote>
<p>PS. I'm using root locus.</p>
| [
{
"answer_id": 367215,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 0,
"selected": false,
"text": "dcgain"
},
{
"answer_id": 425417,
"author": "Stephen Friederichs",
"author_id": 39492,
"author_profile": "https://Stackoverflow.com/users/39492",
"pm_score": 1,
"selected": false,
"text": "num = [1 25];\nden = [1 24 100 0];\n\nsys=tf(num,den)\nrlocus(sys)\n"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,052 | <p>There seems to be no built-in support for case preserving find/replace in VisualStudio (see also a respective <a href="https://developercommunity.visualstudio.com/t/case-preserving-search-replace/580810" rel="nofollow noreferrer">feature request</a>).</p>
<p>What I mean is: searching for 'BadJob' and replacing with 'GoodJob' would do the following replacements</p>
<pre><code>'badjob' -> 'goodjob'
'BadJob' -> 'GoodJob'
'badJob' -> 'goodJob'
'BADJOB' -> 'GOODJOB'
</code></pre>
<p>So I am looking for a macro/add-in which implements case preserving find/replace. And if none exists, what is a good starting point to write my own (preferably based on the built-in find/replace capabilities).</p>
<p>Update:<br />
I know I can make 4 manual replacements doing the job, but I am looking for a way to do it automatically in VS (like e.g. Emacs does it).
A common scenario: a variable named 'foo' and some functions DoFoo(), GetFoo(), ... and some additional comments containing 'foo' 'Foo' etc.
Now rename 'foo' to bar' yielding variable 'bar', functions DoBar(), GetBar() etc. by ONE find/replace.</p>
| [
{
"answer_id": 53559408,
"author": "noelicus",
"author_id": 865643,
"author_profile": "https://Stackoverflow.com/users/865643",
"pm_score": 0,
"selected": false,
"text": "from Npp import *\n\n#Use capitalizeFirst because .capitalize will make the remaining string lower, but in CamelCase examples \n#we will want to preserve the user-typed casing. e.g. YourMonkeyMagic -> MyMonkieMagik \ndef capitalizeFirst(str):\n return '%s%s' % (str[:1].upper(), str[1:])\n\n#*** Ask user what to find and replace ***\nfind_str=notepad.prompt(notepad, 'Find (keeping case)', '')\nreplace_str=notepad.prompt(notepad, 'Replace (keeping case)', '')\n\n#*** Do a case-sensitive replacement on each type ***\neditor.replace(find_str.upper(), replace_str.upper())\neditor.replace(find_str.lower(), replace_str.lower())\neditor.replace(capitalizeFirst(find_str), capitalizeFirst(replace_str))\neditor.replace(find_str, replace_str)\n"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45637/"
] |
367,066 | <p>I am developing an application trying to employ the Observer pattern. Basically I have a base form from which various components (forms) can be loaded.</p>
<p>The base form references each of the components and some of the components reference each other.</p>
<p>If I want one of the components to listen for events raised by the base form (perhaps from a menu etc) I can't seem to achieve this without needing to add a reference to the base form in the component. This causes a "circular reference".</p>
<p>Is it possible to listen/subscribe to events in projects which are not referenced?</p>
| [
{
"answer_id": 371855,
"author": "Nigel Hawkins",
"author_id": 1389021,
"author_profile": "https://Stackoverflow.com/users/1389021",
"pm_score": 0,
"selected": false,
"text": "publisherObject.SomeEvent += MyEventHandler();\n"
},
{
"answer_id": 377415,
"author": "Hinek",
"author_id": 20580,
"author_profile": "https://Stackoverflow.com/users/20580",
"pm_score": 0,
"selected": false,
"text": "public class BaseFormEventClass\n{\n public EventHandler<EventArgs> BaseFormDidSomething;\n}\n public class MyComponent\n{\n public MyComponent(BaseFormEventClass eventClass)\n {\n eventClass.BaseFormDidSomething += this.EventClass_BaseFormDidSometing;\n }\n // ...\n}\n\npublic class BaseForm\n{\n private BaseFormEventClass eventClass = new BaseFormEventClass();\n\n private void LoadComponents()\n {\n MyComponent component1 = new MyComponent(this.eventClass);\n }\n\n private void RaiseBaseFormDidSomething()\n {\n EventHandler<EventArgs> handler = eventClass.BaseFormDidSomething;\n if (handler != null) handler(this, EventArgs.Empty);\n }\n}\n"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,069 | <p>I'm looking for a simple, but cross-platform <em>negate</em>-process that negates the value a process returns. It should map 0 to some value != 0 and any value != 0 to 0, i.e. the following command should return "yes, nonexistingpath doesn't exist":</p>
<pre><code> ls nonexistingpath | negate && echo "yes, nonexistingpath doesn't exist."
</code></pre>
<p>The ! - operator is great but unfortunately not shell-independent.</p>
| [
{
"answer_id": 367075,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 6,
"selected": false,
"text": "! ls nonexistingpath && echo \"yes, nonexistingpath doesn't exist\"\n"
},
{
"answer_id": 367076,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 4,
"selected": false,
"text": "ls nonexistingpath || echo \"yes, nonexistingpath doesn't exist.\"\n ! ls nonexistingpath\n"
},
{
"answer_id": 367077,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "! ls nonexistingpath && echo \"yes, nonexistingpath doesn't exist.\"\n ls nonexistingpath || echo \"yes, nonexistingpath doesn't exist.\"\n"
},
{
"answer_id": 367167,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 8,
"selected": true,
"text": "! ! if while until ! ! # Simple commands, pipes, and redirects work fine.\n$ ! some-command succeed; echo $?\n1\n$ ! some-command fail | some-other-command fail; echo $?\n0\n$ ! some-command < succeed.txt; echo $?\n1\n\n# Environment variables also work, but must come after the !.\n$ ! RESULT=fail some-command; echo $?\n0\n\n# A more complex example.\n$ if ! some-command < input.txt | grep Success > /dev/null; then echo 'Failure!'; recover-command; mv input.txt input-failed.txt; fi\nFailure!\n$ ls *.txt\ninput-failed.txt\n if ...command and arguments...\nthen : it succeeded\nelse : it failed\nfi\n not /*\n@(#)File: $RCSfile: not.c,v $\n@(#)Version: $Revision: 4.2 $\n@(#)Last changed: $Date: 2005/06/22 19:44:07 $\n@(#)Purpose: Invert success/failure status of command\n@(#)Author: J Leffler\n@(#)Copyright: (C) JLSS 1991,1997,2005\n*/\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n#include \"stderr.h\"\n\n#ifndef lint\nstatic const char sccs[] = \"@(#)$Id: not.c,v 4.2 2005/06/22 19:44:07 jleffler Exp $\";\n#endif\n\nint main(int argc, char **argv)\n{\n int pid;\n int corpse;\n int status;\n\n err_setarg0(argv[0]);\n\n if (argc <= 1)\n {\n /* Nothing to execute. Nothing executed successfully. */\n /* Inverted exit condition is non-zero */\n exit(1);\n }\n\n if ((pid = fork()) < 0)\n err_syserr(\"failed to fork\\n\");\n\n if (pid == 0)\n {\n /* Child: execute command using PATH etc. */\n execvp(argv[1], &argv[1]);\n err_syserr(\"failed to execute command %s\\n\", argv[1]);\n /* NOTREACHED */\n }\n\n /* Parent */\n while ((corpse = wait(&status)) > 0)\n {\n if (corpse == pid)\n {\n /* Status contains exit status of child. */\n /* If exit status of child is zero, it succeeded, and we should\n exit with a non-zero status */\n /* If exit status of child is non-zero, if failed and we should\n exit with zero status */\n exit(status == 0);\n /* NOTREACHED */\n }\n }\n\n /* Failed to receive notification of child's death -- assume it failed */\n return (0);\n}\n \"stderr.h\""
},
{
"answer_id": 15720063,
"author": "Chris Suszyński",
"author_id": 844449,
"author_profile": "https://Stackoverflow.com/users/844449",
"pm_score": 4,
"selected": false,
"text": "echo '! ls notexisting' | bash echo '! ls /' | bash"
},
{
"answer_id": 55875061,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "!(command || other command) ! ls nonexistingpath && echo \"yes, nonexistingpath doesn't exist.\" szeder dscho gitster t9811-git-p4-label-import t9811-git-p4-label-import.sh tag that cannot be exported !(p4 labels | grep GIT_TAG_ON_A_BRANCH)\n p4 labels ! command1 ( command1 ! <blank> ! ( ! mksh/lksh main ! ("
},
{
"answer_id": 64707841,
"author": "4irmann",
"author_id": 14587285,
"author_profile": "https://Stackoverflow.com/users/14587285",
"pm_score": 3,
"selected": false,
"text": "ls nonexistingpath; test $? -eq 2 && echo \"yes, nonexistingpath doesn't exist.\"\n\n# Alternatively without an error message and handling of any error code > 0\nls nonexistingpath 2>/dev/null; test $? -gt 0 && echo \"yes, nonexistingpath doesn't exist.\"\n"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4085/"
] |
367,090 | <p>I was intending on use the Title attribute in the @Page directive to customise each pages title, but it simply doesn't appear to do anything.</p>
<p>The site uses master pages - I don't know if that is a consideration.</p>
<p>Master Page snippet:</p>
<pre><code><%@ Master Language="VB" CodeFile="brightnorth.master.vb" Inherits="brightnorth" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
etc....
</code></pre>
<p>Page snippet (from <a href="http://www.brightnorth.com/about/aboutus.aspx" rel="nofollow noreferrer">http://www.brightnorth.com/about/aboutus.aspx</a>):</p>
<pre><code><%@ Page Language="VB" MasterPageFile="~/brightnorth.master" AutoEventWireup="false" CodeFile="aboutus.aspx.vb" Inherits="about_aboutus" Title="Brightnorth.com: About Us" %>
</code></pre>
<p>What is more, if I run the page through the <a href="http://validator.w3.org/check?verbose=1&uri=http%3A%2F%2Fwww.brightnorth.com%2Fabout%2Faboutus.aspx" rel="nofollow noreferrer">validator</a>, it complains about... </p>
<blockquote>
<p>end tag for "head" which is not finished</p>
</blockquote>
<p>..whereas the the tag <em>is</em> present in the source code.</p>
<p>I've already got a workaround in place, but it's annoying the hell out of me, so I'm determined to find a resolution!</p>
| [
{
"answer_id": 367100,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 0,
"selected": false,
"text": "<title><%=Title%></title>\n"
},
{
"answer_id": 367109,
"author": "CJM",
"author_id": 6898,
"author_profile": "https://Stackoverflow.com/users/6898",
"pm_score": 4,
"selected": true,
"text": "runat=\"server\""
},
{
"answer_id": 538950,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<head runat=\"server\">\n<title><%=Page.Title%></title>\n</head>\n"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6898/"
] |
367,104 | <p>In java <1.5, constants would be implemented like this</p>
<pre><code>public class MyClass {
public static int VERTICAL = 0;
public static int HORIZONTAL = 1;
private int orientation;
public MyClass(int orientation) {
this.orientation = orientation;
}
...
</code></pre>
<p>and you would use it like this:</p>
<pre><code>MyClass myClass = new MyClass(MyClass.VERTICAL);
</code></pre>
<p>Now, in 1.5 obviously you should be using enums:</p>
<pre><code>public class MyClass {
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
private Orientation orientation;
public MyClass(Orientation orientation) {
this.orientation = orientation;
}
...
</code></pre>
<p>and now you would use it like this:</p>
<pre><code>MyClass myClass = new MyClass(MyClass.Orientation.VERTICAL);
</code></pre>
<p>Which I find slightly ugly. Now I could easily add a couple of static variables:</p>
<pre><code>public class MyClass {
public static Orientation VERTICAL = Orientation.VERTICAL;
public static Orientation HORIZONTAL = Orientation.HORIZONTAL;
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
private Orientation orientation;
public MyClass(Orientation orientation) {
this.orientation = orientation;
}
...
</code></pre>
<p>And now I can do this again:</p>
<pre><code>MyClass myClass = new MyClass(MyClass.VERTICAL);
</code></pre>
<p>With all the type-safe goodness of enums.</p>
<p>Is this good style, bad style or neither. Can you think of a better solution?</p>
<p><strong>Update</strong></p>
<p>Vilx- was the first one to highlight what I feel I was missing - that the enum should be a first-class citizen. In java this means it gets its own file in the package - we don't have namespaces. I had thought this would be a bit heavyweight, but having actually done it, it definitely feels right.</p>
<p>Yuval's answer is fine, but it didn't really emphasise the non-nested enum. Also, as for 1.4 - there are plenty of places in the JDK that use integers, and I was really looking for a way to evolve that sort of code.</p>
| [
{
"answer_id": 367105,
"author": "Yoni Roit",
"author_id": 34161,
"author_profile": "https://Stackoverflow.com/users/34161",
"pm_score": 2,
"selected": false,
"text": "MyClass myClass = new MyClass(Orientation.VERTICAL);\n"
},
{
"answer_id": 367113,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 2,
"selected": true,
"text": "namespace Whatever\n{\n enum MyEnum\n {\n }\n class MyClass\n {\n }\n}\n MyClass c = new MyClass(MyEnum.MyValue);\n"
},
{
"answer_id": 367123,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 5,
"selected": false,
"text": "public enum Color\n{\n BLACK, WHITE;\n}\n public class Color\n{\n public static Color WHITE = new Color(\"white\");\n public static Color BLACK = new Color(\"black\");\n\n private String color;\n\n private Color(String s)\n {\n color = s;\n }\n}\n drawBackground(Color.WHITE);\n getName() getId()"
},
{
"answer_id": 367128,
"author": "eulerfx",
"author_id": 13855,
"author_profile": "https://Stackoverflow.com/users/13855",
"pm_score": 0,
"selected": false,
"text": "MyClass.Vertical() : MyClass\nMyClass.Horizontal() : MyClass\n"
},
{
"answer_id": 24524882,
"author": "Raedwald",
"author_id": 545127,
"author_profile": "https://Stackoverflow.com/users/545127",
"pm_score": 1,
"selected": false,
"text": "enum int long double enum"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26334/"
] |
367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e s/foo/bar/g</code> for sub-directories).</p>
<p>I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes <code>perl -pi -e</code> work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...</p>
| [
{
"answer_id": 367181,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 4,
"selected": true,
"text": "python -h $_"
},
{
"answer_id": 367238,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "pypi.py python -c 'import pypi; pypi.subs(\"this\",\"that\")' subs"
},
{
"answer_id": 367260,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 3,
"selected": false,
"text": "def myfunc(filename, use_versbose):\n # function code\n\nif __name__ == '__main__':\n from optparse import OptionParser\n\n parser = OptionParser()\n parser.add_option(\"-f\", \"--file\", dest=\"filename\",\n help=\"write report to FILE\", metavar=\"FILE\")\n parser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n\n (options, args) = parser.parse_args()\n\n if options.filename:\n myfunc(options.filename, options.verbose)\n\n else:\n print 'ERROR -- Necessary command line options not given!'\n print parser.print_help()\n usage: <yourscript> [options]\n\noptions:\n -h, --help show this help message and exit\n -f FILE, --file=FILE write report to FILE\n -q, --quiet don't print status messages to stdout\n"
},
{
"answer_id": 9611564,
"author": "Michael Hoffman",
"author_id": 494061,
"author_profile": "https://Stackoverflow.com/users/494061",
"pm_score": 2,
"selected": false,
"text": "python -c 'import fileinput, sys; for line in fileinput.input(inplace=True): sys.stdout.write(line, \"foo\", \"bar\")'\n"
},
{
"answer_id": 14429701,
"author": "jarondl",
"author_id": 386899,
"author_profile": "https://Stackoverflow.com/users/386899",
"pm_score": 3,
"selected": false,
"text": "pyp \"p.replace('foo','bar')\"\n"
},
{
"answer_id": 24758853,
"author": "cgseller",
"author_id": 2664549,
"author_profile": "https://Stackoverflow.com/users/2664549",
"pm_score": 0,
"selected": false,
"text": "import fileinput \nimport sys\nfor line in fileinput.input(\"./poop\", inplace=True):\n line = line.replace(\"foo\", \"bar\")\n sys.stdout.write(line)\n"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28421/"
] |
367,130 | <p>I want create a Playlist control. I have a lot of information to display into a TStringList. I want to assign a record to TStringGrid.Objects instead of an object because so many objects may take a while to create/destroy. It also take a lot of RAM.</p>
<p>A record will be much faster and slim.
How can I do that?</p>
<pre><code>TYPE
AMyRec= packed record
FullName : string[255];
RelativePath : boolean;
IsInvalid : boolean;
InCache : boolean;
etc
end;
</code></pre>
| [
{
"answer_id": 367147,
"author": "Cesar Romero",
"author_id": 36875,
"author_profile": "https://Stackoverflow.com/users/36875",
"pm_score": 1,
"selected": false,
"text": "List.AddObject(MyRecord.FullName, @MyRecord);\n"
},
{
"answer_id": 367156,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 3,
"selected": false,
"text": "Type \nPMyrec = ^AMyRec;\n var\n MyRec : PMyRec;\nnew(MyRec);\nMyRec^.Fullname := 'test';\nMyRec^.RelativePath := false;\n MyList.Add(MyRec);\n Dispose(PMyRec(MyList[Index])); var\n MyRec : PMyRec;\n\nPMyRec := MyList.Items[i];\ntxtBox.Text = PMyRec^.Fullname;\n"
},
{
"answer_id": 367163,
"author": "Server Overflow",
"author_id": 46207,
"author_profile": "https://Stackoverflow.com/users/46207",
"pm_score": 1,
"selected": false,
"text": "Type\n AMyRec= packed record\n FullName : string[255];\n RelativePath : boolean;\n IsInvalid : boolean;\n end;\n PMyrec = ^AMyRec;\n\nprocedure TPlaylst.Button1Click(Sender: TObject);\nVAR MyRec1: PMyRec;\n PlaylistCtrl: TStringGrid;\nbegin\n {SET}\n new(MyRec1);\n MyRec1^.Fullname := 'test';\n MyRec1^.RelativePath := false;\n PlaylistCtrl.Objects[1,1]:= Pointer(MyRec1); \n\n\n {GET}\n ...\nend;\n"
},
{
"answer_id": 401457,
"author": "Matthias Hryniszak",
"author_id": 49970,
"author_profile": "https://Stackoverflow.com/users/49970",
"pm_score": 1,
"selected": false,
"text": "\ntype\n TMyRec= packed record\n FullName : string[255];\n RelativePath : boolean;\n IsInvalid : boolean;\n end;\n TMyData = object (TObject)\n private\n FData: TMRec;\n public\n constructor Create(AData: TMyRec);\n property FullName: String read FData.FullName write FData.FullName;\n property RelativePath: Boolean read FData.RelativePath write FData.RelativePath;\n property IsInvalid: Boolean read FData.IsInvalid write FData.IsInvalid;\n end;\n\n...\n\nconstructor TMyData.Create(AData: TMyRec);\nbegin\n FData := AData;\nend;\n procedure TMainForm.GrdPathsDrawCell(Sender: Object; ...);"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,141 | <p>Using Win32-specific APIs, is there an easy way to start an external application to open a file simply by passing in the path/name of the file?</p>
<p>For example, say I have a file called C:\tmp\image.jpg. Is there a single API that I can call to tell Windows to open the application associated with .jpg files? Without having to do a bunch of registry lookups?</p>
<p>I thought I remembered doing this many years ago, but I cannot find it.</p>
| [
{
"answer_id": 367144,
"author": "Igal Serban",
"author_id": 25737,
"author_profile": "https://Stackoverflow.com/users/25737",
"pm_score": 5,
"selected": true,
"text": "HINSTANCE ShellExecute(\n _In_opt_ HWND hwnd,\n _In_opt_ LPCTSTR lpOperation,\n _In_ LPCTSTR lpFile,\n _In_opt_ LPCTSTR lpParameters,\n _In_opt_ LPCTSTR lpDirectory,\n _In_ INT nShowCmd\n);\n"
},
{
"answer_id": 367218,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "HINSTANCE ShellExecute(\n HWND hwnd, // handle to owner window.\n LPCTSTR lpOperation, // verb to do, e.g., edit, open, print.\n LPCTSTR lpFile, // file to perform verb on.\n LPCTSTR lpParameters, // parameters if lpFile is executable, else NULL.\n LPCTSTR lpDirectory, // working directory or NULL for current directory.\n INT nShowCmd // window mode e.g., SW_HIDE, SW_SHOWNORMAL.\n);\n"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13022/"
] |
367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| [
{
"answer_id": 367244,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 1,
"selected": false,
"text": "import string\n\nd = \"Hello, I'm a string!\"\n\nresult = []\nword = ''\n\nfor char in d:\n if char not in string.whitespace:\n if char not in string.ascii_letters + \"'\":\n if word:\n result.append(word)\n result.append(char)\n word = ''\n else:\n word = ''.join([word,char])\n\n else:\n if word:\n result.append(word)\n word = ''\nprint result\n['Hello', ',', \"I'm\", 'a', 'string', '!']\n"
},
{
"answer_id": 367265,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": ">>> import re\n>>> import string\n>>> s = \"Helo, my name is Joe! and i live!!! in a button; factory:\"\n>>> l = [item for item in map(string.strip, re.split(\"(\\W+)\", s)) if len(item) > 0]\n>>> l\n['Helo', ',', 'my', 'name', 'is', 'Joe', '!', 'and', 'i', 'live', '!!!', 'in', 'a', 'button', ';', 'factory', ':']\n>>>\n"
},
{
"answer_id": 367292,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": true,
"text": ">>> import re\n>>> re.findall(r\"[\\w']+|[.,!?;]\", \"Hello, I'm a string!\")\n['Hello', ',', \"I'm\", 'a', 'string', '!']\n"
},
{
"answer_id": 8930959,
"author": "LaC",
"author_id": 151238,
"author_profile": "https://Stackoverflow.com/users/151238",
"pm_score": 5,
"selected": false,
"text": "re.findall(r\"\\w+|[^\\w\\s]\", text, re.UNICODE)\n ['r', 'sum'] ['I', \"'\", 'm']"
},
{
"answer_id": 23092385,
"author": "FrauHahnhen",
"author_id": 2173470,
"author_profile": "https://Stackoverflow.com/users/2173470",
"pm_score": 0,
"selected": false,
"text": "\\W+ \\b >>> import re\n>>> sentence = 'Hello, world!'\n>>> tokens = [t.strip() for t in re.findall(r'\\b.*?\\S.*?(?:\\b|$)', sentence)]\n['Hello', ',', 'world', '!']\n .*?\\S.*? $ >>> print [t.strip() for t in re.findall(r'\\b.*?\\S.*?(?:\\b|$)', '\"Oh no\", she said')]\n['Oh', 'no', '\",', 'she', 'said']\n >>> for token in [t.strip() for t in re.findall(r'\\b.*?\\S.*?(?:\\b|$)', '\"You can\", she said')]:\n... print re.findall(r'(?:\\w+|\\W)', token)\n\n['You']\n['can']\n['\"', ',']\n['she']\n['said']\n"
},
{
"answer_id": 43467899,
"author": "Siddharth Sonone",
"author_id": 5912110,
"author_profile": "https://Stackoverflow.com/users/5912110",
"pm_score": 0,
"selected": false,
"text": "string_big = \"One of Python's coolest features is the string format operator This operator is unique to strings\"\nmy_list =[]\nx = len(string_big)\npoistion_ofspace = 0\nwhile poistion_ofspace < x:\n for i in range(poistion_ofspace,x):\n if string_big[i] == ' ':\n break\n else:\n continue\n print string_big[poistion_ofspace:(i+1)]\n my_list.append(string_big[poistion_ofspace:(i+1)])\n poistion_ofspace = i+1\n\nprint my_list\n"
},
{
"answer_id": 53211805,
"author": "Fernando S. Peregrino",
"author_id": 7751504,
"author_profile": "https://Stackoverflow.com/users/7751504",
"pm_score": 3,
"selected": false,
"text": "import nltk\nnltk.download('punkt')\nsentence = \"help, me\"\nnltk.word_tokenize(sentence)\n"
},
{
"answer_id": 59066699,
"author": "ChocolateChip",
"author_id": 12397656,
"author_profile": "https://Stackoverflow.com/users/12397656",
"pm_score": -1,
"selected": false,
"text": "word = \"Hello,there\"\nword = word.replace(\",\" , \" ,\" )\nword = word.replace(\".\" , \" .\")\nreturn word.split()\n"
},
{
"answer_id": 61339339,
"author": "Malgo",
"author_id": 10484156,
"author_profile": "https://Stackoverflow.com/users/10484156",
"pm_score": 1,
"selected": false,
"text": "import re\n\ni = 'Sandra went to the hallway.!!'\nl = re.split('(\\W+?)', i)\nprint(l)\n\nempty = ['', ' ']\nl = [el for el in l if el not in empty]\nprint(l)\n\nOutput:\n['Sandra', ' ', 'went', ' ', 'to', ' ', 'the', ' ', 'hallway', '.', '', '!', '', '!', '']\n['Sandra', 'went', 'to', 'the', 'hallway', '.', '!', '!']\n"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40429/"
] |
367,178 | <p>I think the answer to this question is so obivous that noone has bothered writing about this, but its late and I really can't get my head around this.</p>
<p>I've been reading into IoC containers (Windsor in this case) and I'm missing how you talk to the container from the various parts of your code.</p>
<p>I get DI, I've been doing poor mans DI (empty constructors calling overloaded injection constructors with default parameter implementations) for some time and I can completely see the benefit of the container. However, Im missing one vital piece of info; how are you supposed to reference the container every time you need a service from it?</p>
<p>Do I create a single global insance which I pass around? Surely not!</p>
<p>I know I should call this:</p>
<pre><code>WindsorContainer container = new WindsorContainer(new XmlInterpreter());
</code></pre>
<p>(for example) when I want to load my XML config, but then what do I do with container? Does creating a new container every time thereafter persist the loaded config through some internal static majicks or otherwise, or do I have to reload the config every time (i guess not, or lifecycles couldnt work).</p>
<p>Failing to understand this is preventing me from working out how the lifecycles work, and getting on with using some IoC awsomeness</p>
<p>Thanks,</p>
<p>Andrew</p>
| [
{
"answer_id": 367190,
"author": "maxnk",
"author_id": 45862,
"author_profile": "https://Stackoverflow.com/users/45862",
"pm_score": 0,
"selected": false,
"text": "public interface IResolver\n{\n object Resolve(Type type);\n object Resolve(string name);\n\n T Resolve<T>() where T : class;\n T Resolve<T>(string name) where T : class;\n}\n public static class Resolver // : IResolver\n{\n private static IResolver _current;\n\n public static object Resolve(Type type)\n {\n return Current.Resolve(type);\n }\n\n public static object Resolve(string name)\n {\n return Current.Resolve(name);\n }\n\n public static T Resolve<T>() where T : class\n {\n return Current.Resolve<T>();\n }\n\n public static T Resolve<T>(string name) where T : class\n {\n return Current.Resolve<T>(name);\n }\n\n private static IResolver Current\n {\n get\n {\n if (_current == null)\n {\n _current = new SpringResolver();\n }\n\n return _current;\n }\n }\n}\n"
},
{
"answer_id": 673540,
"author": "Peter Lillevold",
"author_id": 35245,
"author_profile": "https://Stackoverflow.com/users/35245",
"pm_score": 1,
"selected": false,
"text": "IKernel"
}
] | 2008/12/14 | [
"https://Stackoverflow.com/questions/367178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28543/"
] |
367,192 | <p>I know java and would normally put in getter/setter methods. I am interested in doing it in C# with the following code, but it throws a StackOverflow exception. What am I doing wrong?</p>
<p>Calling Code</p>
<pre><code>c.firstName = "a";
</code></pre>
<p>Property Code </p>
<pre><code>public String firstName;
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
</code></pre>
| [
{
"answer_id": 367195,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 8,
"selected": true,
"text": "set private string firstName;\n\npublic string FirstName\n{\n get\n {\n return this.firstName;\n }\n set\n {\n this.firstName = value;\n }\n}\n public string FirstName { get; set; }\n"
},
{
"answer_id": 367196,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 4,
"selected": false,
"text": "private string m_firstName;\n\npublic String firstName;\n{\n get\n {\n return m_firstName;\n }\n set\n {\n m_firstName = value;\n }\n}\n"
},
{
"answer_id": 68843910,
"author": "Dorin Baba",
"author_id": 9517443,
"author_profile": "https://Stackoverflow.com/users/9517443",
"pm_score": 0,
"selected": false,
"text": "// this is the private field that we do not want to expose (aka to make\n// it accessible for everyone\nprivate int digit;\n\n// But we want somehow to allow users of our class to interact \n// with the digit field, so we create a property.\n// Note: fields' name start with lowercase, properties' name with Uppercase\npublic int Digit\n{\n get \n {\n // this is the method that gets calls whenever the user calls Digit,\n // Example: Console.WriteLine(object.Digit);\n\n // let's add here the logic of getting digit's ascii code\n return Char.Parse(digit.ToString());\n }\n\n set\n {\n // this method gets called when someone assigns a value for Digit\n // Example: Digit = 3;\n \n // here we can add the validation logic ( 0 <= value <=9)\n if(value < 0 || value > 9)\n throw new Exception(\"Please provide a number between 0 and 9\");\n \n digit = value;\n }\n} \n public string FirstName{ get; set; }\n private string firstName;\npublic string FirstName\n{\n get { return firstName; }\n set { firstName= value }\n}\n private string firstName;\n\npublic string GetFirstName()\n{\n return firstName;\n}\n\npublic void SetFirstName(string value)\n{\n firstName = value;\n}\n public string GetFirstName()\n{\n return GetFirstName();\n}\n\npublic void SetFirstName(string value)\n{\n GetFirstName() = value; \n}\n object.SetFirstName(\"Rick Astley\");\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] |
367,201 | <p>I need to intercept the console output stream(s) in order to capture it for a log but still pass things through to the original stream so the application works properly. This obviously means storing the original <code>Console.Out</code> TextWriter before changing it with <code>Console.SetOut(new MyTextWriterClass(originalOut))</code>.</p>
<p>I assume the individual operations to get the Out property and to call the SetOut() method are implemented by <code>Console</code> in a thread-safe manner. But I'd like to make sure that some other thread (eg. running client application code that I don't control and can't expect to change, and so I can't rely on my own custom locking scheme) can't accidentally change it in between my get and set and end up getting overwritten by my change to it (breaking their application's behavior!). Since the other code may simply call SetOut(), my code should ideally get the same lock used internally by <code>Console</code> (assuming there is one).</p>
<p>Unfortunately, <code>Console</code> is a (static) class, not an instance, so you can't just <code>lock (Console)</code>. And looking in the class documentation there does not seem to be any mention of locking. This is not the normally-expected usage of these Console methods, but there should be some safe way of doing this as an atomic operation.</p>
<p>Failing a standard locking scheme, is there some other way to ensure this? For such a short critical section (and done only once), even momentarily blocking all other threads might be acceptable, if that's the only way to do it. We're using C# and .NET2.0.</p>
<p>If not even <em>that</em> is possible (without disrupting the client application), then we'll just have to rely on it being very unlikely that the client application would redirect its console output <i>and</i> happen to do it in between our get and set operations. I'd just like to cover all the bases, just in case.</p>
<p><strong>Edit</strong>: Now that we have a concrete answer with example code, I've reworded the question title to more generally reflect the use cases where the answer(s) can help, to be more clear. Also, added a tag for "atomic".</p>
| [
{
"answer_id": 367428,
"author": "devstuff",
"author_id": 41321,
"author_profile": "https://Stackoverflow.com/users/41321",
"pm_score": 0,
"selected": false,
"text": "Main() Main() [STAThread]"
},
{
"answer_id": 368584,
"author": "JoshBerke",
"author_id": 26160,
"author_profile": "https://Stackoverflow.com/users/26160",
"pm_score": 3,
"selected": true,
"text": "[HostProtection(SecurityAction.LinkDemand, UI=true)]\npublic static void SetOut(TextWriter newOut)\n{\n if (newOut == null)\n {\n throw new ArgumentNullException(\"newOut\");\n }\n new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();\n _wasOutRedirected = true;\n newOut = TextWriter.Synchronized(newOut);\n lock (InternalSyncObject)\n {\n _out = newOut;\n }\n}\n"
},
{
"answer_id": 538621,
"author": "Rob Parker",
"author_id": 181460,
"author_profile": "https://Stackoverflow.com/users/181460",
"pm_score": 1,
"selected": false,
"text": "ConsoleIntercepter TextWriter private static object GetConsoleLockObject()\n{\n object lockObject;\n try\n {\n const BindingFlags bindingFlags = BindingFlags.GetProperty |\n BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;\n // It's currently private, but we'd be happy if it were public, too.\n Type consoleType = typeof(Console);\n\n lockObject = consoleType.InvokeMember(\"InternalSyncObject\", bindingFlags,\n null, null, null);\n }\n catch\n {\n lockObject = null; // Return null on any failure.\n }\n return lockObject;\n}\npublic static void RegisterConsoleIntercepter()\n{\n object lockObject = GetConsoleLockObject();\n if (lockObject != null)\n {\n // Great! We can make sure any other changes happen before we read\n // or after we've written, making this an atomic replacement operation.\n lock (lockObject)\n {\n DoIntercepterRegistration();\n }\n }\n else\n {\n // Couldn't get the lock object, but we still need to work, so\n // just do it without an outer lock, and keep your fingers crossed.\n DoIntercepterRegistration();\n }\n}\n DoIntercepterRegistration() private static void DoIntercepterRegistration()\n{\n Console.SetOut(new ConsoleIntercepter(Console.Out));\n Console.SetError(new ConsoleIntercepter(Console.Error));\n}\n TextWriter"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181460/"
] |
367,213 | <p>Is there a way to find the HTML element on the page that a Silverlight control is hosted in from within Silverlight?</p>
| [
{
"answer_id": 367638,
"author": "Boyan",
"author_id": 38106,
"author_profile": "https://Stackoverflow.com/users/38106",
"pm_score": 3,
"selected": true,
"text": "System.Windows.Browser.HtmlElement plugin = System.Windows.Browser.HtmlPage.Plugin;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11829/"
] |
367,214 | <p>Consider two web pages with the following in their body respectively:</p>
<pre><code><body>
<script>
document.writeln('<textarea></textarea>')
</script>
</body>
</code></pre>
<p>and</p>
<pre><code><body>
<script>
var t = document.createElement('textarea');
document.body.appendChild(t);
</script>
</body>
</code></pre>
<p>(think of them as part of something larger, where the textareas <em>have</em> to be generated from JavaScript and can't be hard-coded into the page). They both produce the same output, but the former is considered "bad", while the latter is considered the "right" way to do it. (Right?)</p>
<p>On the other hand, if you type something in the page and then either refresh it, or go somewhere else and hit Back, then in the former case, what you typed in the textarea is preserved, while in the later it is lost. (At least on Firefox.)</p>
<p>Is there a way to use the latter method and still have the useful feature that what the user has typed into a form is saved even if they accidentally hit refresh or come back via the Back button (at least on Firefox)?</p>
| [
{
"answer_id": 367982,
"author": "roborourke",
"author_id": 42147,
"author_profile": "https://Stackoverflow.com/users/42147",
"pm_score": 0,
"selected": false,
"text": "<div id=\"addtextarea\"></div>\n\nvar e = document.getElementByID('addtextarea');\ne.innerHTML = '<textarea></textarea>';\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4958/"
] |
367,216 | <p>Does using STL increase footprint significantly? Could you guys share your experience regarding this matter? What are the best practices to build a small footprint library?</p>
| [
{
"answer_id": 367296,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 2,
"selected": false,
"text": "std::list<int> std::list<int> std::list<int> std::list<double> std::vector<bool> std::vector<T> void*"
},
{
"answer_id": 367303,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 4,
"selected": false,
"text": "#include <vector>\n\nvoid a(std::vector<int>& l)\n{\n l.push_back(1);\n l.at(0) = 2;\n}\n #include <vector>\n\nvoid b(std::vector<int>& l)\n{\n l.push_back(1);\n l.at(0) = 2;\n}\n #include <vector>\n\nvoid a(std::vector<int>&);\nvoid b(std::vector<int>&);\n\nint main()\n{\n std::vector<int> x;\n a(x);\n b(x);\n}\n >g++ -c a.cpp\n>g++ -c b.cpp\n\n>nm a.o\n<removed other stuff>\n000000a0 S __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi\n<removed other stuff>\n\n>nm b.o\n<removed other stuff>\n000000a0 S __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi\n<removed other stuff>\n\n>c++filt __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi\nstd::vector<int, std::allocator<int> >::_M_insert_aux(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, int const&)\n\n>g++ a.o b.o main.cpp\nnm a.out | grep __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi\n00001700 T __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi\n"
},
{
"answer_id": 367348,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 1,
"selected": false,
"text": "libpthread.a"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,219 | <p>I'm currently getting through the <a href="http://www.cplusplus.com" rel="nofollow noreferrer">http://www.cplusplus.com</a> tutorial and I came across this section here: <a href="http://www.cplusplus.com/doc/tutorial/inheritance.html" rel="nofollow noreferrer">http://www.cplusplus.com/doc/tutorial/inheritance.html</a> that deals with the subject of <em>friend functions</em> and <em>friend classes</em> in C++. </p>
<p>My question is, when When is it prudent to use friendship when creating a program? </p>
<p>The only clue I got was in an example inside of the article that demonstrated a friend function that 'duplicated' an object. </p>
| [
{
"answer_id": 367313,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 2,
"selected": false,
"text": "BigNum // binary operators where BigNum isn't the left-hand operand\nBigNum operator+ (int, BigNum);\nBigNum operator- (int, BigNum);\n\n// stream operators\nstd::ostream &operator<< (std::ostream &os, const BigNum &num);\nstd::istream &operator>> (std::istream &is, BigNum &num);\n int + BigNum BigNum + int"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,226 | <p>Its the weekend again, and that means I get to play with my <a href="https://stackoverflow.com/questions/332585/2d-platformer-physics">hobby project</a>.</p>
<p>I've gotten tired of creating test levels by hand, so I thought I'd take a break from engine development and work on a level editor:</p>
<p><a href="http://gfilter.net/junk/Editor.JPG" rel="nofollow noreferrer">Level Editor http://gfilter.net/junk/Editor.JPG</a></p>
<p>I'd like to implement a flood fill algorithm in the editor, which would work just like in a paint program. Does anyone have any pointers on what technique would work good for me here?</p>
<p>The level is just a 2d array, so it could be considered the same as a bitmap really.</p>
<p>Thanks!</p>
| [
{
"answer_id": 367235,
"author": "AAA",
"author_id": 1977,
"author_profile": "https://Stackoverflow.com/users/1977",
"pm_score": 2,
"selected": false,
"text": "Select Tile To Fill: \nFill Till \nCheck neighbouring Tiles - If Empty Then Fill \nRepeat, for all filled tiles.\n"
},
{
"answer_id": 367253,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "1: stuff the start pixel into a queue, note its color. note it as added.\n2: begin picking a pixel off the queue. If it's similar to the start pixel:\n 2: put all its neighbours into the queue\n for each added pixel, note it's added. if already noted for a pixel, don't \n add it anymore.\n 3: color it with the destination color.\n3: nonempty => jump back to 2\n4: empty => we are finished\n public class Uebung1_2 implements PlugInFilter, MouseListener {\n private ImageProcessor ip;\n boolean[] state;\n int[] pixels;\n Queue<Integer> nextPixels;\n int threshould;\n\n /**\n * adds one pixel to the next-pixel queue only if it's not\n * already added.\n */\n void addNextPixel(int p) {\n if(!state[p]) {\n nextPixels.add(p);\n state[p] = true;\n }\n }\n\n boolean pixelsSimilar(int color1, int color2) {\n int dr = Math.abs(((color1 >> 16) & 0xff) -\n ((color2 >> 16) & 0xff));\n int dg = Math.abs(((color1 >> 8) & 0xff) -\n ((color2 >> 8) & 0xff));\n int db = Math.abs(((color1 >> 0) & 0xff) -\n ((color2 >> 0) & 0xff));\n return ((double)(dr + dg + db) / 3.0) <= threshould;\n }\n\n /**\n * actually does the hard work :)\n * @param x the x position from which to start filling\n * @param y the y position from which to start filling\n */\n private void doFill(int x, int y, boolean connect8) {\n // first, add the start pixel\n int width = ip.getWidth(),\n height = ip.getHeight();\n /* for 8bit, we just gonna take the median of rgb */\n Color colorC = ij.gui.Toolbar.getForegroundColor();\n int color = colorC.getRGB();\n int firstPixel = ip.get(x, y);\n\n // go on with the mainloop\n addNextPixel(y * width + x);\n while(!nextPixels.isEmpty()) {\n int nextPixel = nextPixels.remove();\n int pixel = pixels[nextPixel];\n if(pixelsSimilar(pixel, firstPixel)) {\n // yay it matches. put the neighbours.\n int xN = nextPixel % width,\n yN = nextPixel / width;\n /* the three pixels above */\n if(yN - 1 >= 0) {\n if(connect8) {\n if(xN + 1 < width) { \n addNextPixel(nextPixel - width + 1);\n }\n if(xN - 1 >= 0) {\n addNextPixel(nextPixel - width - 1);\n }\n }\n addNextPixel(nextPixel - width);\n }\n\n /* pixels left and right from the current one */\n if(xN > 0) {\n addNextPixel(nextPixel - 1);\n }\n if(xN + 1 < width) {\n addNextPixel(nextPixel + 1);\n }\n\n /* three pixels below */\n if(yN + 1 < height) {\n if(connect8) {\n if(xN + 1 < width) { \n addNextPixel(nextPixel + width + 1);\n }\n if(xN - 1 >= 0) {\n addNextPixel(nextPixel + width - 1);\n }\n }\n addNextPixel(nextPixel + width);\n }\n\n /* color it finally */\n pixels[nextPixel] = color;\n }\n }\n }\n\n @Override\n public void run(ImageProcessor ip) {\n ij.WindowManager.getCurrentImage().getCanvas().addMouseListener(this);\n this.ip = ip;\n this.pixels = (int[])ip.getPixels();\n this.state = new boolean[ip.getPixelCount()];\n this.nextPixels = new LinkedList<Integer>();\n }\n\n @Override\n public int setup(String arg0, ImagePlus arg1) {\n return DOES_RGB;\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n ij.WindowManager.getCurrentWindow().getCanvas().removeMouseListener(this);\n ij.gui.GenericDialog g = new GenericDialog(\"Please enter parameters\");\n g.addChoice(\"connection\", new String[]{\"4-connect\", \"8-connect\"}, \"8-connect\");\n g.addNumericField(\"Threshould (0..255)\", 0.0, 3);\n g.showDialog();\n\n boolean connect8 = g.getNextChoice().equals(\"8-connect\");\n threshould = (int) g.getNextNumber();\n doFill(e.getX(), e.getY(), connect8);\n ij.WindowManager.getCurrentImage().draw();\n }\n}\n"
},
{
"answer_id": 51232437,
"author": "Geograph",
"author_id": 3302804,
"author_profile": "https://Stackoverflow.com/users/3302804",
"pm_score": 2,
"selected": false,
"text": "var img = Image.FromFile(\"test.png\");\nimg = img.FloodFill(new Point(0, 0), Color.Red);\nimg.Save(\"testcomplete.png\", ImageFormat.Png);\n public static Image FloodFill(this Image img, Point pt, Color color)\n {\n Stack<Point> pixels = new Stack<Point>();\n var targetColor = ((Bitmap)img).GetPixel(pt.X, pt.Y);\n pixels.Push(pt);\n\n while (pixels.Count > 0)\n {\n Point a = pixels.Pop();\n if (a.X < img.Width && a.X > -1 && a.Y < img.Height && a.Y > -1)\n {\n if (((Bitmap)img).GetPixel(a.X, a.Y) == targetColor)\n {\n ((Bitmap)img).SetPixel(a.X, a.Y, color);\n pixels.Push(new Point(a.X - 1, a.Y));\n pixels.Push(new Point(a.X + 1, a.Y));\n pixels.Push(new Point(a.X, a.Y - 1));\n pixels.Push(new Point(a.X, a.Y + 1));\n }\n }\n }\n return img;\n }\n"
},
{
"answer_id": 56220198,
"author": "Ivan P.",
"author_id": 5128696,
"author_profile": "https://Stackoverflow.com/users/5128696",
"pm_score": 1,
"selected": false,
"text": "using System.Runtime.InteropServices;\n//insert by Zswang(wjhu111#21cn.com) at 2007-05-22\n[DllImport(\"gdi32.dll\")]\npublic static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);\n[DllImport(\"gdi32.dll\")]\npublic static extern IntPtr CreateSolidBrush(int crColor);\n[DllImport(\"gdi32.dll\")]\npublic static extern bool ExtFloodFill(IntPtr hdc, int nXStart, int nYStart, \n int crColor, uint fuFillType);\n[DllImport(\"gdi32.dll\")]\npublic static extern bool DeleteObject(IntPtr hObject);\n[DllImport(\"gdi32.dll\")]\npublic static extern int GetPixel(IntPtr hdc, int x, int y);\npublic static uint FLOODFILLBORDER = 0;\npublic static uint FLOODFILLSURFACE = 1;\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n Graphics vGraphics = Graphics.FromHwnd(Handle);\n vGraphics.DrawRectangle(Pens.Blue, new Rectangle(0, 0, 300, 300));\n vGraphics.DrawRectangle(Pens.Blue, new Rectangle(50, 70, 300, 300));\n IntPtr vDC = vGraphics.GetHdc();\n IntPtr vBrush = CreateSolidBrush(ColorTranslator.ToWin32(Color.Red));\n IntPtr vPreviouseBrush = SelectObject(vDC, vBrush);\n ExtFloodFill(vDC, 10, 10, GetPixel(vDC, 10, 10), FLOODFILLSURFACE);\n SelectObject(vDC, vPreviouseBrush);\n DeleteObject(vBrush);\n vGraphics.ReleaseHdc(vDC);\n}\n Graphics vGraphics = Graphics.FromHwnd(Handle); e.Graphics"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
367,257 | <p>I've taken over a mixed PHP4/PHP5 project which has been handed down from developer to developer, with each one making things worse. Before I spend too much time on it I'd like to develop a base-standard, with consistent formatting at a minimum.</p>
<p>Can anyone recommend a utility (Linux or Mac OS X preferably) that will reformat the code?</p>
<p>If I can set parameters which influence output (like tab-indentation, brace/bracket placement, when to split array values onto new lines etc.) then that's a benefit, though not crucial.</p>
<p>Preference goes to Open Source tools, though I'd like to know your experiences with purchased software too.</p>
| [
{
"answer_id": 9628910,
"author": "mlambie",
"author_id": 17453,
"author_profile": "https://Stackoverflow.com/users/17453",
"pm_score": 1,
"selected": false,
"text": "gg=G\n ~/.vimrc filetype plugin indent on\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17453/"
] |
367,262 | <p>I need to make some commits using Git but I would like the timestamp in git-log to be in the future.</p>
<p>How can I do a commit in git that causes a future timestamp to register in the git-log?</p>
| [
{
"answer_id": 367475,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 7,
"selected": true,
"text": "/tmp/x 604% env GIT_AUTHOR_DATE='Wed Dec 19 15:14:05 2029 -0800' git commit -m 'future!'\n[master]: created 6348548: \"Future!\"\n 1 files changed, 1 insertions(+), 0 deletions(-)\n\n/tmp/x 605% git log \n\nAuthor: Dustin Sallings <dustin@spy.net>\nDate: Wed Dec 19 15:14:05 2029 -0800\n\n Future!\n"
},
{
"answer_id": 1474183,
"author": "Hugo",
"author_id": 972,
"author_profile": "https://Stackoverflow.com/users/972",
"pm_score": 3,
"selected": false,
"text": "env GIT_AUTHOR_DATE=\"`ls -rt *.cpp|tail -1|xargs date -u -r`\" git commit -m \"Old sources retaining old change-dates of last changed\n file: `ls -rt *.cpp|tail -1`, actual commit date: `date`\"\n"
},
{
"answer_id": 5017325,
"author": "Paul Pladijs",
"author_id": 613109,
"author_profile": "https://Stackoverflow.com/users/613109",
"pm_score": 6,
"selected": false,
"text": "git commit --amend --date=\"Wed Feb 16 14:00 2037 +0100\"\n"
},
{
"answer_id": 14300605,
"author": "Dan Hunsaker",
"author_id": 1973492,
"author_profile": "https://Stackoverflow.com/users/1973492",
"pm_score": 2,
"selected": false,
"text": "sed alias newest=\"find . -path ./.git -prune -o -type f -exec stat -c \\\"%y %n\\\" '{}' + | sort -r | head -1 | sed s#'.*\\./'##\"\nGIT_AUTHOR_DATE=\"$(newest | xargs date -u -r)\" GIT_COMMITTER_DATE=\"$(newest | xargs date -u -r)\" git commit -m \"Old sources retaining old change-dates of last changed file: $(newest), actual commit date: $(date)\"\n"
},
{
"answer_id": 52066322,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "git commit --amend --date=\"Wed Feb 16 14:00 2037 +0100\"\n derrickstolee gitster commit timestamp_t author_date_slab author_date_slab --author-date log --author-date-order unsigned long commit.c timestamp_t"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,276 | <p>I seem to not understand two OOP concepts very well. Could you explain what <strong>abstraction</strong> and <strong>polymorphism</strong> are, preferably with real examples and code?</p>
<p>Thank you.</p>
| [
{
"answer_id": 367289,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "class fraction:\n int denominator\n int numerator\n fraction(obj1): denominator=-1 numerator=-1\nfraction(obj2): denominator=1 numerator=1\n (1/1) == (-1)/(-1) [1]=(1, 1), (-1, -1), (5, 5), ...\n[2]=(2, 4), (-2, -4), ...\n...\n f((1, 1)) = [1]\nf((-1, -1)) = [1]\n class pen:\n void draw(int x, int y)\n\nclass pen_thin extends pen:\n void draw(int x, int y) { color(x, y) = green; }\n\nclass pen_thick extends pen:\n void draw(int x, int y) { color(x, y) = green; \n color(x, y+1) = green; }\nand two objects:\n pen_thin(p1)\n pen_thick(p2)\n class colorizer:\n void colorize(shirt s)\n void colorize(pants p)\n obj.colorize(something)"
},
{
"answer_id": 367306,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "Object.equals(Object o) makeNoise() Animal a = new Dog();\nAnimal b = new Cat();\n makeNoise()"
},
{
"answer_id": 367396,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 4,
"selected": false,
"text": "class Set <T> { ... }\n T <T>"
},
{
"answer_id": 367538,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 4,
"selected": false,
"text": " public Amount getAmountToPay( Product product, Employee internalCustomer ) { \n Amount amount = product.getPrice();\n amount.applyDiscount( internalCustomer.getDiscount() );\n return amount;\n }\n class Employee { \n public int getDiscount();\n}\n\n\nclass InternalEmployee extends Employee { \n public int getDiscount() { \n return 10 + 2 * getWorkedYears() + 2 * getNumberOfChilds();\n }\n }\n\n class Contractor extends Employee { \n public int getDiscount() { \n return 10;\n }\n }\n Amount amount = product.getPrice();\n\n if( employee.isContractor() ) { \n amount.applyDiscount( 10 );\n } else if( employee.isSomthingElse() ) {\n amount.applyDiscount( 10 * 2 * getYrs() + 2 * getChilds() );\n } else if ( employee.contidions, condigions, conditions ) {\n amount.applyDiscount( getSomeStrageRuleHere() );\n }\n Amount amount = product.getPrice();\n amount.applyDiscount( internalCustomer.getDiscount() );\n return amount;\n"
},
{
"answer_id": 33932104,
"author": "Alok",
"author_id": 5471827,
"author_profile": "https://Stackoverflow.com/users/5471827",
"pm_score": 0,
"selected": false,
"text": "abstract class car {\n abstract void gear();\n}\n\nclass sedan extends car {\n public void gear()\n {\n //complete the method\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1602746/"
] |
367,278 | <p>I'm a fan of SVN and I am comfortable setting up my own svn repository, but I'm wondering if there are better options than creating a separate repository.</p>
<p>Basically I'm just looking for a way to keep track of or roll back changes before my code is reviewed and checked in to the main repository (SourceSafe). </p>
<p>Note: I can't control which version control system we use (would prefer svn or svk), so stuck with SourceSafe for the main repository.</p>
| [
{
"answer_id": 367302,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 3,
"selected": false,
"text": "cd $PROJECT git init # Create the repository git add . # Recursively add all files in the directory to the repository git commit # Make the initial commit hg git"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46225/"
] |
367,282 | <p>I have a content management application in the root of my website, and I'm trying to use a different app (a billing application) under a sub-folder. Unfortunately, the web.config of the root site is interfering with the sub-app.</p>
<p>Is there a way to just disable web.config inheritance for a sub-folder?</p>
<p><strong>Update:</strong>
As linked by <a href="https://stackoverflow.com/users/31474/stephen-b-burris-jr">Stephen Burris</a>, using the <code><location></code> tag can prevent inheritance for part of the web config, as follows:</p>
<pre><code><?xml version="1.0"?>
<configuration>
<configSections>
....
</configSections>
<location path="." inheritInChildApplications="false">
<appSettings>
....
</appSettings>
<connectionStrings/>
<system.web>
....
</system.web>
<system.codedom>
....
</system.codedom>
<system.webServer>
....
</system.webServer>
</location>
<runtime>
....
</runtime>
</configuration>
</code></pre>
<p>The <code><configSections></code> and <code><runtime></code> sections will not accept being enclosed in the tag...so I guess this only does most of the job. Anybody know how to do it better?</p>
| [
{
"answer_id": 367372,
"author": "devstuff",
"author_id": 41321,
"author_profile": "https://Stackoverflow.com/users/41321",
"pm_score": 3,
"selected": false,
"text": "<clear /> <add name=... />"
},
{
"answer_id": 367403,
"author": "SBurris",
"author_id": 31474,
"author_profile": "https://Stackoverflow.com/users/31474",
"pm_score": 6,
"selected": true,
"text": "<location inheritInChildApplications=\"false\">\n <NotInheritedConfigPart/>\n</location>\n"
},
{
"answer_id": 26381207,
"author": "Matteo Sganzetta",
"author_id": 1581344,
"author_profile": "https://Stackoverflow.com/users/1581344",
"pm_score": 4,
"selected": false,
"text": "enableConfigurationOverride=\"false\" <add name=\"MyAppPool\" enableConfigurationOverride=\"false\" autoStart=\"true\" managedRuntimeVersion=\"v4.0\" managedPipelineMode=\"Integrated\" >\n <processModel identityType=\"NetworkService\" />\n</add>\n"
},
{
"answer_id": 71846683,
"author": "Michael",
"author_id": 2868597,
"author_profile": "https://Stackoverflow.com/users/2868597",
"pm_score": 0,
"selected": false,
"text": "<location> <system.web> </system.web> <location path=\".\" inheritInChildApplications=\"false\"> <system.webserver> <location> <location path=\".\" inheritInChildApplications=\"false\">\n <system.web>\n ...\n </system.web>\n</location>\n <location path=\".\" inheritInChildApplications=\"false\">\n <system.webserver>\n ...\n </system.webserver>\n</location>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23276/"
] |
367,308 | <p>I'm working on a project where there is a lot of external service messaging. A good way to describe it in only a slightly "hyperbolas" way would be an application where the system has to send messages to the Flicker API, the Facebook API, and the Netflix API.</p>
<p>To support disconnected scenarios, logging concerns, developer usability, configuration, etc... I've experimented using an approach which heavily uses generics and expression trees. The end result looks like this:</p>
<pre><code>Messenger<NetflixApi>.SendCustom( netflix => netflix.RecommendMovie("my message"));
</code></pre>
<p>Overall I'm happy with the end result but feel like I've made a mistake, or overlooked a design principal someplace with regards to testing and disconnected scenarios.</p>
<p>During testing, whether automated, unit, or human based, I've implemented an object factory that initially uses DI to perform the correct action in "Live mode" and used Mocks to provide a sort of sterile messenger that doesn't do anything at all when in a testing mode.</p>
<p>I've only seen or read about Mocks being used in pure TDD mode and not being used to be sort of a dumb object. The approaches I've seen would revolve around stubbing or mocking out the HTTP communication functionality which all the APIs I'm using depend on. </p>
<p>My main concern is that will all the different services I expect to connect to I'd end up having to do a lot of granular work substituting specific HTTP implementation and if I used a stub approach I'd have 3 classes for each of these services( IService, ConcreteService, StubService ) and maintaining those when implementing a new method or changing anything would be a real PITA.</p>
<p>In the current implementation I'm using Mocks to get "sterile mode" for free almost without having to implement anything extra just to conform to a certain testing principal. </p>
<p>The question is am I missing something? Did I violate a design principal using Mocks in a more... convenient way?</p>
<p>Can anybody offer any advice on how to get a sterile mode out of many different outside services without jumping through a lot of hoops?</p>
<p>Does this question make sense? </p>
<p>Thanks for all the answers.</p>
<p>Edit #1:</p>
<p>I wasn't clear in my original question. Any null or mock objects are to be used purely in a development/debug/testing environment. In production the code that sends these messages will be the actual implementation of them.</p>
<p>I voted everybody up because there seem to be a lot of different solutions to this problem and I'll be exploring each one. </p>
<p>Please don't think this question has been answered yet, I'd appreciate as much advice as I can get.</p>
| [
{
"answer_id": 367543,
"author": "NicoGranelli",
"author_id": 451623,
"author_profile": "https://Stackoverflow.com/users/451623",
"pm_score": 4,
"selected": true,
"text": "class Logger{\n private static ILogger _Logger;\n\n static Logger(){\n //DI injection here\n _Logger = new NullLogger(); //or\n _Logger = new TraceLogger();\n }\n}\n\ninterface ILogger{\n void Log(string Message);\n}\n\ninternal class TraceLogger:ILooger{\n public void Log(string Message){\n //Code here\n }\n}\n\ninternal class NullLogger{\n public void Log(string Message){\n //Don't don anything, in purporse\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25300/"
] |
367,310 | <p>I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user.</p>
<p>Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask.</p>
<pre><code>char someArr[];
do{
someArr = new char[10];
Sleep(100); // no justification for choosing 100 ms
} while ( someArr == NULL );
</code></pre>
<p>Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere?</p>
<p><strong>FINAL UPDATE:</strong> Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).</p>
| [
{
"answer_id": 395953,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 1,
"selected": false,
"text": "void my_new_handler() {\n // make room for memory, then return, or throw bad_alloc if\n // nothing can be freed.\n}\n\nint main() {\n std::set_new_handler(&my_new_handler);\n\n // every allocation done will ask my_new_handler if there is\n // no memory for use anymore. This answer tells you what the\n // standard allocator function does: \n // https://stackoverflow.com/questions/377178\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34910/"
] |
367,325 | <p>Here is an interesting piece of code that my fellow team members were just having a slightly heated discussion about...</p>
<pre><code> Dim fred As Integer
If True Then fred = 5 : fred = 3 : fred = 6 Else fred = 4 : fred = 2 : fred = 1
</code></pre>
<p>After executing the above code snippet, what is the value of <em>fred</em>?</p>
<p>Try not to cheat and debug the code.</p>
<p>This is a highly contrived code example that started out as an example of using the colon with an If statement, but then someone decided to take it upon themselves to proffer a result for <em>fred</em>.</p>
<p><strong>UPDATE</strong>:
I would not normally write code like this and this snippet only serves as an example. As it so happens, this question originated from a discussion involving the creation of a coding standards document for our team.</p>
| [
{
"answer_id": 367342,
"author": "user21826",
"author_id": 21826,
"author_profile": "https://Stackoverflow.com/users/21826",
"pm_score": 0,
"selected": false,
"text": "\nif (condition) then\n statement\n statement\nelse\n statement\n statement\nend if\n"
},
{
"answer_id": 367344,
"author": "Scott Wisniewski",
"author_id": 1737192,
"author_profile": "https://Stackoverflow.com/users/1737192",
"pm_score": 5,
"selected": true,
"text": "If BooleanExpression Then Statements [ Else Statements ] StatementTerminator\n Statements ::=\n[ Statement ] |\nStatements : [ Statement ]\n"
},
{
"answer_id": 367345,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 2,
"selected": false,
"text": "fred 6 Dim fred As Integer\n\nIf True Then\n fred = 5\n fred = 3\n fred = 6\nElse\n fred = 4\n fred = 2\n fred = 1\nEnd If\n if (condition)\n do_something();\n do_other_thing();\n do_something do_other_thing condition do_other_thing"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19377/"
] |
367,328 | <p>I received a dump file of a SVN repository that I'm moving to my server. Let's call it myserver.com/svn. The load statement prints out a long list of files loaded and reports no error. However, once I try to access the repository for checkout, or relocate my existing checkout, I'm told:</p>
<pre><code>Repository moved temporarily to 'http://www.myserver.com/svn'; please relocate
</code></pre>
<p>In other words, my new repository reports that it has temporarily moved to itself. How do I get past that? I can't find anything about this message in documentation about the svnadmin load command.</p>
| [
{
"answer_id": 1118406,
"author": "kikito",
"author_id": 312586,
"author_profile": "https://Stackoverflow.com/users/312586",
"pm_score": 0,
"selected": false,
"text": "ErrorDocument 404 http://www.myserver.com/svn\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28565/"
] |
367,343 | <p>I have the following code:</p>
<pre><code>abstract class AbstractParent {
function __construct($param) { print_r($param); }
public static function test() { return new self(1234); }
}
class SpecificClass extends AbstractParent {}
</code></pre>
<p>When I invoke <code>SpecificClass::test()</code>, I am getting an error:</p>
<pre>Fatal error: Cannot instantiate abstract class AbstractParent</pre>
<p>So what I basically want is just to let <code>AbstractParent</code>'s <code>test()</code> instantiate class where this <code>test()</code> was called from (so, in my example, instantiate <code>SpecificClass</code>).</p>
| [
{
"answer_id": 367357,
"author": "Alexei Tenitski",
"author_id": 45508,
"author_profile": "https://Stackoverflow.com/users/45508",
"pm_score": 2,
"selected": false,
"text": "abstract class AbstractParent {\n function __construct($param) { print_r($param); }\n abstract public static function test();\n private static function test2($classname) { return new $classname(1234); }\n}\n\nclass SpecificClass extends AbstractParent {\n public static function test() {return self::test2(__CLASS__);}\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45652/"
] |
367,349 | <p>How do you submit from a dropdownlist "onchange" event from inside of an ajax form?</p>
<p>According to the following question: <a href="https://stackoverflow.com/questions/364505/how-do-you-submit-a-dropdownlist-in-aspnet-mvc">How do you submit a dropdownlist in asp.net mvc</a>, from inside of an Html.BeginFrom you can set onchange="this.form.submit" and changing the dropdown posts back.</p>
<p>However, using the following code (inside an Ajax.BeginFrom):</p>
<pre><code><% using (Ajax.BeginForm("UpdateForm", new AjaxOptions() { UpdateTargetId = "updateText" })) { %>
<h2>Top Authors</h2>
Sort by:&nbsp;<%=Html.DropDownList("sortByList", new SelectList(ViewData["SortOptions"], new { onchange = "this.form.submit()" })%>
<%= Html.TextBox("updateText")%>
<% } %>
</code></pre>
<p>Posts back to the controller action, but the entire page is replaced with the contents of the "updateText" text, rather than just what is inside the "updateText" textbox.</p>
<p>Thus, rather than replacing just the area inside the Ajax.BeginForm, the entire page is replaced.</p>
<p>What is the correct way for the dropdownlist to call this.form.submit such that only the area inside the Ajax.BeginForm?</p>
| [
{
"answer_id": 367401,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 2,
"selected": false,
"text": "$(\"#yourDropdown\").change(function() {\n var f = $(\"#yourForm\");\n var action = f.attr(\"action\");\n var serializedForm = f.serialize();\n $.post(action, serializedForm,\n function () { alert(\"Finished! Can do something here!\") });\n});\n"
},
{
"answer_id": 384039,
"author": "Adam",
"author_id": 37742,
"author_profile": "https://Stackoverflow.com/users/37742",
"pm_score": 0,
"selected": false,
"text": "Html.RenderPartial(\"viewname\"); if (Request.IsMvcAjaxRequest()){ return PartialView(\"viewname\");}\nelse{\n//Non Ajax code here.\n}"
},
{
"answer_id": 971280,
"author": "Francisco",
"author_id": 119980,
"author_profile": "https://Stackoverflow.com/users/119980",
"pm_score": 2,
"selected": false,
"text": "<%=Html.DropDownList(\"data\", ViewData[\"data\"] as SelectList\n, new { onchange = \"$(\\\"#button\" + Model.IdIndex + \"\\\").click();\" })%>\n\n\n<input type=\"submit\" id=\"button<%=Model.IdIndex %>\" style=\"display: none\" /><br />\n"
},
{
"answer_id": 1914353,
"author": "Stelloy",
"author_id": 213609,
"author_profile": "https://Stackoverflow.com/users/213609",
"pm_score": 1,
"selected": false,
"text": "<%= Html.DropDownList(\"sortByList\", new SelectList(ViewData[\"SortOptions\"]) %> \n<%= Html.TextBox(\"updateText\") %>\n\n<script>\n$(\"#sortByList\").change(function() {\n $.ajax({\n url: <%= Url.Action(\"UpdateForm\")%>,\n type: \"POST\",\n data: { 'sortBy': $(this).val() },\n dataType: \"json\",\n success: function(result) { $('#updateText').text(result); },\n error: function(error) { alert(error); }\n })\n\n});\n</script>\n public JsonResult UpdateForm(string sortBy)\n{\n string result = \"Your result here\";\n return Json(result);\n}\n"
},
{
"answer_id": 4326151,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 5,
"selected": false,
"text": "Html.DropDownList(...) new { onchange = \"this.form.submit()\" }\n new { onchange = \"this.form.onsubmit()\" }\n Ajax.BeginForm() onsubmit() submit() onsubmit() onsubmit()"
},
{
"answer_id": 10646174,
"author": "Carbosound1",
"author_id": 1066906,
"author_profile": "https://Stackoverflow.com/users/1066906",
"pm_score": 1,
"selected": false,
"text": " <button id=\"submitButton\" type=\"submit\" class=\"btn\" style=\"vertical-align: top\"><i class=\"icon\"></i> replace</button>\n new { onchange = \"document.getElementById('submitButton').click()\" }\n"
},
{
"answer_id": 24411912,
"author": "Bonomi",
"author_id": 909986,
"author_profile": "https://Stackoverflow.com/users/909986",
"pm_score": 3,
"selected": false,
"text": "this.form.submit()\n $(this.form).submit();\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,368 | <p>Is it possible to set a symbol for conditional compilation by setting up properties in an Xcode project?</p>
<p>My aim is to to create a symbol that is available to all files, without having to use import/include, so that a set of common classes can have a special behavior in some projects. Like the following, but with my own symbols.</p>
<pre><code>#if TARGET_IPHONE_SIMULATOR
...
#endif
</code></pre>
| [
{
"answer_id": 367430,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 8,
"selected": true,
"text": "GCC_PREPROCESSOR_DEFINITIONS constant_1=VALUE constant_2=VALUE\n #ifdef"
},
{
"answer_id": 1384658,
"author": "hEADcRASH",
"author_id": 169138,
"author_profile": "https://Stackoverflow.com/users/169138",
"pm_score": 2,
"selected": false,
"text": "#if DEBUG\n printf(\"DEBUG is set!\");\n#endif \n"
},
{
"answer_id": 8793346,
"author": "Stickley",
"author_id": 268416,
"author_profile": "https://Stackoverflow.com/users/268416",
"pm_score": 5,
"selected": false,
"text": "APPURL_NSString=\\@\\\"www.foobar.org\\\"\n objectManager.client.baseURL = APPURL_NSString;\n"
},
{
"answer_id": 8949373,
"author": "chunkyguy",
"author_id": 286094,
"author_profile": "https://Stackoverflow.com/users/286094",
"pm_score": 3,
"selected": false,
"text": "*_Prefix.pch"
},
{
"answer_id": 51609855,
"author": "Petr Javorik",
"author_id": 5216949,
"author_profile": "https://Stackoverflow.com/users/5216949",
"pm_score": 2,
"selected": false,
"text": "const char* const char* ...\n#ifndef JSON_DEFINITIONS_FILE_PATH\nstatic constexpr auto JSON_DEFINITIONS_FILE_PATH = \"definitions.json\";\n#endif\n...\nFILE *pFileIn = fopen(JSON_DEFINITIONS_FILE_PATH, \"r\");\n...\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36182/"
] |
367,377 | <p>Suppose you have a software package. You want to make it a gem, because gems are the de facto standard way to distribute anything in the Ruby world. Gems are great -- for libraries. But for real applications, the Rubygems system seems lacking. Only "recently" did they introduce a way to mark executables to be placed in somewhere in the system wide executable PATH. Unfortunately, Ruby gems still seems to be wanting in other aspects of software packaging, namely putting configuration files in places like /etc, or documentation under /usr/share/doc. Or is it? My question is:</p>
<p>Can I put instructions or code in a gemspec to have configuration installed into /etc, and documentation under some sensible, standardized place (like /usr/share/doc)? Or perhaps, as a workaround, can a post-install script be run to do these things?</p>
<p>For reference: <a href="http://www.rubygems.org/read/book/4" rel="nofollow noreferrer">the GemSpec specification</a>.</p>
<p>Note that rubygems.org is down at the time of this writing. Here's the Google cache of that page: <a href="http://74.125.95.132/search?q=cache:JwJO6slR4BwJ:www.rubygems.org/read/chapter/20+http://www.rubygems.org/read/chapter/20%23page85&hl=en&ct=clnk&cd=1" rel="nofollow noreferrer">http://74.125.95.132/search?q=cache:JwJO6slR4BwJ:www.rubygems.org/read/chapter/20+http://www.rubygems.org/read/chapter/20%23page85&hl=en&ct=clnk&cd=1</a></p>
<p>If you examine <a href="http://rubygems.rubyforge.org/svn/trunk/lib/rubygems/specification.rb" rel="nofollow noreferrer">the specification.rb file in the repo</a>, and scroll down towards the end (search for ":section: Required gemspec attributes"), you can see what appear to be the currently supported attributes. I see nothing in there that looks like what I want.</p>
| [
{
"answer_id": 367430,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 8,
"selected": true,
"text": "GCC_PREPROCESSOR_DEFINITIONS constant_1=VALUE constant_2=VALUE\n #ifdef"
},
{
"answer_id": 1384658,
"author": "hEADcRASH",
"author_id": 169138,
"author_profile": "https://Stackoverflow.com/users/169138",
"pm_score": 2,
"selected": false,
"text": "#if DEBUG\n printf(\"DEBUG is set!\");\n#endif \n"
},
{
"answer_id": 8793346,
"author": "Stickley",
"author_id": 268416,
"author_profile": "https://Stackoverflow.com/users/268416",
"pm_score": 5,
"selected": false,
"text": "APPURL_NSString=\\@\\\"www.foobar.org\\\"\n objectManager.client.baseURL = APPURL_NSString;\n"
},
{
"answer_id": 8949373,
"author": "chunkyguy",
"author_id": 286094,
"author_profile": "https://Stackoverflow.com/users/286094",
"pm_score": 3,
"selected": false,
"text": "*_Prefix.pch"
},
{
"answer_id": 51609855,
"author": "Petr Javorik",
"author_id": 5216949,
"author_profile": "https://Stackoverflow.com/users/5216949",
"pm_score": 2,
"selected": false,
"text": "const char* const char* ...\n#ifndef JSON_DEFINITIONS_FILE_PATH\nstatic constexpr auto JSON_DEFINITIONS_FILE_PATH = \"definitions.json\";\n#endif\n...\nFILE *pFileIn = fopen(JSON_DEFINITIONS_FILE_PATH, \"r\");\n...\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28558/"
] |
367,378 | <p>I'm creating my own dictionary and I am having trouble implementing the <a href="http://msdn.microsoft.com/en-us/library/ms132143(VS.85).aspx" rel="noreferrer">TryGetValue</a> function. When the key isn't found, I don't have anything to assign to the out parameter, so I leave it as is. This results in the following error: "The out parameter 'value' must be assigned to before control leaves the current method"</p>
<p>So, basically, I need a way to get the default value (0, false or nullptr depending on type). My code is similar to the following:</p>
<pre><code>class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
bool IDictionary<K, V>.TryGetValue (K key, out V value)
{
return false;
}
....
}
</code></pre>
| [
{
"answer_id": 367380,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 3,
"selected": false,
"text": "return default(int);\n\nreturn default(bool);\n\nreturn default(MyObject);\n class MyEmptyDictionary<K, V> : IDictionary<K, V>\n{\n bool IDictionary<K, V>.TryGetValue (K key, out V value)\n {\n ... get your value ...\n if (notFound) {\n value = default(V);\n return false;\n }\n }\n\n....\n"
},
{
"answer_id": 367383,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 7,
"selected": true,
"text": "default class MyEmptyDictionary<K, V> : IDictionary<K, V>\n{\n bool IDictionary<K, V>.TryGetValue (K key, out V value)\n {\n value = default(V);\n return false;\n }\n\n ....\n\n}\n"
},
{
"answer_id": 370035,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 3,
"selected": false,
"text": "default(T)\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4891/"
] |
367,400 | <p>Lately I've been seeing a lot of talk regarding PHP's lack of late static binding until 5.3. </p>
<p>From what I've read proper implementations of stuff like ActiveRecord are not possible until the language has this feature.</p>
<p>So, I'm curious about:</p>
<ul>
<li>Which languages do support it,
specifically those commonly
associated with web development such
as Python, Ruby, Perl, Java, C#,
(JavaScript?).</li>
<li>Which actually make use of it on a
regular basis?</li>
</ul>
| [
{
"answer_id": 367410,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": -1,
"selected": false,
"text": "class A {\n static $word = \"hello\";\n static function hello() {print self::$word;}\n}\n\nclass B extends A {\n static $word = \"bye\";\n}\n\nB::hello();\n hello() class B hello() class B $word B::$word B::hello() A::$word A::hello() self static A::hello() class A {\n static $word = \"Welcome\";\n static function hello() {print static::$word;}\n}\n\nclass B extends A {\n static $word = \"bye\";\n}\n\nB::hello();\n"
},
{
"answer_id": 367564,
"author": "navitronic",
"author_id": 46264,
"author_profile": "https://Stackoverflow.com/users/46264",
"pm_score": 2,
"selected": false,
"text": "class Specific_Model extends Model{\n\n public static function GetAll($options = null){\n\n parent::GetAll($options, get_class());\n\n }\n\n}\n\n\nclass Model{\n\n public static function GetAll($options = null, $class = null){\n\n if(is_null($class)) $class = get_class(); \n\n /* Do stuff here */\n\n }\n\n}\n Specific_Model::GetAll($options);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41111/"
] |
367,411 | <p>When discussing the evolution of computer languages, Alan Kay says that the single most important attribute of his Smalltalk is late binding; it gives the language its malleability and extensibility, and allows inappropriate coupling to be refactored out over time. Do you agree? Are there compensating advantages for early binding that explain why it seems to be the dominant of the two paradigms for domains where either could be used?</p>
<p>My personal experience (which is not broad or deep enough to be authoritative), based on implement web applications with javascript, jQuery, jsext, actionscript, php, java, RoR and asp.net seems to suggest a positive correlation between late binding and bloat reduction. Early binding I'm sure helps detect and prevent some typesafety errors, but so do autocompletion and a good IDE, and good programming practices in general. So I tend to catch myself rooting for the late binding side, before my risk-avoidance side restores my rational perspective.</p>
<p>But I really don't have a good sense for how to balance the tradeoffs.</p>
| [
{
"answer_id": 368276,
"author": "Peter Gfader",
"author_id": 35693,
"author_profile": "https://Stackoverflow.com/users/35693",
"pm_score": 2,
"selected": false,
"text": "var excel = CreateObject(\"Excel.Application\");\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31641/"
] |
367,426 | <p>This is a total newbie question, so thanks in advance. I'm trying to get my head around the difference between divs and spans, and when and how to use them.</p>
<p>Say for instance, I want to have an image left justified, and I want the text to flow around the image on the right, while maintaining justification. If the text flows past the image, I want it to wrap around the bottom of the image...same as what we call in the layout world, "wrap".</p>
<p>I'm looking for an example to reference, so in your answer can you provide an example of the mark up?</p>
<p>Huge Thanks!!!</p>
| [
{
"answer_id": 367434,
"author": "Elle H",
"author_id": 23666,
"author_profile": "https://Stackoverflow.com/users/23666",
"pm_score": 2,
"selected": false,
"text": "<img src=\"picture.jpg\" alt=\"An image\" style=\"float: left\" />\nLorem ipsum dolor sit amet, consectetur adipiscing elit. In eros. Curabitur posuere. Cras sodales leo quis mauris. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum adipiscing nunc vel arcu. Ut sed quam non est molestie commodo. Suspendisse metus erat, cursus fermentum, faucibus nec, pulvinar et, lorem. Praesent odio. In interdum imperdiet enim.\n"
},
{
"answer_id": 367441,
"author": "Geoff Dalgas",
"author_id": 2,
"author_profile": "https://Stackoverflow.com/users/2",
"pm_score": 4,
"selected": true,
"text": "<div>\ntest test test test <img src=\"\" alt=\"\" style=\"float:left;margin:8px 0 0 8px; display:inline\" /> test test test test test test test test test test test test \n</div>\n"
},
{
"answer_id": 463912,
"author": "Marco Luglio",
"author_id": 14263,
"author_profile": "https://Stackoverflow.com/users/14263",
"pm_score": 1,
"selected": false,
"text": "p h1 table ul blockquote div img strong em input a span vertical-align img strong em input a span <span style=\"display:block\">\n this will be displayed like a div,\n but still cannnot contain block level elements\n</span>\n <span class=\"tel\">555-5555</span> <tel> <p><img src=\"image.jpg\" style=\"float: right\" alt=\"my image\" />Long paragraph.</p>\n <p>unrelated to the image</p>\n<div>\n<img src=\"image.jpg\" style=\"float: right\" alt=\"my image\" />\n<p>Long paragraph.</p>\n</div>\n div p"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39781/"
] |
367,440 | <p>I want to create an associative array:</p>
<pre><code>var aa = {} // Equivalent to Object(), new Object(), etc...
</code></pre>
<p>And I want to be sure that any key I access is going to be a number:</p>
<pre><code>aa['hey'] = 4.3;
aa['btar'] = 43.1;
</code></pre>
<p>I know JavaScript doesn't have typing, so I can't automatically check this, but I can ensure in my own code that I only assign strings to this <code>aa</code>.</p>
<p>Now I'm taking keys from the user. I want to display the value for that key. However, if the user gives me something like "toString", the user gets back a function, not an int! Is there a way to make sure any string the user gives me is only something I define?</p>
<p>Is the only solution something like the following?</p>
<pre><code>delete aa['toString'];
delete aa['hasOwnProperty'];
</code></pre>
<p>etc...</p>
| [
{
"answer_id": 367453,
"author": "Moss Collum",
"author_id": 13210,
"author_profile": "https://Stackoverflow.com/users/13210",
"pm_score": 2,
"selected": false,
"text": "function findNumber(userEnteredKey) {\n return aa[userEnteredKey];\n}\n function findNumber(userEnteredKey) {\n if (Object.prototype.hasOwnProperty.call(aa, userEnteredKey))\n return aa[userEnteredKey];\n}\n"
},
{
"answer_id": 367454,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 3,
"selected": true,
"text": "function getValue(id){\n return (!isNaN(aa[id])) ? aa[id] : undefined;\n}\n function getValue(hash,key) {\n return Object.prototype.hasOwnProperty.call(hash,key) ? hash[key] : undefined;\n}\n var test = {\n 2: \"Defined as numeric\",\n \"2\": \"Defined as string\"\n}\n\nalert(test[2]); // Alerts \"Defined as string\"\n var test = {}, test2 = {};\ntest[test2] = \"message\"; // Using an object as a key.\n\nalert(test[test2]); // Alerts \"message\". It looks like it works...\n\nalert(test[test2.toString()]);\n// If it really was an object this would not have worked,\n// but it also alerts \"message\".\n var test = {};\n\nvar test2 = {\n toString:function(){return \"some_unique_value\";}\n // Note that the attribute name (toString) don't need quotes.\n}\n\ntest[test2] = \"message\";\nalert(test[\"some_unique_value\"]); // Alerts \"message\".\n"
},
{
"answer_id": 368296,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 2,
"selected": false,
"text": "var a = {};\nvar k = 'MYAPP.COLLECTIONFOO.KEY.';\n\nfunction setkey(userstring)\n{\n a[k + userstring] = 42;\n}\n\nfunction getkey(userstring)\n{\n return a[k + userstring];\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
367,442 | <p>I've been trying to use Zsh within my emacs session, without emacs remapping all the Zsh keys. I found ansi-term works pretty well for this but, I'm still having some problems. I was getting lots of junk characters outputted with, I was able to fix it with:</p>
<pre><code>## Setup proper term information for emacs ansi-term mode
[[ $TERM == eterm-color ]] && export TERM=xterm
</code></pre>
<p>But everything still doesn't work perfectly. Now I am having trouble with output being drawn offscreen , especially when using something like C-r for search.</p>
<p>What I found is that it works fine if you don't resize the window. I can reproduce it like:</p>
<ol>
<li>Launch a clean <code>emacs -q</code></li>
<li>Start <code>ansi-term</code> and use <code>zsh</code></li>
<li>Make window fullscreen</li>
<li>Output something that fills the screen</li>
<li>Type <kbd>C-r</kbd></li>
<li>The prompt will be off the screen</li>
</ol>
<p>Maybe there is some way I can make the space between the output and the minibuffer larger to compensate for the overshoot?</p>
<p>Anyone else have Zsh + Ansi-term working properly?</p>
| [
{
"answer_id": 369938,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "(custom-set-variables\n '(fringe-mode nil nil (fringe))\n '(fringes-outside-margins t t))\n"
},
{
"answer_id": 2879086,
"author": "Sandeep",
"author_id": 130208,
"author_profile": "https://Stackoverflow.com/users/130208",
"pm_score": 1,
"selected": false,
"text": ";; ansi-term\n\n(global-set-key \"\\C-x\\C-a\" '(lambda ()(interactive)(ansi-term \"/bin/zsh\")))\n(global-set-key \"\\C-x\\ a\" '(lambda ()(interactive)(ansi-term \"/bin/zsh\")))\n"
},
{
"answer_id": 10050104,
"author": "bengineerd",
"author_id": 10428,
"author_profile": "https://Stackoverflow.com/users/10428",
"pm_score": 4,
"selected": false,
"text": "if [ -n \"$INSIDE_EMACS\" ]; then\n chpwd() { print -P \"\\033AnSiTc %d\" }\n print -P \"\\033AnSiTu %n\"\n print -P \"\\033AnSiTc %d\"\nfi\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,444 | <p>I need to show an object in PropertyGrid with the following requirements: the object and its sub object must be read-only, able to activate PropertyGrid's CollectionEditors.</p>
<p>I found a sample that's closely match to what I need but there's an unexpected behaviour I couldn't figure out. I have more than one PropertyGrids each for different objects. In SetBrowsablePropertiesAsReadOnly, I loop one object but suprisingly all of PropertyGrids in my project become readonly. Can anybody help me out. Here's the code:</p>
<pre><code>
Imports System.Reflection
Imports System.ComponentModel
Public Class PropertyGridEx
Inherits PropertyGrid
Private isReadOnly As Boolean
Public Property [ReadOnly]() As Boolean
Get
Return Me.isReadOnly
End Get
Set(ByVal value As Boolean)
Me.isReadOnly = value
Me.SetBrowsablePropertiesAsReadOnly(Me.SelectedObject, value)
End Set
End Property
Protected Overloads Sub OnSelectedObjectsChanged(ByVal e As EventArgs)
Me.SetBrowsablePropertiesAsReadOnly(Me.SelectedObject, Me.isReadOnly)
MyBase.OnSelectedObjectsChanged(e)
End Sub
Private Sub SetBrowsablePropertiesAsReadOnly(ByRef selectedObject As Object, ByVal isReadOnly As Boolean)
If selectedObject IsNot Nothing Then
Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(selectedObject)
For Each propDescript As PropertyDescriptor In props
If propDescript.IsBrowsable AndAlso propDescript.PropertyType.GetInterface("ICollection", True) Is Nothing Then
Dim attr As ReadOnlyAttribute = TryCast(propDescript.Attributes(GetType(ReadOnlyAttribute)), ReadOnlyAttribute)
If attr IsNot Nothing Then
Dim field As FieldInfo = attr.[GetType]().GetField("isReadOnly", BindingFlags.NonPublic Or BindingFlags.Instance)
field.SetValue(attr, isReadOnly, BindingFlags.NonPublic Or BindingFlags.Instance, Nothing, Nothing)
End If
End If
Next
End If
End Sub
End Class
</code></pre>
| [
{
"answer_id": 369938,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "(custom-set-variables\n '(fringe-mode nil nil (fringe))\n '(fringes-outside-margins t t))\n"
},
{
"answer_id": 2879086,
"author": "Sandeep",
"author_id": 130208,
"author_profile": "https://Stackoverflow.com/users/130208",
"pm_score": 1,
"selected": false,
"text": ";; ansi-term\n\n(global-set-key \"\\C-x\\C-a\" '(lambda ()(interactive)(ansi-term \"/bin/zsh\")))\n(global-set-key \"\\C-x\\ a\" '(lambda ()(interactive)(ansi-term \"/bin/zsh\")))\n"
},
{
"answer_id": 10050104,
"author": "bengineerd",
"author_id": 10428,
"author_profile": "https://Stackoverflow.com/users/10428",
"pm_score": 4,
"selected": false,
"text": "if [ -n \"$INSIDE_EMACS\" ]; then\n chpwd() { print -P \"\\033AnSiTc %d\" }\n print -P \"\\033AnSiTu %n\"\n print -P \"\\033AnSiTc %d\"\nfi\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,448 | <p>I'm using the following code within a VB 6.0 application to allow give the application a system tray icon:</p>
<pre><code>Option Explicit
'user defined type required by Shell_NotifyIcon API call
Public Type NOTIFYICONDATA
cbSize As Long
hwnd As Long
uId As Long
uFlags As Long
uCallBackMessage As Long
hIcon As Long
szTip As String * 64
End Type
'constants required by Shell_NotifyIcon API call:
Public Const NIM_ADD = &H0
Public Const NIM_MODIFY = &H1
Public Const NIM_DELETE = &H2
Public Const NIF_MESSAGE = &H1
Public Const NIF_ICON = &H2
Public Const NIF_TIP = &H4
Public Const WM_MOUSEMOVE = &H200
Public Const WM_LBUTTONDOWN = &H201 'Button down
Public Const WM_LBUTTONUP = &H202 'Button up
Public Const WM_LBUTTONDBLCLK = &H203 'Double-click
Public Const WM_RBUTTONDOWN = &H204 'Button down
Public Const WM_RBUTTONUP = &H205 'Button up
Public Const WM_RBUTTONDBLCLK = &H206 'Double-click
Public Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function Shell_NotifyIcon Lib "shell32" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, pnid As NOTIFYICONDATA) As Boolean
Public nid As NOTIFYICONDATA
</code></pre>
<p>I want the application to minimize to the system tray when you click the Window's X to close it. I accomplish this with the following code in the form's QueryUnload event:</p>
<pre><code>Me.WindowState = vbMinimized
Me.Hide
</code></pre>
<p>In the form's Unload event I do the following:</p>
<pre><code>Shell_NotifyIcon NIM_DELETE, nid
</code></pre>
<p>The PROBLEM is that when I shut down the operating system and Windows sends the WM_CLOSE message to the app, QueryUnload is being fired but apparently not the Unload event, since Windows prompts me that it wants to end my task. </p>
<p>Any ideas on how to get the application to close gracefully on Windows shutdown?</p>
<p>Thanks</p>
| [
{
"answer_id": 367463,
"author": "JFV",
"author_id": 1391,
"author_profile": "https://Stackoverflow.com/users/1391",
"pm_score": 4,
"selected": true,
"text": "Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)\n Select Case UnloadMode\n Case 1, 2, 3 'If the program is being terminated by Code, Windows shutting down, or Task Manager\n Cancel = False 'Allow the program termination\n Unload Me\n Case Else\n Cancel = True 'Else disallow the termination\n End Select\nEnd Sub\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46249/"
] |
367,449 | <p>An RGB color is composed of three components: Red (0-255), Green (0-255) and Blue (0-255).</p>
<p>What exactly is BGR color space? How is it different from RGB color space?</p>
| [
{
"answer_id": 367458,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "0 16777215 0xffffff"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43076/"
] |
367,457 | <p>I have a list of objects implementing an interface, and a list of that interface:</p>
<pre><code>public interface IAM
{
int ID { get; set; }
void Save();
}
public class concreteIAM : IAM
{
public int ID { get; set; }
internal void Save(){
//save the object
}
//other staff for this particular class
}
public class MyList : List<IAM>
{
public void Save()
{
foreach (IAM iam in this)
{
iam.Save();
}
}
//other staff for this particular class
}
</code></pre>
<p>The previous code doesn't compile because the compiler requires all the interface members to be public.</p>
<pre><code>internal void Save(){
</code></pre>
<p>But i don't want to allow the from outside my DLL to save the <code>ConcreteIAM</code>, it only should be saved through the <code>MyList</code>.</p>
<p>Any way to do this?</p>
<p><strong>Update#1</strong>: Hi all, thanks for the answers so far, but none of them is exactly what i need:</p>
<p>The interface needs to be public because it is the signature the client from outside the dll will use, along with <code>ID</code> and other properties i didn't bother to write in the example to keep it simple.</p>
<p>Andrew, I don't think the solution is create a factory to create another object that will contain the <code>IAM</code> members + Save. I am still thinking... Any other ideas?</p>
| [
{
"answer_id": 367464,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 3,
"selected": false,
"text": "public abstract class AM\n{\n public int ID { get; set; }\n internal abstract void Save();\n}\n\npublic class concreteIAM : AM\n{\n internal override void Save()\n {\n //Do some save stuff\n }\n}\n public class AMList : List<AM>\n{\n public void SaveItems()\n {\n foreach (var item in this)\n {\n item.Save();\n }\n }\n}\n"
},
{
"answer_id": 367529,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 1,
"selected": false,
"text": "internal interface IAMSaver { void Save(IAM item); }\n\ninternal class AMSaverFactory {\n IAMSaver GetSaver(Type itemType) { ... }\n}\n\npublic class MyList : List<IAM>\n{\n public void Save()\n {\n foreach (IAM itemin this)\n {\n IAMSaver saver = SaverFactory.GetSaver(item.GetType());\n saver.Save(item)\n }\n }\n}\n"
},
{
"answer_id": 367555,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 1,
"selected": false,
"text": " internal interface IPersist\n {\n void Save();\n }\n public class Concrete : IPersist\n {\n void IPersist.Save()\n {\n Console.WriteLine(\"Yeah!\");\n }\n }\n\n// Mylist.cs in the same assembly can still call save like\npublic void SaveItems()\n {\n foreach (IPersist item in this)\n {\n item.Save();\n }\n }\n new Concrete().Save(); // doesn't compile. 'Concrete' does not contain a definition for 'Save'\n"
},
{
"answer_id": 367897,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 6,
"selected": false,
"text": "Save()"
},
{
"answer_id": 367913,
"author": "MZywitza",
"author_id": 44243,
"author_profile": "https://Stackoverflow.com/users/44243",
"pm_score": 1,
"selected": false,
"text": "public interface IAM\n{\n int ID { get; set; }\n}\n\n\ninternal interface IAMSavable\n{\n void Save();\n}\n\npublic class concreteIAM : IAM, IAMSavable\n{\n public int ID{get;set;}\n public void IAMSavable.Save(){\n //save the object\n }\n\n //other staff for this particular class\n}\n\npublic class MyList : List<IAM>\n{\n public void Save()\n {\n foreach (IAM iam in this)\n {\n ((IAMSavable)iam).Save();\n }\n }\n\n //other staff for this particular class\n}\n"
},
{
"answer_id": 367924,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 1,
"selected": false,
"text": "public abstract class Item\n{\n public int ID { get; set; }\n protected abstract void Save();\n\n public class ItemCollection : List<Item>\n {\n public void Save()\n {\n foreach (Item item in this) item.Save();\n }\n }\n}\n public sealed class NiceItem : Item\n{\n protected override void Save()\n {\n // do something\n }\n}\n Save() ItemCollection Item"
},
{
"answer_id": 367946,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": false,
"text": "internal interface InternalIAM\n{\n void Save();\n}\n\npublic class concreteIAM : InternalIAM\n{\n void InternalIAM.Save()\n {\n }\n}\n"
},
{
"answer_id": 368482,
"author": "Andrew Hare",
"author_id": 34211,
"author_profile": "https://Stackoverflow.com/users/34211",
"pm_score": 3,
"selected": false,
"text": "using System;\n\npublic interface IPublic\n{\n void Public();\n}\n\ninternal interface IInternal : IPublic\n{\n void Internal();\n}\n\npublic class Concrete : IInternal\n{\n public void Internal() { }\n\n public void Public() { }\n}\n"
},
{
"answer_id": 8823563,
"author": "Tomer W",
"author_id": 648368,
"author_profile": "https://Stackoverflow.com/users/648368",
"pm_score": -1,
"selected": false,
"text": " public interface IAM\n {\n int ID { get; set; }\n }\n\n public class concreteIAM : IAM\n {\n public int ID{get;set;}\n internal void Save(){\n //save the object\n }\n\n //other staff for this particular class\n }\n\n public class MyList : List<IAM>\n {\n public void Save()\n {\n foreach (concreteIAM iam in this)\n {\n iam.Save();\n }\n }\n //other staff for this particular class\n }\n"
},
{
"answer_id": 11145493,
"author": "Reuven Bass",
"author_id": 675116,
"author_profile": "https://Stackoverflow.com/users/675116",
"pm_score": 2,
"selected": false,
"text": "public class Internal\n{\n internal Internal() { }\n}\n\npublic interface IAM\n{\n int ID { get; set; }\n void Save(Internal access);\n}\n Save() Internal"
},
{
"answer_id": 52934653,
"author": "Rishi Prasad",
"author_id": 10541937,
"author_profile": "https://Stackoverflow.com/users/10541937",
"pm_score": 0,
"selected": false,
"text": "using System.Collections.Generic;\n\npublic abstract class IAM\n{\n int ID { get; set; }\n internal abstract void Save();\n}\n\npublic class concreteIAM : IAM\n{\n public int ID { get; set; }\n internal override void Save()\n {\n //save the object\n }\n\n //other staff for this particular class\n}\n\npublic class MyList : List<IAM>\n{\n internal void Save()\n {\n foreach (IAM iam in this)\n {\n iam.Save();\n }\n }\n\n //other staff for this particular class\n}\n"
},
{
"answer_id": 68167560,
"author": "Jordi",
"author_id": 4313030,
"author_profile": "https://Stackoverflow.com/users/4313030",
"pm_score": 0,
"selected": false,
"text": "public interface IAM\n{\n int ID { get; set; }\n internal void Save();\n}\n\npublic class concreteIAM : IAM\n{\n public int ID { get; set; }\n void IAMSavable.Save() {\n //save the object\n }\n}\n Save() concreteIAM IAM Save() internal"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,461 | <p>I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table.</p>
<p>The following example should illustrate my problem:</p>
<pre><code>class Answer(models.Model):
ovramt = models.ForeignKey("Ovramt")
question = models.ForeignKey("Question")
answer = models.CharField(max_length=3, choices=(("yes","yes"),("no","no") ("NA","N/A"))
likelihood = models.IntegerField(choices=LIKELY_CHOICES)
consequence = models.IntegerField(choices=CONSEQUENCE_CHOICES)
class Meta:
abstract = True
class Answer_A(Answer):
resident = models.ForeignKey("Resident")
def __unicode__(self):
return u"%s - %s - %s" %(self.ovramt.ssa.name, self.resident, self.question)
class Answer_B(Answer):
def __unicode__(self):
return u"%s - %s" %(self.ovramt.ssa.name, self.question)
class Answer_Risk(models.Model):
answer = models.ForeignKey("Answer")
risk = models.CharField(max_length=200)
def __unicode__(self):
return self.risk
</code></pre>
<p>Answer_A and Answer_B are slightly different in that Answer_A also needs a FK relationship to another table. Answer_B may also require some specific attributes later. The problem would STILL exist if I had Answer_B be the superclass - and have Answer_A subclass or compose it.</p>
<p>A 'Risk' is the same whether it's Answer_A or Answer_B. I also have other models that need to reference an 'Answer' regardless of it's sub-type. How can this be done? How can you reference a type regardless of it's sub-type?</p>
<p>Update:<br>
I was trying to avoid a join operation but I don't think I'm going to be able to. Would it be worth having the reference to 'Resident' in all 'Answer's and just nulling it where required? Or is that considered very bad practice? </p>
| [
{
"answer_id": 367765,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 5,
"selected": true,
"text": "Answer Answer_Risk resident Answer_A resident == None Answer"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
] |
367,467 | <p>Timezone information for Java are kept in a folder called "zi". For eg.
C:\Program Files\Java\jdk6\jre\lib\zi</p>
<p>files in this folder are in binary format. But it is very important for me to see exactly what they say.</p>
<p>Can anyone share a way, to read these files, or are they Sun proprietary?</p>
| [
{
"answer_id": 367765,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 5,
"selected": true,
"text": "Answer Answer_Risk resident Answer_A resident == None Answer"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,471 | <p>In the clocks application, the timer screen shows a picker (probably a <code>UIPicker</code> in <code>UIDatePickerModeCountDownTimer</code> mode) with some text in the selection bar ("hours" and "mins" in this case).</p>
<p>(edit) Note that these labels are <strong>fixed</strong>: They don't move when the picker wheel is rolling.</p>
<p>Is there a way to show such fixed labels in the selection bar of a standard <code>UIPickerView</code> component?</p>
<p>I did not find any API that would help with that. A suggestion was to add a <code>UILabel</code> as a subview of the picker, but that didn't work.</p>
<hr>
<p><strong>Answer</strong></p>
<p>I followed Ed Marty's advice (answer below), and it works! Not perfect but it should fool people. For reference, here's my implementation, feel free to make it better...</p>
<pre><code>- (void)viewDidLoad {
// Add pickerView
self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
[pickerView release];
CGSize pickerSize = [pickerView sizeThatFits:CGSizeZero];
CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
#define toolbarHeight 40.0
CGFloat pickerTop = screenRect.size.height - toolbarHeight - pickerSize.height;
CGRect pickerRect = CGRectMake(0.0, pickerTop, pickerSize.width, pickerSize.height);
pickerView.frame = pickerRect;
// Add label on top of pickerView
CGFloat top = pickerTop + 2;
CGFloat height = pickerSize.height - 2;
[self addPickerLabel:@"x" rightX:123.0 top:top height:height];
[self addPickerLabel:@"y" rightX:183.0 top:top height:height];
//...
}
- (void)addPickerLabel:(NSString *)labelString rightX:(CGFloat)rightX top:(CGFloat)top height:(CGFloat)height {
#define PICKER_LABEL_FONT_SIZE 18
#define PICKER_LABEL_ALPHA 0.7
UIFont *font = [UIFont boldSystemFontOfSize:PICKER_LABEL_FONT_SIZE];
CGFloat x = rightX - [labelString sizeWithFont:font].width;
// White label 1 pixel below, to simulate embossing.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, top + 1, rightX, height)];
label.text = labelString;
label.font = font;
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.opaque = NO;
label.alpha = PICKER_LABEL_ALPHA;
[self.view addSubview:label];
[label release];
// Actual label.
label = [[UILabel alloc] initWithFrame:CGRectMake(x, top, rightX, height)];
label.text = labelString;
label.font = font;
label.backgroundColor = [UIColor clearColor];
label.opaque = NO;
label.alpha = PICKER_LABEL_ALPHA;
[self.view addSubview:label];
[label release];
}
</code></pre>
| [
{
"answer_id": 367763,
"author": "keremk",
"author_id": 29475,
"author_profile": "https://Stackoverflow.com/users/29475",
"pm_score": 2,
"selected": false,
"text": "UIPickerViewDelegate - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component CustomPickerView UIPickerView - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated - (UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component"
},
{
"answer_id": 548104,
"author": "mikechambers",
"author_id": 10232,
"author_profile": "https://Stackoverflow.com/users/10232",
"pm_score": 0,
"selected": false,
"text": " CGFloat pickerTop = timePicker.bounds.origin.y;\nCGSize pickerSize = timePicker.bounds.size;\n"
},
{
"answer_id": 616517,
"author": "dizy",
"author_id": 74421,
"author_profile": "https://Stackoverflow.com/users/74421",
"pm_score": 5,
"selected": true,
"text": "\nUILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(135, 93, 80, 30)] autorelease];\nlabel.text = @\"Label\";\nlabel.font = [UIFont boldSystemFontOfSize:20];\nlabel.backgroundColor = [UIColor clearColor];\nlabel.shadowColor = [UIColor whiteColor];\nlabel.shadowOffset = CGSizeMake (0,1);\n[picker insertSubview:label aboveSubview:[picker.subviews objectAtIndex:5]]; \n//When you have multiple components (sections)...\n//you will need to find which subview you need to actually get under\n//so experiment with that 'objectAtIndex:5'\n//\n//you can do something like the following to find the view to get on top of\n// define @class UIPickerTable;\n// NSMutableArray *tables = [[NSMutableArray alloc] init];\n// for (id i in picker.subviews) if([i isKindOfClass:[UIPickerTable class]]) [tables addObject:i];\n// etc...\n\n"
},
{
"answer_id": 6169669,
"author": "Andrey Tarantsov",
"author_id": 58146,
"author_profile": "https://Stackoverflow.com/users/58146",
"pm_score": 4,
"selected": false,
"text": "UIPickerView UIDatePicker // UIPickerView_SelectionBarLabelSupport.h\n//\n// This file adds a new API to UIPickerView that allows to easily recreate\n// the look and feel of UIDatePicker labeled components.\n//\n// Copyright (c) 2009, Andrey Tarantsov <andreyvit@gmail.com>\n//\n// Permission to use, copy, modify, and/or distribute this software for any\n// purpose with or without fee is hereby granted, provided that the above\n// copyright notice and this permission notice appear in all copies.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\n#import <Foundation/Foundation.h>\n\n\n// useful constants for your font size-related code\n#define kPickerViewDefaultTitleFontSize 20.0f\n#define kDatePickerTitleFontSize 25.0f\n#define kDatePickerLabelFontSize 21.0f\n\n\n@interface UIPickerView (SelectionBarLabelSupport)\n\n// The primary API to add a label to the given component.\n// If you want to match the look of UIDatePicker, use 21pt as pointSize and 25pt as the font size of your content views (titlePointSize).\n// (Note that UIPickerView defaults to 20pt items, so you need to use custom views. See a helper method below.)\n// Repeated calls will change the label with an animation effect similar to UIDatePicker's one.\n//\n// To call this method on viewDidLoad, please call [pickerView layoutSubviews] first so that all subviews\n// get created.\n- (void)addLabel:(NSString *)label ofSize:(CGFloat)pointSize toComponent:(NSInteger)component leftAlignedAt:(CGFloat)offset baselineAlignedWithFontOfSize:(CGFloat)titlePointSize;\n\n// A helper method for your delegate's \"pickerView:viewForRow:forComponent:reusingView:\".\n// Creates a propertly positioned right-aligned label of the given size, and also handles reuse.\n// The actual UILabel is a child of the returned view, use [returnedView viewWithTag:1] to retrieve the label.\n- (UIView *)viewForShadedLabelWithText:(NSString *)label ofSize:(CGFloat)pointSize forComponent:(NSInteger)component rightAlignedAt:(CGFloat)offset reusingView:(UIView *)view;\n\n// Creates a shaded label of the given size, looking similar to the labels used by UIPickerView/UIDatePicker.\n- (UILabel *)shadedLabelWithText:(NSString *)label ofSize:(CGFloat)pointSize;\n\n@end\n // UIPickerView_SelectionBarLabelSupport.m\n//\n// This file adds a new API to UIPickerView that allows to easily recreate\n// the look and feel of UIDatePicker labeled components.\n//\n// Copyright (c) 2009, Andrey Tarantsov <andreyvit@gmail.com>\n//\n// Permission to use, copy, modify, and/or distribute this software for any\n// purpose with or without fee is hereby granted, provided that the above\n// copyright notice and this permission notice appear in all copies.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n#import \"UIPickerView_SelectionBarLabelSupport.h\"\n\n\n// used to find existing component labels among UIPicker's children\n#define kMagicTag 89464534\n// a private UIKit implementation detail, but we do degrade gracefully in case it stops working\n#define kSelectionBarClassName @\"_UIPickerViewSelectionBar\"\n\n// used to sort per-component selection bars in a left-to-right order\nstatic NSInteger compareViews(UIView *a, UIView *b, void *context) {\n CGFloat ax = a.frame.origin.x, bx = b.frame.origin.x;\n if (ax < bx)\n return -1;\n else if (ax > bx)\n return 1;\n else\n return 0;\n}\n\n\n@implementation UIPickerView (SelectionBarLabelSupport)\n\n- (UILabel *)shadedLabelWithText:(NSString *)label ofSize:(CGFloat)pointSize {\n UIFont *font = [UIFont boldSystemFontOfSize:pointSize];\n CGSize size = [label sizeWithFont:font];\n UILabel *labelView = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)] autorelease];\n labelView.font = font;\n labelView.adjustsFontSizeToFitWidth = NO;\n labelView.shadowOffset = CGSizeMake(1, 1);\n labelView.textColor = [UIColor blackColor];\n labelView.shadowColor = [UIColor whiteColor];\n labelView.opaque = NO;\n labelView.backgroundColor = [UIColor clearColor];\n labelView.text = label;\n labelView.userInteractionEnabled = NO;\n return labelView;\n}\n\n- (UIView *)viewForShadedLabelWithText:(NSString *)title ofSize:(CGFloat)pointSize forComponent:(NSInteger)component rightAlignedAt:(CGFloat)offset reusingView:(UIView *)view {\n UILabel *label;\n UIView *wrapper;\n if (view != nil) {\n wrapper = view;\n label = (UILabel *)[wrapper viewWithTag:1];\n } else {\n CGFloat width = [self.delegate pickerView:self widthForComponent:component];\n\n label = [self shadedLabelWithText:title ofSize:pointSize];\n CGSize size = label.frame.size;\n label.frame = CGRectMake(0, 0, offset, size.height);\n label.tag = 1;\n label.textAlignment = UITextAlignmentRight;\n label.autoresizingMask = UIViewAutoresizingFlexibleHeight;\n\n wrapper = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, width, size.height)] autorelease];\n wrapper.autoresizesSubviews = NO;\n wrapper.userInteractionEnabled = NO;\n [wrapper addSubview:label];\n }\n label.text = title;\n return wrapper;\n}\n\n- (void)addLabel:(NSString *)label ofSize:(CGFloat)pointSize toComponent:(NSInteger)component leftAlignedAt:(CGFloat)offset baselineAlignedWithFontOfSize:(CGFloat)titlePointSize {\n NSParameterAssert(component < [self numberOfComponents]);\n\n NSInteger tag = kMagicTag + component;\n UILabel *oldLabel = (UILabel *) [self viewWithTag:tag];\n if (oldLabel != nil && [oldLabel.text isEqualToString:label])\n return;\n\n NSInteger n = [self numberOfComponents];\n CGFloat total = 0.0;\n for (int c = 0; c < component; c++)\n offset += [self.delegate pickerView:self widthForComponent:c];\n for (int c = 0; c < n; c++)\n total += [self.delegate pickerView:self widthForComponent:c];\n offset += (self.bounds.size.width - total) / 2;\n\n offset += 2 * component; // internal UIPicker metrics, measured on a screenshot\n offset += 4; // add a gap\n\n CGFloat baselineHeight = [@\"X\" sizeWithFont:[UIFont boldSystemFontOfSize:titlePointSize]].height;\n CGFloat labelHeight = [@\"X\" sizeWithFont:[UIFont boldSystemFontOfSize:pointSize]].height;\n\n UILabel *labelView = [self shadedLabelWithText:label ofSize:pointSize];\n labelView.frame = CGRectMake(offset,\n (self.bounds.size.height - baselineHeight) / 2 + (baselineHeight - labelHeight) - 1,\n labelView.frame.size.width,\n labelView.frame.size.height);\n labelView.tag = tag;\n\n UIView *selectionBarView = nil;\n NSMutableArray *selectionBars = [NSMutableArray array];\n for (UIView *subview in self.subviews) {\n if ([[[subview class] description] isEqualToString:kSelectionBarClassName])\n [selectionBars addObject:subview];\n }\n if ([selectionBars count] == n) {\n [selectionBars sortUsingFunction:compareViews context:NULL];\n selectionBarView = [selectionBars objectAtIndex:component];\n }\n if (oldLabel != nil) {\n [UIView beginAnimations:nil context:oldLabel];\n [UIView setAnimationDuration:0.25];\n [UIView setAnimationDelegate:self];\n [UIView setAnimationDidStopSelector:@selector(YS_barLabelHideAnimationDidStop:finished:context:)];\n oldLabel.alpha = 0.0f;\n [UIView commitAnimations];\n }\n // if the selection bar hack stops working, degrade to using 60% alpha\n CGFloat normalAlpha = (selectionBarView == nil ? 0.6f : 1.0f);\n if (selectionBarView != nil)\n [self insertSubview:labelView aboveSubview:selectionBarView];\n else\n [self addSubview:labelView];\n if (oldLabel != nil) {\n labelView.alpha = 0.0f;\n [UIView beginAnimations:nil context:oldLabel];\n [UIView setAnimationDuration:0.25];\n [UIView setAnimationDelay:0.25];\n labelView.alpha = normalAlpha;\n [UIView commitAnimations];\n } else {\n labelView.alpha = normalAlpha;\n }\n}\n\n- (void)YS_barLabelHideAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(UIView *)oldLabel {\n [oldLabel removeFromSuperview];\n}\n\n@end\n - (void)updateFloorLabel {\n NSInteger floor = [self.pickerView numberOfRowsInComponent:0] - [self.pickerView selectedRowInComponent:0];\n NSString *suffix = @\"th\";\n if (((floor % 100) / 10) != 1) {\n switch (floor % 10) {\n case 1: suffix = @\"st\"; break;\n case 2: suffix = @\"nd\"; break;\n case 3: suffix = @\"rd\"; break;\n }\n }\n [self.pickerView addLabel:[NSString stringWithFormat:@\"%@ Floor\", suffix]\n ofSize:21\n toComponent:0\n leftAlignedAt:50\nbaselineAlignedWithFontOfSize:25]; \n}\n\n- (void)viewDidLoad {\n ...\n [self.pickerView layoutSubviews];\n [self updateFloorLabel];\n ...\n}\n\n- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {\n NSString *s = [NSString stringWithFormat:@\"%d\", [pickerView numberOfRowsInComponent:0] - row];\n return [pickerView viewForShadedLabelWithText:s ofSize:25 forComponent:0 rightAlignedAt:46 reusingView:view];\n}\n\n- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {\n [self updateFloorLabel];\n}\n"
},
{
"answer_id": 19843863,
"author": "Jon",
"author_id": 463059,
"author_profile": "https://Stackoverflow.com/users/463059",
"pm_score": 2,
"selected": false,
"text": "- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component"
},
{
"answer_id": 23048584,
"author": "Kun Hu",
"author_id": 2014948,
"author_profile": "https://Stackoverflow.com/users/2014948",
"pm_score": 3,
"selected": false,
"text": "- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component\n{\n if (component == 0) {\n return self.distanceItems[row];\n }\n else {\n return @\"km\";\n }\n}\n\n-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{\n return 2;\n}\n\n-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{\n if (component == 0) {\n return [self.distanceItems count];\n }\n else {\n // when it comes to the second column, only one row.\n return 1;\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42690/"
] |
367,494 | <p>I'm attempting to map a set of key presses to a set of commands. Because I process the commands from several places, I'd like to set up a layer of abstraction between the keys and the commands so that if I change the underlying key mappings, I don't have to change very much code. My current attempt looks like this:</p>
<pre><code>// input.h
enum LOGICAL_KEYS {
DO_SOMETHING_KEY,
DO_SOMETHING_ELSE_KEY,
...
countof_LOGICAL_KEYS
};
static const SDLKey LogicalMappings[countof_LOGICAL_KEYS] = {
SDLK_RETURN, // Do Something
SDLK_ESCAPE, // Do Something Else
...
};
// some_other_file.cpp
...
switch( event.key.keysym.key ) {
case LogicalMappings[ DO_SOMETHING_KEY ]:
doSomething();
break;
case LogicalMappings[ DO_SOMETHING_ELSE_KEY ]:
doSomethingElse();
break;
...
}
</code></pre>
<p>When I try to compile this (gcc 4.3.2) I get the error message:</p>
<blockquote>
<p>error: 'LogicalMappings' cannot appear in a constant-expression</p>
</blockquote>
<p>I don't see why the compiler has a problem with this. I understand why you're not allowed to have variables in a case statement, but I was under the impression that you could use constants, as they could be evaluated at compile-time. Do constant arrays not work with switch statements? If so, I suppose I could just replace the array with something like:</p>
<pre><code>static const SDLKey LOGICAL_MAPPING_DO_SOMETHING = SDLK_RETURN;
static const SDLKey LOGICAL_MAPPING_DO_SOMETHING_ELSE = SDLK_ESCAPE;
...
</code></pre>
<p>But that seems much less elegant. Does anybody know why you can't use a constant array here?</p>
<p>EDIT: I've seen the bit of the C++ standard that claims that, "An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5)...". I still don't see why a constant array doesn't count as an "enumeration type initialized with a constant expression." It could just be that the answer to my question is "because that's the way that it is," and I'll have to work around it. But if that's the case, it's sort of disappointing, because the compiler really <i>could</i> determine those values at compile-time.</p>
| [
{
"answer_id": 367525,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "case switch switch"
},
{
"answer_id": 368541,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 0,
"selected": false,
"text": "class Event // you probably have this defined already\n{\n}\n\nclass EventHandler // abstract base class\n{\npublic:\n virtual void operator()(Event& e) = 0;\n};\n\nclass EventHandler1\n{\n virtual void operator()(Event& e){\n // do something here \n }\n};\nclass EventHandler2\n{\n virtual void operator()(Event& e){\n // do something here \n }\n};\n\nEventHandler1 ev1;\nEventHandler2 ev2;\nEventHandler *LogicalMappings[countof_LOGICAL_KEYS] = {\n &ev1,\n &ev2,\n // more here...\n\n};\n\n// time to use code:\nEvent event;\nif (event.key.keysym.key < countof_LOGICAL_KEYS)\n{\n EventHandler *p = LogicalMappings[event.key.keysym.key];\n if (p != NULL)\n (*p)(event);\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19491/"
] |
367,518 | <p>This should be straight forward for a guru. I don't have any code really written out, just a couple of controllers and a custom UIView. All connected through nibs. The app loads without crashing, yet I can't see my NSLog() hit from my custom UIView.</p>
<p>My application delegate has default template code which calls for a class of mine called TabAnimationController. TabAnimationViewController has its view set to TabView. I made sure that in TabAnimationViewController's NIB that File's owner is set to TabAnimationViewController and that my instance of UIView has its class set to TabView.</p>
<p>In TabView.m I'm trying to see how NSLog is going to hit, and it's not showing up at all.</p>
<pre><code>- (void)loadView {
NSLog(@"calling loadView");
}
- (id)initWithFrame:(CGRect)frame {
NSLog(@"Calling initWithFrame:");
return self;
}
</code></pre>
<p>Strange. I'm not sure why even after proper IB connections that my NSLog will not show up. Only anything put into drawRect: will invoke. Why isn't initWithFrame or loadView ever get hit? What if I want to customize this view programmatically?</p>
| [
{
"answer_id": 367668,
"author": "keremk",
"author_id": 29475,
"author_profile": "https://Stackoverflow.com/users/29475",
"pm_score": 4,
"selected": true,
"text": "initWithFrame initWithCoder initWithCoder initWithFrame init if (self = [super initXXX]) { do your initialization } \nreturn self;\n loadView UIViewController UIView view loadView viewDidLoad"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
367,523 | <p>I would like to ensure that I only subscribe once in a particular class for an event on an instance.</p>
<p>For example I would like to be able to do the following:</p>
<pre><code>if (*not already subscribed*)
{
member.Event += new MemeberClass.Delegate(handler);
}
</code></pre>
<p>How would I go about implementing such a guard?</p>
| [
{
"answer_id": 367541,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 2,
"selected": false,
"text": "class MemberClass\n{\n private EventHandler _event;\n\n public event EventHandler Event\n {\n add\n {\n if( /* handler not already added */ )\n {\n _event+= value;\n }\n }\n remove\n {\n _event-= value;\n }\n }\n}\n"
},
{
"answer_id": 367542,
"author": "Hamish Smith",
"author_id": 15572,
"author_profile": "https://Stackoverflow.com/users/15572",
"pm_score": 6,
"selected": true,
"text": "private bool _eventHasSubscribers = false;\nprivate EventHandler<MyDelegateType> _myEvent;\n\npublic event EventHandler<MyDelegateType> MyEvent\n{\n add \n {\n if (_myEvent == null)\n {\n _myEvent += value;\n }\n }\n remove\n {\n _myEvent -= value;\n }\n}\n if (alreadySubscribedFlag)\n{\n member.Event += new MemeberClass.Delegate(handler);\n}\n"
},
{
"answer_id": 7065833,
"author": "alf",
"author_id": 512507,
"author_profile": "https://Stackoverflow.com/users/512507",
"pm_score": 6,
"selected": false,
"text": "myClass.MyEvent -= MyHandler;\nmyClass.MyEvent += MyHandler;\n"
},
{
"answer_id": 10250169,
"author": "Saghar",
"author_id": 309941,
"author_profile": "https://Stackoverflow.com/users/309941",
"pm_score": 3,
"selected": false,
"text": "[Serializable]\npublic class PreventEventHookedTwiceAttribute: EventInterceptionAspect\n{\n private readonly object _lockObject = new object();\n readonly List<Delegate> _delegates = new List<Delegate>();\n\n public override void OnAddHandler(EventInterceptionArgs args)\n {\n lock(_lockObject)\n {\n if(!_delegates.Contains(args.Handler))\n {\n _delegates.Add(args.Handler);\n args.ProceedAddHandler();\n }\n }\n }\n\n public override void OnRemoveHandler(EventInterceptionArgs args)\n {\n lock(_lockObject)\n {\n if(_delegates.Contains(args.Handler))\n {\n _delegates.Remove(args.Handler);\n args.ProceedRemoveHandler();\n }\n }\n }\n}\n [PreventEventHookedTwice]\npublic static event Action<string> GoodEvent;\n"
},
{
"answer_id": 60373122,
"author": "Tony Steel",
"author_id": 5757094,
"author_profile": "https://Stackoverflow.com/users/5757094",
"pm_score": 1,
"selected": false,
"text": "private bool subscribed;\n\nif(!subscribed)\n{\n myClass.MyEvent += MyHandler;\n subscribed = true;\n} \n\nprivate void MyHandler()\n{\n // Do stuff\n myClass.MyEvent -= MyHandler;\n subscribed = false;\n}\n"
},
{
"answer_id": 63179902,
"author": "computercarguy",
"author_id": 1836461,
"author_profile": "https://Stackoverflow.com/users/1836461",
"pm_score": 2,
"selected": false,
"text": "private EventHandler<bar> foo;\npublic event EventHandler<bar> Foo\n{\n add\n {\n if (foo == null || \n !foo.GetInvocationList().Select(il => il.Method).Contains(value.Method))\n {\n foo += value;\n }\n }\n\n remove\n {\n if (foo != null)\n {\n EventHandler<bar> eventMethod = (EventHandler<bar>)foo .GetInvocationList().FirstOrDefault(il => il.Method == value.Method);\n\n if (eventMethod != null)\n {\n foo -= eventMethod;\n }\n }\n }\n}\n foo.Invoke(...) Foo.Invoke(...) System.Linq"
},
{
"answer_id": 68213642,
"author": "Кое Кто",
"author_id": 5197544,
"author_profile": "https://Stackoverflow.com/users/5197544",
"pm_score": -1,
"selected": false,
"text": "GetInvocationList using System.Linq;\n....\npublic event HandlerType SomeEvent;\n....\n//Raising code\nforeach (HandlerType d in (SomeEvent?.GetInvocationList().Distinct() ?? Enumerable.Empty<Delegate>()).ToArray())\n d.Invoke(sender, arg);\n class CA \n{\n public CA()\n { }\n public void Inc()\n => count++;\n public int count;\n}\n[TestMethod]\npublic void TestDistinctDelegates()\n{\n var a = new CA();\n Action d0 = () => a.Inc();\n var d = d0;\n d += () => a.Inc();\n d += d0;\n d.Invoke();\n Assert.AreEqual(3, a.count);\n var l = d.GetInvocationList();\n Assert.AreEqual(3, l.Length);\n var distinct = l.Distinct().ToArray();\n Assert.AreEqual(2, distinct.Length);\n foreach (Action di in distinct)\n di.Invoke();\n Assert.AreEqual(3 + distinct.Length, a.count);\n}\n[TestMethod]\npublic void TestDistinctDelegates2()\n{\n var a = new CA();\n Action d = a.Inc;\n d += a.Inc;\n d.Invoke();\n Assert.AreEqual(2, a.count);\n var distinct = d.GetInvocationList().Distinct().ToArray();\n Assert.AreEqual(1, distinct.Length);\n foreach (Action di in distinct)\n di.Invoke();\n Assert.AreEqual(3, a.count);\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40444/"
] |
367,545 | <p>Is there an equivalent of <a href="http://www.php.net/manual/en/function.get-defined-functions.php" rel="noreferrer"><code>get_defined_functions()</code></a> which only shows the functions of a given object?</p>
<p>Example usage and output:</p>
<pre><code>class A {
function foo() { }
function bar() { }
}
class B extends A {
function foobar() { }
}
$b = new B();
print_r(get_object_functions($b));
// Array (
// 0 => "foo",
// 1 => "bar",
// 2 => "foobar"
//)
</code></pre>
| [
{
"answer_id": 367546,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": false,
"text": "get_class_methods()"
},
{
"answer_id": 367548,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 2,
"selected": false,
"text": "ReflectionClass"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| [
{
"answer_id": 367568,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 2,
"selected": false,
"text": "def factorial(num):\n \"\"\"Computes the factorial of num.\"\"\"\n try:\n num = int(num)\n except ValueError, e:\n print e\n else:\n ...\n"
},
{
"answer_id": 367699,
"author": "saffsd",
"author_id": 37984,
"author_profile": "https://Stackoverflow.com/users/37984",
"pm_score": 2,
"selected": false,
"text": "def publicly_accessible_function(arg1, validate=False):\n if validate:\n do_validation(arg1)\n do_work\n"
},
{
"answer_id": 368054,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "assert def factorial(num):\n assert int(num)\n assert num > 0\n def factorial(num):\n assert type(num) in ( int, long )\n assert num > 0\n Error except somelibrary.Error,e: assert all( type(i) in (int,long) for i in someList ) \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
367,565 | <p>How can I build a numpy array out of a generator object?</p>
<p>Let me illustrate the problem:</p>
<pre><code>>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>In this instance, <code>gimme()</code> is the generator whose output I'd like to turn into an array. However, the array constructor does not iterate over the generator, it simply stores the generator itself. The behaviour I desire is that from <code>numpy.array(list(gimme()))</code>, but I don't want to pay the memory overhead of having the intermediate list and the final array in memory at the same time. Is there a more space-efficient way?</p>
| [
{
"answer_id": 367599,
"author": "shsmurfy",
"author_id": 2188962,
"author_profile": "https://Stackoverflow.com/users/2188962",
"pm_score": 8,
"selected": true,
"text": "my_array = numpy.empty(predict_length())\nfor i, el in enumerate(gimme()): my_array[i] = el\n my_array = numpy.array(list(gimme()))\n length = sum(1 for el in gimme())\nmy_array = numpy.empty(length)\nfor i, el in enumerate(gimme()): my_array[i] = el\n"
},
{
"answer_id": 580416,
"author": "dhill",
"author_id": 69769,
"author_profile": "https://Stackoverflow.com/users/69769",
"pm_score": 8,
"selected": false,
"text": "numpy.fromiter(data, dtype, count) count=-1 dtype numpy.fromiter(something.generate(from_this_input), float)"
},
{
"answer_id": 854732,
"author": "Benjamin Horstman",
"author_id": 105703,
"author_profile": "https://Stackoverflow.com/users/105703",
"pm_score": 3,
"selected": false,
"text": "numpy.where"
},
{
"answer_id": 45980483,
"author": "mdeff",
"author_id": 3734066,
"author_profile": "https://Stackoverflow.com/users/3734066",
"pm_score": 5,
"selected": false,
"text": "numpy.fromiter() numpy.stack >>> mygen = (np.ones((5, 3)) for _ in range(10))\n>>> x = numpy.stack(mygen)\n>>> x.shape\n(10, 5, 3)\n >>> numpy.stack(2*i for i in range(10))\narray([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])\n numpy.stack arrays = [asanyarray(arr) for arr in arrays]"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37984/"
] |
367,571 | <p>I have written a simple <a href="http://en.wikipedia.org/wiki/Brainfuck" rel="noreferrer">brainfuck</a> interpreter in MATLAB script language. It is fed random bf programs to execute (as part of a genetic algorithm project). The problem I face is, the program turns out to have an infinite loop in a sizeable number of cases, and hence the GA gets stuck at the point.<br>
So, I need a mechanism to detect infinite loops and avoid executing that code in bf.<br>
One obvious (trivial) case is when I have</p>
<pre><code>[]
</code></pre>
<p>I can detect this and refuse to run that program.<br>
For the non-trivial cases, I figured out that the basic idea is: to determine how one iteration of the loop changes the current cell. If the change is negative, we're eventually going to reach 0, so it's a finite loop. Otherwise, if the change is non-negative, it's an infinite loop.<br>
Implementing this is easy for the case of a single loop, but with nested loops it becomes very complicated. For example, (in what follows (1) refers to contents of cell 1, etc. )</p>
<pre><code>++++ Put 4 in 1st cell (1)
>+++ Put 3 in (2)
<[ While( (1) is non zero)
-- Decrease (1) by 2
>[ While( (2) is non zero)
- Decrement (2)
<+ Increment (1)
>]
(2) would be 0 at this point
+++ Increase (2) by 3 making (2) = 3
<] (1) was decreased by 2 and then increased by 3, so net effect is increment
</code></pre>
<p>and hence the code runs on and on. A naive check of the number of +'s and -'s done on cell 1, however, would say the number of -'s is more, so would not detect the infinite loop.<br>
Can anyone think of a good algorithm to detect infinite loops, given arbitrary nesting of arbitrary number of loops in bf?</p>
<p>EDIT: I do know that the halting problem is unsolvable in general, but I was not sure whether there did not exist special case exceptions. Like, maybe Matlab might function as a Super Turing machine able to determine the halting of the bf program. I might be horribly wrong, but if so, I would like to know exactly how and why. </p>
<p>SECOND EDIT: I have written what I purport to be infinite loop detector. It probably misses some edge cases (or less probably, somehow escapes Mr. Turing's clutches), but seems to work for me as of now.
In pseudocode form, here it goes:</p>
<pre><code>subroutine bfexec(bfprogram)
begin
Looping through the bfprogram,
If(current character is '[')
Find the corresponding ']'
Store the code between the two brackets in, say, 'subprog'
Save the value of the current cell in oldval
Call bfexec recursively with subprog
Save the value of the current cell in newval
If(newval >= oldval)
Raise an 'infinite loop' error and exit
EndIf
/* Do other character's processings */
EndIf
EndLoop
end
</code></pre>
| [
{
"answer_id": 367758,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "< > + -"
},
{
"answer_id": 19773000,
"author": "Robert",
"author_id": 2953412,
"author_profile": "https://Stackoverflow.com/users/2953412",
"pm_score": 2,
"selected": false,
"text": "+[->[>]+<[-<]+]\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8127/"
] |
367,577 | <p>When you have code like the following: </p>
<pre><code>static T GenericConstruct<T>() where T : new()
{
return new T();
}
</code></pre>
<p>The C# compiler insists on emitting a call to Activator.CreateInstance, which is considerably slower than a native constructor. </p>
<p>I have the following workaround:</p>
<pre><code>public static class ParameterlessConstructor<T>
where T : new()
{
public static T Create()
{
return _func();
}
private static Func<T> CreateFunc()
{
return Expression.Lambda<Func<T>>( Expression.New( typeof( T ) ) ).Compile();
}
private static Func<T> _func = CreateFunc();
}
// Example:
// Foo foo = ParameterlessConstructor<Foo>.Create();
</code></pre>
<p>But it doesn't make sense to me why this workaround should be necessary.</p>
| [
{
"answer_id": 367643,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "List<string> List<Stream> new T()"
},
{
"answer_id": 367648,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "static void Create<T>()\n where T : struct\n{\n var x = new T();\n Console.WriteLine(x.ToString());\n}\n"
},
{
"answer_id": 367665,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "static T Create<T>() where T : new()\n{\n Expression<Func<T>> e = () => new T();\n return e.Compile()();\n}\n"
},
{
"answer_id": 1280832,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public class Foo<T> where T : new()\n{\n static Expression<Func<T>> x = () => new T();\n static Func<T> f = x.Compile();\n\n public static T build()\n {\n return f();\n }\n}\n new T() public static Func<T> BuildFn { get { return f; } }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46267/"
] |
367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| [
{
"answer_id": 367594,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 4,
"selected": false,
"text": "from random import choice\nimport string\n\ndef GenPasswd2(length=8, chars=string.letters + string.digits):\n return ''.join([choice(chars) for i in range(length)])\n\n>>> GenPasswd2(8,string.digits) + GenPasswd2(15,string.ascii_letters)\n'28605495YHlCJfMKpRPGyAw'\n>>> \n"
},
{
"answer_id": 367596,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 7,
"selected": true,
"text": "#!/usr/bin/python\n\nimport random\nimport string\n\ndigits = \"\".join( [random.choice(string.digits) for i in xrange(8)] )\nchars = \"\".join( [random.choice(string.letters) for i in xrange(15)] )\nprint digits + chars\n chars = \"\".join( [random.choice(string.letters[:26]) for i in xrange(15)] )\n"
},
{
"answer_id": 14195441,
"author": "Devi",
"author_id": 526365,
"author_profile": "https://Stackoverflow.com/users/526365",
"pm_score": 4,
"selected": false,
"text": "random.sample random.sample random.sample(string.letters, 53) ValueError import random, string\n\ndigits = ''.join(random.sample(string.digits, 8))\nchars = ''.join(random.sample(string.letters, 15))\n"
},
{
"answer_id": 30010270,
"author": "jithin",
"author_id": 1447634,
"author_profile": "https://Stackoverflow.com/users/1447634",
"pm_score": 1,
"selected": false,
"text": "import random\nimport string\n\ndigits = \"\".join( [random.choice(string.digits+string.letters) for i in xrange(10)] )\nprint digits\n"
},
{
"answer_id": 63537425,
"author": "Riya John",
"author_id": 10547264,
"author_profile": "https://Stackoverflow.com/users/10547264",
"pm_score": 2,
"selected": false,
"text": "random.choices import random\nimport string\nx = ''.join(random.choices(string.ascii_letters + string.digits, k=16))\nprint(x)\n string.punctuation"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27474/"
] |
367,617 | <p>In another <a href="https://stackoverflow.com/questions/89193/does-linq-to-sql-support-composable-queries">posting: Does Linq-To-Sql support composable queries</a> there was discussion on how to compose/concat where clauses dynamically. This appears to be done with an "AND" (i.e. the first where clause and the second where clause are joined by an AND). What I am wondering is if there is a way to compose Linq queries with an OR.</p>
<p>Example:</p>
<pre><code>var people = from p in Person
where p.age < 18
select p
var otherPeople = from p in people
where p.firstName equals "Daniel"
select p
</code></pre>
<p>This gives people with a first name of "Daniel" and that are under 18. I'm looking for the syntax to join these to find people who have a first name of "Daniel" or are under 18.</p>
<p>Note: I am using ADO.net Data Services so I do not have .Contains() available to me.</p>
<p><strong>EDIT</strong>: The Union Suggestion (by Garry Shutler) is exactly what I am looking for functionality-wise. I did run into two possible issues with it:</p>
<ol>
<li>It looks like it would make multiple database hits if I was to do a third condition (union seems to take an IEnumerable as its parameter) - I was hoping to build up multiple AND and OR statements in code and then execute one request.</li>
<li>Union is not supported by ADO.Net Data Services (very disappointing)</li>
</ol>
| [
{
"answer_id": 367912,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 4,
"selected": true,
"text": "var people = from p in Person\n where p.age < 18 || p.firstName == \"Daniel\"\n select p;\n var under18 = from p in Person\n where p.age < 18\n select p;\n\nvar daniels = from p in Person\n where p.firstName == \"Daniel\"\n select p;\n\nvar combined = under18.Union(daniels);\n"
},
{
"answer_id": 368059,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 2,
"selected": false,
"text": "var predicate = PredicateBuilder.False<Person>();\npredicate = predicate.Or(p => p.age < 18);\npredicate = predicate.Or(p => p.firstName == \"Daniel\");\n\nvar query = Person.Where(predicate);\n"
},
{
"answer_id": 1669816,
"author": "Phani Raj",
"author_id": 197671,
"author_profile": "https://Stackoverflow.com/users/197671",
"pm_score": 1,
"selected": false,
"text": "//The set in which we have to search for a match\nList<string> citiesIWillVisit = new List<string>() {\"London\",\"Berlin\",\"Prague\"};\nvar customersAround = nwContext.Customers\n .IsIn<Customers>(citiesIWillVisit, c=> c.City);\n foreach (Customers localCustomer in customersAround) {\n System.Console.WriteLine(localCustomer.ContactName);\n }"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25719/"
] |
367,623 | <p>We are invoking Asp.Net ajax web service from the client side. So the JavaScript functions have calls like:</p>
<p>// The function to alter the server side state object and set the selected node for the case tree.</p>
<pre><code>function JSMethod(caseId, url)
{
Sample.XYZ.Method(param1, param2, OnMethodReturn);
}
function OnMethodReturn(result)
{
var sessionExpiry = CheckForSessionExpiry(result);
var error = CheckForErrors(result);
... process result
}
</code></pre>
<p>And on the server side in the ".asmx.cs" file:
namespace Sample</p>
<pre><code>[ScriptService]
class XYZ : WebService
{
[WebMethod(EnableSession = true)]
public string Method(string param1, string param2)
{
if (SessionExpired())
{
return sessionExpiredMessage;
}
.
.
.
}
}
</code></pre>
<p>The website is setup to use form based authentication. Now if the session has expired and then the JavaScript function "JSMethod" is invoked,
then the following error is obtained:
Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'Method' failed with the following error: System.InvalidOperationException-- Authentication failed.</p>
<p>This exception is raised by method "function Sys$Net$WebServiceProxy$invoke" in file "ScriptResource.axd":</p>
<pre><code>function Sys$Net$WebServiceProxy$invoke
{
.
.
.
{
// In debug mode, if no error was registered, display some trace information
var error;
if (result && errorObj) {
// If we got a result, we're likely dealing with an error in the method itself
error = result.get_exceptionType() + "-- " + result.get_message();
}
else {
// Otherwise, it's probably a 'top-level' error, in which case we dump the
// whole response in the trace
error = response.get_responseData();
}
// DevDiv 89485: throw, not alert()
throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error));
}
</code></pre>
<p>So the problem is that the exception is raised even before "Method" is invoked, the exception occurs during the creation of the Web Proxy. Any ideas on how to resolve this problem</p>
| [
{
"answer_id": 376909,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 0,
"selected": false,
"text": "try { } catch { }"
},
{
"answer_id": 3421097,
"author": "Bharat Patil",
"author_id": 412663,
"author_profile": "https://Stackoverflow.com/users/412663",
"pm_score": -1,
"selected": false,
"text": "[WebMethod(EnableSession = true)]\npublic static string Method(string param1, string param2)\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46279/"
] |
367,626 | <p>In the Java snippet:</p>
<pre><code>SyndFeedInput fr = new SyndFeedInput();
SyndFeed sf = fr.build(new XmlReader(myInputStream));
List<SyndEntry> entries = sf.getEntries();
</code></pre>
<p>the last line generates the warning </p>
<p>"The expression of type <code>List</code> needs unchecked conversion to conform to <code>List<SyndEntry></code>"</p>
<p>What's an appropriate way to fix this? </p>
| [
{
"answer_id": 367632,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 3,
"selected": false,
"text": "SyndFeed sf.getEntries List<SyndEntry> List List<SyndEntry> SyndFeed @SuppressWarning(\"unchecked\")"
},
{
"answer_id": 367634,
"author": "Shyam Kumar Sundarakumar",
"author_id": 35392,
"author_profile": "https://Stackoverflow.com/users/35392",
"pm_score": 1,
"selected": false,
"text": "SyndFeed com.sun.syndication.feed.synd.SyndFeed java.util.List<SyndEntry> java.util.List"
},
{
"answer_id": 367649,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "SyndFeed @SuppressWarnings(\"unchecked\")\nList<SyndEntry> entries = (List<SyndEntry>) sf.getEntries();\n @SuppressWarnings(\"unchecked\")\nList<SyndEntry> entries = Collections.checkedList(sf.getEntries(), SyndEntry.class);\n"
},
{
"answer_id": 367673,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 8,
"selected": true,
"text": "getEntries List List<SyndEntry> sf.getEntries() SyndEntry Collections.checkedList ClassCastException"
},
{
"answer_id": 2848268,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 7,
"selected": false,
"text": "public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {\n List<T> r = new ArrayList<T>(c.size());\n for(Object o: c)\n r.add(clazz.cast(o));\n return r;\n}\n List<SyndEntry> entries = castList(SyndEntry.class, sf.getEntries());\n SuppressWarnings"
},
{
"answer_id": 6019365,
"author": "DennisTemper",
"author_id": 639802,
"author_profile": "https://Stackoverflow.com/users/639802",
"pm_score": 0,
"selected": false,
"text": "return new ArrayList<?>(getResultOfHibernateCallback(...))"
},
{
"answer_id": 27538166,
"author": "Joseph K. Strauss",
"author_id": 4354956,
"author_profile": "https://Stackoverflow.com/users/4354956",
"pm_score": 2,
"selected": false,
"text": "for(SyndEntry entry: Iterables.filter(sf.getEntries(), SyndEntry.class){\n ...\n}\n List<SyndEntry> list = Lists.newArrayList(\n Iterables.filter(sf.getEntries(), SyndEntry.class));\n List<SyndEntry> list = ImmutableList.copyOf(\n Iterables.filter(sf.getEntries(), SyndEntry.class));\n"
},
{
"answer_id": 30118243,
"author": "Honglonglong",
"author_id": 4877730,
"author_profile": "https://Stackoverflow.com/users/4877730",
"pm_score": 1,
"selected": false,
"text": "SyndFeedInput fr = new SyndFeedInput();\nSyndFeed sf = fr.build(new XmlReader(myInputStream));\nList<?> entries = sf.getEntries();\n"
},
{
"answer_id": 70116396,
"author": "Mathias Zajaczkowski",
"author_id": 9792963,
"author_profile": "https://Stackoverflow.com/users/9792963",
"pm_score": 0,
"selected": false,
"text": "public static <T> HashSet<T> castHashSet(Class<? extends T> clazz, Collection<?> c) {\n int cSize = (c == null) ? 0 : c.size();\n HashSet<T> hashSet = new HashSet<T>(cSize);\n if (c != null) {\n for (Object o : c)\n hashSet.add(clazz.cast(o));\n }\n return hashSet;\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46277/"
] |
367,633 | <p>What are all the common undefined behaviours that a C++ programmer should know about?</p>
<p>Say, like:</p>
<pre><code>a[i] = i++;
</code></pre>
<p></p>
| [
{
"answer_id": 367650,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": false,
"text": "char"
},
{
"answer_id": 367662,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 9,
"selected": true,
"text": "NULL memcpy int64_t i = 1; i <<= 72 int i; i++; cout << i; volatile sig_atomic_t long int #if"
},
{
"answer_id": 367663,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 5,
"selected": false,
"text": "// The simple obvious one.\ncallFunc(getA(),getB());\n int a = getA();\nint b = getB();\ncallFunc(a,b);\n int b = getB();\nint a = getA();\ncallFunc(a,b);\n"
},
{
"answer_id": 367671,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "int i =1;\ni = ++i;\n\n// Undefined. Assignment to 'i' twice in the same expression.\n"
},
{
"answer_id": 367690,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 5,
"selected": false,
"text": "a[i] = i++;\n\n// This expression has three parts:\n(a) a[i]\n(b) i++\n(c) Assign (b) to (a)\n\n// (c) is guaranteed to happen after (a) and (b)\n// But (a) and (b) can be done in either order.\n// See n2521 Section 5.17\n// (b) increments i but returns the original value.\n// See n2521 Section 5.2.6\n// Thus this expression can be written as:\n\nint rhs = i++;\nint lhs& = a[i];\nlhs = rhs;\n\n// or\nint lhs& = a[i];\nint rhs = i++;\nlhs = rhs;\n A* a = new A(\"plop\");\n\n// Looks simple enough.\n// But this can be split into three parts.\n(a) allocate Memory\n(b) Call constructor\n(c) Assign value to 'a'\n\n// No problem here:\n// The compiler is allowed to do this:\n(a) allocate Memory\n(c) Assign value to 'a'\n(b) Call constructor.\n// This is because the whole thing is between two sequence points.\n\n// So what is the big deal.\n// Simple Double checked lock. (I know there are many other problems with this).\nif (a == null) // (Point B)\n{\n Lock lock(mutex);\n if (a == null)\n {\n a = new A(\"Plop\"); // (Point A).\n }\n}\na->doStuff();\n\n// Think of this situation.\n// Thread 1: Reaches point A. Executes (a)(c)\n// Thread 1: Is about to do (b) and gets unscheduled.\n// Thread 2: Reaches point B. It can now skip the if block\n// Remember (c) has been done thus 'a' is not NULL.\n// But the memory has not been initialized.\n// Thread 2 now executes doStuff() on an uninitialized variable.\n\n// The solution to this problem is to move the assignment of 'a'\n// To the other side of the sequence point.\nif (a == null) // (Point B)\n{\n Lock lock(mutex);\n if (a == null)\n {\n A* tmp = new A(\"Plop\"); // (Point A).\n a = tmp;\n }\n}\na->doStuff();\n\n// Of course there are still other problems because of C++ support for\n// threads. But hopefully these are addresses in the next standard.\n"
},
{
"answer_id": 367693,
"author": "yesraaj",
"author_id": 22076,
"author_profile": "https://Stackoverflow.com/users/22076",
"pm_score": 3,
"selected": false,
"text": "const const_cast<> const int i = 10; \nint *p = const_cast<int*>( &i );\n*p = 1234; //Undefined\n"
},
{
"answer_id": 11211519,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 2,
"selected": false,
"text": "memcpy char a[256] = {};\nmemcpy(a, a, sizeof(a));\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
367,656 | <p>Currently I am working very basic game using the C++ environment. The game used to be a school project but now that I am done with that programming class, I wanted to expand my skills and put some more flourish on this old assignment.</p>
<p>I have already made a lot of changes that I am pleased with. I have centralized all the data into folder hierarchies and I have gotten the code to read those locations.</p>
<p>However my problem stems from a very fundamental flaw that has been stumping me. </p>
<p>In order to access the image data that I am using I have used the code:</p>
<pre><code>string imageLocation = "..\\DATA\\Images\\";
string bowImage = imageLocation + "bow.png";
</code></pre>
<p>The problem is that when the player picks up an item on the gameboard my code is supposed to use the code:</p>
<pre><code>hud.addLine("You picked up a " + (*itt)->name() + "!");
</code></pre>
<p>to print to the command line, "You picked up a Bow!". But instead it shows "You picked up a ..\DATA\Images\!". </p>
<p>Before I centralized my data I used to use:</p>
<pre><code>name_(item_name.substr(0, item_name.find('.')))
</code></pre>
<p>in my Item class constructor to chop the item name to just something like bow or candle. After I changed how my data was structured I realized that I would have to change how I chop the name down to the same simple 'bow' or 'candle'. </p>
<p>I have changed the above code to reflect my changes in data structure to be:</p>
<pre><code>name_(item_name.substr(item_name.find("..\\DATA\\Images\\"), item_name.find(".png")))
</code></pre>
<p>but unfortunately as I alluded to earlier this change of code is not working as well as I planned it to be.</p>
<p>So now that I have given that real long winded introduction to what my problem is, here is my question.</p>
<p>How do you extract the middle of a string between two sections that you do not want? Also that middle part that is your target is of an unknown length. </p>
<p>Thank you so very much for any help you guys can give. If you need anymore information please ask; I will be more than happy to upload part or even my entire code for more help. Again thank you very much.</p>
| [
{
"answer_id": 367732,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 2,
"selected": false,
"text": "string extn = item_name.substr(item_name.find_last_of(\".png\"));\nstring path = item_name.substr(0, item_name.find(\"..\\\\DATA\\\\Images\\\\\"));\nname_ = item_name.substr( path.size(), item_name.size() - extn.size() );\n find_last_of"
},
{
"answer_id": 367783,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "find_last_of std::size_type lastSlash = filePath.find_last_of('\\\\');\nif (lastSlash == std::string::npos)\n fileName = filePath;\nelse\n fileName = filePath.substr(lastSlash + 1);\n \\\\ \\\\ find_last_of std::size_type lastDot = fileName.find_last_of('.');\nif (lastDot == std::string::npos)\n{\n title = fileName;\n}\nelse\n{\n title = fileName.substr(0, lastDot);\n extension = fileName.substr(lastDot + 1);\n}\n"
},
{
"answer_id": 367952,
"author": "Raz",
"author_id": 5661,
"author_profile": "https://Stackoverflow.com/users/5661",
"pm_score": 2,
"selected": false,
"text": "#include \"boost/filesystem.hpp\"\n\nnamespace fs = boost::filesystem;\n\nvoid some_function(void)\n{\n string imageLocation = \"..\\\\DATA\\\\Images\\\\\";\n string bowImage = imageLocation + \"bow.png\";\n fs::path image_path( bowImage ); \n hud.addLine(\"You picked up a \" + image_path.filename() + \"!\"); //prints: You picked up a bow!\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36254/"
] |
367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal format for working with. Based on some reading I've come up with this: <a href="http://dpaste.com/99206/" rel="nofollow noreferrer">http://dpaste.com/99206/</a> , however it fails with an IndexError. How would I go about doing this?</p>
| [
{
"answer_id": 368224,
"author": "nikow",
"author_id": 11992,
"author_profile": "https://Stackoverflow.com/users/11992",
"pm_score": 1,
"selected": false,
"text": " buffer = gl.glReadPixels(0, 0, width, height, gl.GL_RGB, \n gl.GL_UNSIGNED_BYTE)\n image = Image.fromstring(mode=\"RGB\", size=(width, height), \n data=buffer)\n image = image.transpose(Image.FLIP_TOP_BOTTOM)\n"
},
{
"answer_id": 525483,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 2,
"selected": false,
"text": "a = (GLuint * 1)(0)\nglReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)\n @window.event\ndef on_mouse_press(x, y, button, modifiers):\n a = (GLuint * 1)(0)\n glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)\n print a[0]\n"
},
{
"answer_id": 4122290,
"author": "jpap",
"author_id": 500309,
"author_profile": "https://Stackoverflow.com/users/500309",
"pm_score": 2,
"selected": false,
"text": "glReadPixels(...) # Capture image from the OpenGL buffer\nbuffer = ( GLubyte * (3*window.width*window.height) )(0)\nglReadPixels(0, 0, window.width, window.height, GL_RGB, GL_UNSIGNED_BYTE, buffer)\n\n# Use PIL to convert raw RGB buffer and flip the right way up\nimage = Image.fromstring(mode=\"RGB\", size=(window.width, window.height), data=buffer) \nimage = image.transpose(Image.FLIP_TOP_BOTTOM)\n\n# Save image to disk\nimage.save('jpap.png')\n glReadPixels(...) pyglet.image.get_buffer_manager().get_color_buffer().save('jpap.png')\n save(...)"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37181/"
] |
367,695 | <p>I need to get substed drive letter in Perl. Could anyone kindly help me?
$ENV{SYSTEMDRIVE} does not work; it gives me real logical drive letter, not the substed one.</p>
| [
{
"answer_id": 367705,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 0,
"selected": false,
"text": "SUBST [drive1: [drive2:]path]\nSUBST drive1: /D\n drive1: Specifies a virtual drive to which you want to assign a path.\n [drive2:]path Specifies a physical drive and path you want to assign to\n a virtual drive.\n /D Deletes a substituted (virtual) drive.\nType SUBST with no parameters to display a list of current virtual drives.\n\nC:\\Documents and Settings\\Administrator\\My Documents>subst r: c:\\bin\n\nC:\\Documents and Settings\\Administrator\\My Documents>subst\n R:\\: => C:\\bin\n sub get_drive {\n my $drv = shift;\n my $ln;\n $drv = substr($drv,0,1);\n open (IN, \"subst |\");\n while ($ln = <IN>) {\n chomp ($ln);\n if ((substr($ln,0,1) eq $drv) && (substr($ln,1,6) eq \":\\\\: =>\")) {\n close (IN);\n return substr($ln,8);\n }\n }\n close (IN);\n return $drv . \":\\\\\";\n}\n\nprint get_drive (\"R:\") . \"\\n\";\nprint get_drive (\"S:\") . \"\\n\";\n C:\\bin\nS:\\\n"
},
{
"answer_id": 367879,
"author": "Dungeo",
"author_id": 46289,
"author_profile": "https://Stackoverflow.com/users/46289",
"pm_score": 3,
"selected": true,
"text": " perl -e 'use Cwd; print( substr(getcwd(),10,1 )) ' # prints 10th char.\n"
},
{
"answer_id": 57438242,
"author": "davidc",
"author_id": 3756914,
"author_profile": "https://Stackoverflow.com/users/3756914",
"pm_score": 0,
"selected": false,
"text": "use strict;\nuse Data::Dumper;\nuse feature 'say';\n\nmy $DB=1;\n\n$Data::Dumper::Indent = 1;\n$Data::Dumper::Terse = 1;\nmy %Virt;\n\nexit main();\n\nsub main\n{\n my $rtn;\n my (@args) = @_;\n open CMD,\"subst|\" or die \"can't run subst command\";\n while (<CMD>) {\n chomp;\n my ($drv, $path) = split(/:\\\\: => /);\n $Virt{$drv} = $path;\n }\n\n my %rset; # result set\n while (my ($d,$p) = each %Virt) {\n $rset{$d} = expand($p);\n }\n #D say Dumper rset => \\%rset;\n return $rtn;\n}\n\n# recursive call if expanded path has another 'virtual' drive\nsub expand\n{\n my ($loc) = @_;\n my $rtn = undef;\n my ($drv, $path) = split(/:\\\\/, $loc);\n if ($a = $Virt{$drv}) {\n #D say \"$a $path\";\n $rtn = \"$a\\\\$path\";\n $rtn = expand($rtn);\n } else {\n #D say \"$drv $path\";\n $rtn = \"$drv:\\\\$path\";\n }\n return $rtn;\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46289/"
] |
367,703 | <p>This obviously requires the source file to be under source control. I would ideally like a tool which works under the IDE (Eclipse, Visual Studio, etc) - but an external tool would be nice, too. Obviously, it is possible manually go through previous versions of the file, and compare the various versions, but I am looking for a way to be able to see quickly who is responsible for a code section.</p>
<p>I am using CVS, but the tool should ideally work with different source control systems.</p>
| [
{
"answer_id": 367710,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": "svn blame\n"
},
{
"answer_id": 368661,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "p4 annotate hg annotate"
},
{
"answer_id": 508972,
"author": "Scottie T",
"author_id": 6688,
"author_profile": "https://Stackoverflow.com/users/6688",
"pm_score": 1,
"selected": false,
"text": "annotate blame cvs annotate foo.cc > foo_changes.txt\n foo_changes.txt foo.cc"
},
{
"answer_id": 14075807,
"author": "Night Warrier",
"author_id": 491409,
"author_profile": "https://Stackoverflow.com/users/491409",
"pm_score": 0,
"selected": false,
"text": "p4 annotate my-file"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18651/"
] |
367,706 | <p>What is a good way of parsing command line arguments in Java?</p>
| [
{
"answer_id": 367714,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 10,
"selected": true,
"text": "commons-cli import org.apache.commons.cli.*;\n\npublic class Main {\n\n\n public static void main(String[] args) throws Exception {\n\n Options options = new Options();\n\n Option input = new Option(\"i\", \"input\", true, \"input file path\");\n input.setRequired(true);\n options.addOption(input);\n\n Option output = new Option(\"o\", \"output\", true, \"output file\");\n output.setRequired(true);\n options.addOption(output);\n\n CommandLineParser parser = new DefaultParser();\n HelpFormatter formatter = new HelpFormatter();\n CommandLine cmd = null;//not a good practice, it serves it purpose \n\n try {\n cmd = parser.parse(options, args);\n } catch (ParseException e) {\n System.out.println(e.getMessage());\n formatter.printHelp(\"utility-name\", options);\n\n System.exit(1);\n }\n\n String inputFilePath = cmd.getOptionValue(\"input\");\n String outputFilePath = cmd.getOptionValue(\"output\");\n\n System.out.println(inputFilePath);\n System.out.println(outputFilePath);\n\n }\n\n}\n $> java -jar target/my-utility.jar -i asd \nMissing required option: o\n\nusage: utility-name\n -i,--input <arg> input file path\n -o,--output <arg> output file\n"
},
{
"answer_id": 41022241,
"author": "Paul",
"author_id": 735217,
"author_profile": "https://Stackoverflow.com/users/735217",
"pm_score": 4,
"selected": false,
"text": "maven_jar(\n name = \"com_github_pcj_google_options\",\n artifact = \"com.github.pcj:google-options:jar:1.0.0\",\n sha1 = \"85d54fe6771e5ff0d54827b0a3315c3e12fdd0c7\",\n)\n dependencies {\n compile 'com.github.pcj:google-options:1.0.0'\n}\n <dependency>\n <groupId>com.github.pcj</groupId>\n <artifactId>google-options</artifactId>\n <version>1.0.0</version>\n</dependency>\n OptionsBase @Option package example;\n\nimport com.google.devtools.common.options.Option;\nimport com.google.devtools.common.options.OptionsBase;\n\nimport java.util.List;\n\n/**\n * Command-line options definition for example server.\n */\npublic class ServerOptions extends OptionsBase {\n\n @Option(\n name = \"help\",\n abbrev = 'h',\n help = \"Prints usage info.\",\n defaultValue = \"true\"\n )\n public boolean help;\n\n @Option(\n name = \"host\",\n abbrev = 'o',\n help = \"The server host.\",\n category = \"startup\",\n defaultValue = \"\"\n )\n public String host;\n\n @Option(\n name = \"port\",\n abbrev = 'p',\n help = \"The server port.\",\n category = \"startup\",\n defaultValue = \"8080\"\n )\n public int port;\n\n @Option(\n name = \"dir\",\n abbrev = 'd',\n help = \"Name of directory to serve static files.\",\n category = \"startup\",\n allowMultiple = true,\n defaultValue = \"\"\n )\n public List<String> dirs;\n\n}\n package example;\n\nimport com.google.devtools.common.options.OptionsParser;\nimport java.util.Collections;\n\npublic class Server {\n\n public static void main(String[] args) {\n OptionsParser parser = OptionsParser.newOptionsParser(ServerOptions.class);\n parser.parseAndExitUponError(args);\n ServerOptions options = parser.getOptions(ServerOptions.class);\n if (options.host.isEmpty() || options.port < 0 || options.dirs.isEmpty()) {\n printUsage(parser);\n return;\n }\n\n System.out.format(\"Starting server at %s:%d...\\n\", options.host, options.port);\n for (String dirname : options.dirs) {\n System.out.format(\"\\\\--> Serving static files at <%s>\\n\", dirname);\n }\n }\n\n private static void printUsage(OptionsParser parser) {\n System.out.println(\"Usage: java -jar server.jar OPTIONS\");\n System.out.println(parser.describeOptions(Collections.<String, String>emptyMap(),\n OptionsParser.HelpVerbosity.LONG));\n }\n\n}\n"
},
{
"answer_id": 43780433,
"author": "Remko Popma",
"author_id": 1446916,
"author_profile": "https://Stackoverflow.com/users/1446916",
"pm_score": 7,
"selected": false,
"text": "<command> -xvfInputFile <command> -x -v -f InputFile \"1..*\" \"3..5\""
},
{
"answer_id": 45898630,
"author": "Himanshu Shekhar",
"author_id": 6662856,
"author_profile": "https://Stackoverflow.com/users/6662856",
"pm_score": 2,
"selected": false,
"text": "public static void main(String[] args) {\n String usage = \"--day|-d day --mon|-m month [--year|-y year][--dir|-ds directoriesToSearch]\";\n ArgumentParser argParser = new ArgumentParser(usage, InputData.class);\n InputData inputData = (InputData) argParser.parse(args);\n showData(inputData);\n\n new StatsGenerator().generateStats(inputData);\n}\n"
},
{
"answer_id": 51421535,
"author": "Ioannis Koumarelas",
"author_id": 1725202,
"author_profile": "https://Stackoverflow.com/users/1725202",
"pm_score": 4,
"selected": false,
"text": "Map<String, String> argsMap = new HashMap<>();\nfor (String arg: args) {\n String[] parts = arg.split(\"=\");\n argsMap.put(parts[0], parts[1]);\n} \n"
},
{
"answer_id": 52024523,
"author": "stevens",
"author_id": 3550482,
"author_profile": "https://Stackoverflow.com/users/3550482",
"pm_score": 0,
"selected": false,
"text": "maven_jar(\n name = \"com_google_guava_guava\",\n artifact = \"com.google.guava:guava:19.0\",\n server = \"maven2_server\",\n)\n\nmaven_jar(\n name = \"com_github_pcj_google_options\",\n artifact = \"com.github.pcj:google-options:jar:1.0.0\",\n server = \"maven2_server\",\n)\n\nmaven_server(\n name = \"maven2_server\",\n url = \"http://central.maven.org/maven2/\",\n)\n bazel run path/to/your:project -- --var1 something --var2 something -v something\n bazel run path/to/your:project -- --help\n"
},
{
"answer_id": 57004094,
"author": "Stefan Haberl",
"author_id": 287138,
"author_profile": "https://Stackoverflow.com/users/287138",
"pm_score": 3,
"selected": false,
"text": "ApplicationRunner @SpringBootApplication\npublic class Application implements ApplicationRunner {\n\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n\n @Override\n public void run(ApplicationArguments args) {\n args.containsOption(\"my-flag-option\"); // test if --my-flag-option was set\n args.getOptionValues(\"my-option\"); // returns values of --my-option=value1 --my-option=value2 \n args.getOptionNames(); // returns a list of all available options\n // do something with your args\n }\n}\n run @SpringBootApplication\npublic class Application implements ApplicationRunner {\n\n public static void main(String[] args) {\n ApplicationArguments arguments = new DefaultApplicationArguments(args);\n // do whatever you like with your arguments\n // see above ...\n SpringApplication.run(Application.class, args);\n }\n\n}\n ApplicationArguments @Component\npublic class MyBean {\n\n @Autowired\n private ApplicationArguments arguments;\n\n // ...\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428/"
] |
367,709 | <p>I would like to execute the jQuery $(document).ready() in a drupal site. While i know that i can just stick it in the index page , this is really messy and a hack. </p>
<p>What i want to know is where is the correct location to put this, it would also need to be theme specific as i dont want all themes to use it.</p>
<p>Thanks in advance for the help. </p>
<hr>
<p>Sweet success , thanks both of you for the help , i just have one last amend to this question. Now that i have got this far , i need to execute the jQuery code to update the document , can i use the context to modify the document ? </p>
| [
{
"answer_id": 367729,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "$(document).ready() Drupal.behaviors misc/ directory drupal_add_js(array('mymodule' => $array_of_settings), 'setting'); \n Drupal.behaviors Drupal.behaviors.myModuleBehavior = function (context) \n{\n //do some fancy stuff\n};\n $(document).ready Drupal.attachBehaviors Drupal.behaviors Drupal.attachBehaviors Drupal.behaviors.myModuleBehavior(newcontext) newcontext"
},
{
"answer_id": 367775,
"author": "gregnostic",
"author_id": 41891,
"author_profile": "https://Stackoverflow.com/users/41891",
"pm_score": 3,
"selected": true,
"text": "$scripts $scripts theme_preprocess_page() drupal_add_js(drupal_get_path('theme', 'theme_name') .'/example.js', 'theme');\n$variables['scripts'] = drupal_get_js();\n drupal_get_path() example.js"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42069/"
] |
367,711 | <p>I'm wondering if there is a "best" choice for collation in MySQL for a general website where you aren't 100% sure of what will be entered? I understand that all the encodings should be the same, such as MySQL, Apache, the HTML and anything inside PHP.</p>
<p>In the past I have set PHP to output in "UTF-8", but which collation does this match in MySQL? I'm thinking it's one of the UTF-8 ones, but I have used <code>utf8_unicode_ci</code>, <code>utf8_general_ci</code>, and <code>utf8_bin</code> before.</p>
| [
{
"answer_id": 367721,
"author": "mepcotterell",
"author_id": 43312,
"author_profile": "https://Stackoverflow.com/users/43312",
"pm_score": 4,
"selected": false,
"text": "utf8_general_ci utf8_bin utf8_general_ci"
},
{
"answer_id": 367725,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 10,
"selected": true,
"text": "utf8_general_ci utf8_unicode_ci utf8_swedish_ci utf8_unicode_ci"
},
{
"answer_id": 367731,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 7,
"selected": false,
"text": "utf8_unicode_ci utf8_general_ci utf8_general_ci utf8_unicode_ci"
},
{
"answer_id": 367735,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": false,
"text": "utf8_general_ci utf8_general_ci utf8_unicode_ci utf8_general_ci"
},
{
"answer_id": 3031968,
"author": "Guus",
"author_id": 189203,
"author_profile": "https://Stackoverflow.com/users/189203",
"pm_score": 7,
"selected": false,
"text": "utf8_general_ci utf8_general_ci utf8-bin -- first, create a sandbox to play in\nCREATE DATABASE `sandbox`;\nuse `sandbox`;\n\n-- next, make sure that your client connection is of the same \n-- character/collate type as the one we're going to test next:\ncharset utf8 collate utf8_general_ci\n\n-- now, create the table and fill it with values\nCREATE TABLE `test` (`key` VARCHAR(16), `value` VARCHAR(16) )\n CHARACTER SET utf8 COLLATE utf8_general_ci;\n\nINSERT INTO `test` VALUES ('Key ONE', 'value'), ('Key TWO', 'valúe');\n\n-- (verify)\nSELECT * FROM `test`;\n\n-- now, expose the problem/bug:\nSELECT * FROM test WHERE `value` = 'value';\n\n--\n-- Note that we get BOTH keys here! MySQLs UTF8 collates that are \n-- case insensitive (ending with _ci) do not distinguish between \n-- both values!\n--\n-- collate 'utf8_bin' doesn't have this problem, as I'll show next:\n--\n\n-- first, reset the client connection charset/collate type\ncharset utf8 collate utf8_bin\n\n-- next, convert the values that we've previously inserted in the table\nALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;\n\n-- now, re-check for the bug\nSELECT * FROM test WHERE `value` = 'value';\n\n--\n-- Note that we get just one key now, as you'd expect.\n--\n-- This problem appears to be specific to utf8. Next, I'll try to \n-- do the same with the 'latin1' charset:\n--\n\n-- first, reset the client connection charset/collate type\ncharset latin1 collate latin1_general_ci\n\n-- next, convert the values that we've previously inserted\n-- in the table\nALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci;\n\n-- now, re-check for the bug\nSELECT * FROM test WHERE `value` = 'value';\n\n--\n-- Again, only one key is returned (expected). This shows \n-- that the problem with utf8/utf8_generic_ci isn't present \n-- in latin1/latin1_general_ci\n--\n-- To complete the example, I'll check with the binary collate\n-- of latin1 as well:\n\n-- first, reset the client connection charset/collate type\ncharset latin1 collate latin1_bin\n\n-- next, convert the values that we've previously inserted in the table\nALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_bin;\n\n-- now, re-check for the bug\nSELECT * FROM test WHERE `value` = 'value';\n\n--\n-- Again, only one key is returned (expected).\n--\n-- Finally, I'll re-introduce the problem in the exact same \n-- way (for any sceptics out there):\n\n-- first, reset the client connection charset/collate type\ncharset utf8 collate utf8_generic_ci\n\n-- next, convert the values that we've previously inserted in the table\nALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;\n\n-- now, re-check for the problem/bug\nSELECT * FROM test WHERE `value` = 'value';\n\n--\n-- Two keys.\n--\n\nDROP DATABASE sandbox;\n"
},
{
"answer_id": 25475756,
"author": "Jeremy Postlethwaite",
"author_id": 1955853,
"author_profile": "https://Stackoverflow.com/users/1955853",
"pm_score": 7,
"selected": false,
"text": "utf8mb4 utf8mb4_unicode_ci utf8 utf8 utf8mb4 utf8mb4 ROW_FORMAT=DYNAMIC Barracuda Antelope innodb_file_format_max innodb_file_format = barracuda Antelope Barracuda utf8mb4 SHOW VARIABLES;\n\ninnodb_large_prefix = OFF\ninnodb_file_format = Antelope\n [client]\ndefault-character-set= utf8mb4\n\n[mysqld]\nexplicit_defaults_for_timestamp = true\ninnodb_large_prefix = true\ninnodb_file_format = barracuda\ninnodb_file_format_max = barracuda\ninnodb_file_per_table = true\n\n# Character collation\ncharacter_set_server=utf8mb4\ncollation_server=utf8mb4_unicode_ci\n CREATE TABLE Contacts (\n id INT AUTO_INCREMENT NOT NULL,\n ownerId INT DEFAULT NULL,\n created timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n contact VARCHAR(640) NOT NULL,\n prefix VARCHAR(128) NOT NULL,\n first VARCHAR(128) NOT NULL,\n middle VARCHAR(128) NOT NULL,\n last VARCHAR(128) NOT NULL,\n suffix VARCHAR(128) NOT NULL,\n notes MEDIUMTEXT NOT NULL,\n INDEX IDX_CA367725E05EFD25 (ownerId),\n INDEX created (created),\n INDEX modified_idx (modified),\n INDEX contact_idx (contact),\n PRIMARY KEY(id)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB ROW_FORMAT=DYNAMIC;\n INDEX contact_idx (contact) ROW_FORMAT=DYNAMIC contact ROW_FORMAT=DYNAMIC INDEX contact_idx (contact(128)),\n VARCHAR(128) INSERT INSERT INTO `Contacts` (`id`, `ownerId`, `created`, `modified`, `contact`, `prefix`, `first`, `middle`, `last`, `suffix`, `notes`) VALUES\n(1, NULL, '0000-00-00 00:00:00', '2014-08-25 03:00:36', '1234567890', '12345678901234567890', '1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890', '12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678', '', ''),\n(2, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '', '', ''),\n(3, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '123', '', '');\n last mysql> SELECT BIT_LENGTH(`last`), CHAR_LENGTH(`last`) FROM `Contacts`;\n+--------------------+---------------------+\n| BIT_LENGTH(`last`) | CHAR_LENGTH(`last`) |\n+--------------------+---------------------+\n| 1024 | 128 | -- All characters are ASCII\n| 4096 | 128 | -- All characters are 4 bytes\n| 4024 | 128 | -- 3 characters are ASCII, 125 are 4 bytes\n+--------------------+---------------------+\n SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'\n \\PDO::MYSQL_ATTR_INIT_COMMAND"
},
{
"answer_id": 30994949,
"author": "tapos ghosh",
"author_id": 3840799,
"author_profile": "https://Stackoverflow.com/users/3840799",
"pm_score": 2,
"selected": false,
"text": "SET NAMES utf8;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
367,724 | <p>What is the standard way of incorporating helper/utility functions in Obj-C classes?</p>
<p>I.e. General purpose functions which are used throughout the application and called by more than 1 class.</p>
<p>Can an Obj-C method exist outside of a class, or does it need to be a C function for it to have this kind of behaviour?</p>
| [
{
"answer_id": 367773,
"author": "AnthonyLambert",
"author_id": 31762,
"author_profile": "https://Stackoverflow.com/users/31762",
"pm_score": 5,
"selected": false,
"text": "@interface HelperClass: superclassname {\n // instance variables - none if all methods are static.\n}\n\n+ (void) helperMethod: (int) parameter_varName;\n\n@end\n [HelperClass helperMethod: 10 ];\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26088/"
] |
367,726 | <p>How can two classes in separate projects communicate between one another?</p>
<p>If ClassA references ClassB I can access methods of ClassB in ClassA... How can I make use of Interfaces to access methods of ClassA in ClassB?</p>
<p>Indeed do the classes even need to be linked if I make use of Interfaces?</p>
<p>Can someone please provide me with an example?</p>
<p>Coding in C# 2.0.</p>
<hr>
<p>I do mean classes. If I have two projects which are not referenced, but I would like to access methods in the class of one from the other ... how can I achieve this with Interfaces.</p>
<p>It has been alluded to me that this is what I should use however I am having a hard time understanding how to implement an interface if the projects are not referenced.</p>
| [
{
"answer_id": 367746,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "System.Reflection.Assembly.LoadFile(\"MyProject.dll\").GetType(\"MyProject.TestClass\").GetMethod(\"TestMethod\").Invoke();\n"
},
{
"answer_id": 367757,
"author": "mtt",
"author_id": 45771,
"author_profile": "https://Stackoverflow.com/users/45771",
"pm_score": 0,
"selected": false,
"text": "class B\n{\n\n Public sub DoSomethingOnA(IA a )\n {\n a.DoSomething();\n }\n\n}\n\nInterface IA\n{\n void DoSomething();\n}\n\nClass A : IA\n{\n void DoSomething()\n {\n //\n }\n\n}\n"
},
{
"answer_id": 367832,
"author": "mtt",
"author_id": 45771,
"author_profile": "https://Stackoverflow.com/users/45771",
"pm_score": 0,
"selected": false,
"text": "Public Interface IA { void DoSomething(); }\n\nPublic Interface IB { void DoSomething(); }\n class A : LinkAssembly.IA {\n\nPublic sub DoSomethingOnB(IB b ) { b.DoSomething(); }\n\nPublic sub DoSomething(){// }\n\n}\n class B : LinkAssembly.IB {\n\nPublic sub DoSomethingOnA(IA a ) { a.DoSomething(); }\n\nPublic sub DoSomething(){// }\n\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,730 | <p>How can I change an attribute of an element in an XML file, using C#?</p>
| [
{
"answer_id": 367772,
"author": "alexmac",
"author_id": 23066,
"author_profile": "https://Stackoverflow.com/users/23066",
"pm_score": 6,
"selected": false,
"text": "using System.Xml.Linq;\n\nXDocument xmlFile = XDocument.Load(\"books.xml\"); \n\nvar query = from c in xmlFile.Elements(\"catalog\").Elements(\"book\") \n select c; \n\nforeach (XElement book in query) \n{\n book.Attribute(\"attr1\").Value = \"MyNewValue\";\n}\n\nxmlFile.Save(\"books.xml\");\n"
},
{
"answer_id": 367981,
"author": "El Padrino",
"author_id": 30339,
"author_profile": "https://Stackoverflow.com/users/30339",
"pm_score": 6,
"selected": false,
"text": "//Here is the variable with which you assign a new value to the attribute\nstring newValue = string.Empty;\nXmlDocument xmlDoc = new XmlDocument();\n\nxmlDoc.Load(xmlFile);\n\nXmlNode node = xmlDoc.SelectSingleNode(\"Root/Node/Element\");\nnode.Attributes[0].Value = newValue;\n\nxmlDoc.Save(xmlFile);\n\n//xmlFile is the path of your file to be modified\n"
},
{
"answer_id": 27801093,
"author": "Ahmad",
"author_id": 2651073,
"author_profile": "https://Stackoverflow.com/users/2651073",
"pm_score": 4,
"selected": false,
"text": "private void SetAttrSafe(XmlNode node,params XmlAttribute[] attrList)\n {\n foreach (var attr in attrList)\n {\n if (node.Attributes[attr.Name] != null)\n {\n node.Attributes[attr.Name].Value = attr.Value;\n }\n else\n {\n node.Attributes.Append(attr);\n }\n }\n }\n XmlAttribute attr = dom.CreateAttribute(\"name\");\n attr.Value = value;\n SetAttrSafe(node, attr);\n"
},
{
"answer_id": 50629912,
"author": "Edward Bagby",
"author_id": 4404399,
"author_profile": "https://Stackoverflow.com/users/4404399",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Xml.Linq;\n\nnamespace XML\n{\n public class Parser\n {\n\n private string _FilePath = string.Empty;\n\n private XDocument _XML_Doc = null;\n\n\n public Parser(string filePath)\n {\n _FilePath = filePath;\n _XML_Doc = XDocument.Load(_FilePath);\n }\n\n\n /// <summary>\n /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.\n /// </summary>\n /// <param name=\"attributeName\"></param>\n /// <param name=\"newValue\"></param>\n public void ReplaceAtrribute(string attributeName, string newValue)\n {\n ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);\n }\n\n /// <summary>\n /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).\n /// </summary>\n /// <param name=\"elementName\"></param>\n /// <param name=\"attributeName\"></param>\n /// <param name=\"newValue\"></param>\n public void ReplaceAtrribute(string elementName, string attributeName, string newValue)\n {\n ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);\n }\n\n\n /// <summary>\n /// Replaces values of all attributes of a given name (attributeName) and value (oldValue) \n /// with the specified new value (newValue) in elements with a given name (elementName).\n /// </summary>\n /// <param name=\"elementName\"></param>\n /// <param name=\"attributeName\"></param>\n /// <param name=\"oldValue\"></param>\n /// <param name=\"newValue\"></param>\n public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)\n {\n ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue); \n }\n\n\n /// <summary>\n /// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues), \n /// with the specified new value (newValue) in elements with a given name (elementName).\n /// If oldValues is empty then oldValues will be ignored.\n /// </summary>\n /// <param name=\"elementName\"></param>\n /// <param name=\"attributeName\"></param>\n /// <param name=\"oldValues\"></param>\n /// <param name=\"newValue\"></param>\n public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)\n {\n List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();\n\n foreach (XElement element in elements)\n {\n if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)\n {\n if (element.Attribute(attributeName) != null)\n {\n\n if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))\n { element.Attribute(attributeName).Value = newValue; }\n }\n }\n }\n\n }\n\n public void SaveChangesToFile()\n {\n _XML_Doc.Save(_FilePath);\n }\n\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,739 | <p>I have a Product Class which has a one to many relationship to a Price class.
So a product can have multiple prices.</p>
<p>I need to query the db to get me 10 products which have Price.amount < $2. In this case its to populate a UI with 10 items in a page.
so i writ the following code:</p>
<pre><code>ICriteria criteria = session.CreateCriteria(typeof(Product));
criteria.SetFirstResult(pageNumber);
criteria.SetMaxResults(numberOfItemInPage);
criteria = criteria.CreateCriteria("PriceCollection");
criteria.Add(Restrictions.Le("Amount", new Decimal(2)));
criteria.SetResultTransformer(CriteriaSpecification.DistinctRootEntity);
</code></pre>
<p>Instead of getting 10 Product on the list, I'm getting less than that (i.e. 5).
The reason being SetMaxResults(10) return me 10 Products but with duplicates. The duplicates are then removed by SetResultTransformer(DistinctRootEntity). </p>
<p>Can anyone tell me any way for me to get 10 unique Products without increasing SetMaxResults()? I need to use pagenumber as some sort of indexing.</p>
| [
{
"answer_id": 367951,
"author": "Bork Blatt",
"author_id": 5381,
"author_profile": "https://Stackoverflow.com/users/5381",
"pm_score": 0,
"selected": false,
"text": "MinimumPrice (numeric(18,2)\nMaximumPrice (numeric(18,2)\n SELECT TOP 10 * FROM Product\nWHERE MinimumPrice > 2.0\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,751 | <p>I want to create a dmg file for my Mac project. Can someone please tell me how to do this? This being my first Mac project, I do not have any idea how to proceed. I also want to give the user an option of running the app on start-up. How do I do this?</p>
<p>Thanks.</p>
<p>P.S. I also want to add a custom license agreement.</p>
| [
{
"answer_id": 367826,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 5,
"selected": false,
"text": "/Applications/Utilities/ Cmd + Shift + N background.png .background.png hdiutil hdiutil create -srcfolder mydirtodmg mydmg.dmg\n /Developers/Application/Utilities/"
},
{
"answer_id": 976397,
"author": "kent",
"author_id": 78568,
"author_profile": "https://Stackoverflow.com/users/78568",
"pm_score": 2,
"selected": false,
"text": "# be sure to check the man page for hdiutil\n# it is very powerful and has tons of options...\n\nhdiutil create -megabytes 54 -fs HFS+ -volname awesome_app_install myAwesomeApplication.dmg\nhdiutil mount myAwesomeApplication.dmg\ncp -r /build/Release/AwesomeApplication.app /Volumes/awesome_app_install/\n"
},
{
"answer_id": 13984321,
"author": "user2067021",
"author_id": 2067021,
"author_profile": "https://Stackoverflow.com/users/2067021",
"pm_score": 3,
"selected": false,
"text": "cd /Volumes/SLAs_for_UDIFs_1.0\nDeRez SLAResources > /tmp/sla.r\n data 'TEXT' (5000, \"English SLA\")"
},
{
"answer_id": 58933218,
"author": "AdriZ",
"author_id": 6415465,
"author_profile": "https://Stackoverflow.com/users/6415465",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n# Create .dmg file for macOS\n\n# Adapt these variables to your needs\nAPP_VERS=\"1.0\"\nDMG_NAME=\"MyApp_v${APP_VERS}_macos\"\nOUTPUT_DMG_DIR=\"path_to_output_dmg_file\"\nAPP_FILE=\"path_to_my_app/MyApp.app\"\nOTHER_FILES_TO_INCLUDE=\"path_to_other_files\"\n\n\n# The directory of the script\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n# The temp directory used, within $DIR\nWORK_DIR=`mktemp -d \"${DIR}/tmp\"`\n\n# Check if tmp dir was created\nif [[ ! \"${WORK_DIR}\" || ! -d \"${WORK_DIR}\" ]]; then\n echo \"Could not create temp dir\"\n exit 1\nfi\n\n# Function to deletes the temp directory\nfunction cleanup {\n rm -rf \"${WORK_DIR}\"\n #echo \"Deleted temp working directory ${WORK_DIR}\"\n}\n\n# Register the cleanup function to be called on the EXIT signal\ntrap cleanup EXIT\n\n# Copy application on temp dir\ncp -R \"${APP_FILE}\" \"${WORK_DIR}\"\n# Copy other files without hidden files\nrsync -a --exclude=\".*\" \"${OTHER_FILES_TO_INCLUDE}\" \"${WORK_DIR}\"\n\n# Create .dmg\nhdiutil create -volname \"${DMG_NAME}\" -srcfolder \"${WORK_DIR}\" -ov -format UDZO \"${OUTPUT_DMG_DIR}/${DMG_NAME}.dmg\"\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46297/"
] |
367,752 | <p>Trying to add an onclick handler to my tabs, and can't seem to get the DOM selection right. Can you guys help?</p>
<pre><code> <div id="tabstrip">
<ul>
<li id="a" class="selected"><a href="#">A</a></li>
<li id="b"><a href="#">B</a></li>
<li id="b"><a href="#">C</a></li>
</ul>
</div>
function initTabStrip()
{
var lis = document.getElementById('tabstrip').getElementsByTagName('li');
for (var i=0;i<items.length;i++)
{
var as = items[i].getElementsByTagName('a');
for (var j=0;j<as.length;j++)
{
as[j].onclick=function(){changeTab(items[i].id);return false}
}
}
}
</code></pre>
| [
{
"answer_id": 367777,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "as[j].onclick = function(items, i)\n{\n return function()\n {\n changeTab(items[i].id);\n return false;\n };\n}(items, i);\n"
},
{
"answer_id": 367793,
"author": "Guillaume",
"author_id": 23704,
"author_profile": "https://Stackoverflow.com/users/23704",
"pm_score": 0,
"selected": false,
"text": "var lis items"
},
{
"answer_id": 367887,
"author": "Cliff",
"author_id": 8372,
"author_profile": "https://Stackoverflow.com/users/8372",
"pm_score": 0,
"selected": false,
"text": "function initTabStrip()\n{\n var tabstrip = document.getElementById('tabstrip');\n var items = tabstrip.getElementsByTagName('li');\n for (var i=0;i<items.length;i++)\n {\n var as = items[i].getElementsByTagName('a');\n for (var j=0;j<as.length;j++)\n {\n as[j].onclick = function(items, i)\n {\n return function()\n {\n changeTab(items[i].id);\n return false;\n };\n }(items, i);\n }\n }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8372/"
] |
367,761 | <h2>Original title: How can I prevent loading a native dll from a .NET app?</h2>
<p><strong>Background:</strong></p>
<p>My C# application includes a plugin framework and generic plugin loader.</p>
<p>The plugin loader enumerates the application directory in order to identify plugin dlls (essentially it searches for *.dll at this time). </p>
<p>Within the same application directory is a native (Windows, non-.net) dll, which, indirectly, one of the plugin dlls depends upon.</p>
<p>The plugin loader blindly assumes that the native.dll is a .NET Assembly dll, simply because it only checks the file extension. When it attempts to load the native dll, an exception is thrown:</p>
<p>"Could not load file or assembly 'native.dll' or one of its dependencies. The module was expected to contain an assembly manifest."</p>
<p>I basically create a diagnostic report if plugin loading fails, so I'm trying to avoid having this log filled up with messages about not being able to load the native dll (which I don't even want to attempt).</p>
<p><strong>The question:</strong></p>
<p>Is there some .NET API call that I can use to determine whether a binary happens to be a .NET assembly so that I don't attempt to load the native dll at all?</p>
<p>Perhaps longer term I will move my plugins to a subdirectory, but for now, I just want a work around that doesn't involve hard-coding the "native.dll" name inside my plugin loader. </p>
<p>I guess I'm looking for some kind of static Assembly.IsManaged() API call that I've overlooked.... presumably no such API exists?</p>
| [
{
"answer_id": 367785,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 2,
"selected": false,
"text": "foreach (string aDll in dllCollection) \n{\n try \n {\n Assembly anAssembly = Assembly.LoadFrom(aDll);\n }\n catch (BadImageFormatException ex)\n {\n //Handle this here\n }\n catch (Exception ex)\n {\n //Other exceptions (i/o, security etc.)\n }\n}\n"
},
{
"answer_id": 367798,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 4,
"selected": false,
"text": "public static bool IsManagedAssembly(string fileName)\n{\n uint peHeader;\n uint peHeaderSignature;\n ushort machine;\n ushort sections;\n uint timestamp;\n uint pSymbolTable;\n uint noOfSymbol;\n ushort optionalHeaderSize;\n ushort characteristics;\n ushort dataDictionaryStart;\n uint[] dataDictionaryRVA = new uint[16];\n uint[] dataDictionarySize = new uint[16];\n\n Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);\n BinaryReader reader = new BinaryReader(fs);\n\n //PE Header starts @ 0x3C (60). Its a 4 byte header.\n fs.Position = 0x3C;\n peHeader = reader.ReadUInt32();\n\n //Moving to PE Header start location...\n fs.Position = peHeader;\n peHeaderSignature = reader.ReadUInt32();\n\n //We can also show all these value, but we will be \n //limiting to the CLI header test.\n machine = reader.ReadUInt16();\n sections = reader.ReadUInt16();\n timestamp = reader.ReadUInt32();\n pSymbolTable = reader.ReadUInt32();\n noOfSymbol = reader.ReadUInt32();\n optionalHeaderSize = reader.ReadUInt16();\n characteristics = reader.ReadUInt16();\n\n // Now we are at the end of the PE Header and from here, the PE Optional Headers starts... To go directly to the datadictionary, we'll increase the stream’s current position to with 96 (0x60). 96 because, 28 for Standard fields 68 for NT-specific fields From here DataDictionary starts...and its of total 128 bytes. DataDictionay has 16 directories in total, doing simple maths 128/16 = 8. So each directory is of 8 bytes. In this 8 bytes, 4 bytes is of RVA and 4 bytes of Size. btw, the 15th directory consist of CLR header! if its 0, its not a CLR file :)\n dataDictionaryStart = Convert.ToUInt16(Convert.ToUInt16(fs.Position) + 0x60);\n fs.Position = dataDictionaryStart;\n for (int i = 0; i < 15; i++)\n {\n dataDictionaryRVA[i] = reader.ReadUInt32();\n dataDictionarySize[i] = reader.ReadUInt32();\n }\n fs.Close();\n\n if (dataDictionaryRVA[14] == 0) return false;\n else return true;\n}\n"
},
{
"answer_id": 367820,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 3,
"selected": false,
"text": "System.Reflection.AssemblyName.GetAssemblyName BadImageFormatException"
},
{
"answer_id": 15608028,
"author": "Kirill Osenkov",
"author_id": 37899,
"author_profile": "https://Stackoverflow.com/users/37899",
"pm_score": 5,
"selected": false,
"text": "public static bool IsManagedAssembly(string fileName)\n{\n using (Stream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))\n using (BinaryReader binaryReader = new BinaryReader(fileStream))\n {\n if (fileStream.Length < 64)\n {\n return false;\n }\n\n //PE Header starts @ 0x3C (60). Its a 4 byte header.\n fileStream.Position = 0x3C;\n uint peHeaderPointer = binaryReader.ReadUInt32();\n if (peHeaderPointer == 0)\n {\n peHeaderPointer = 0x80;\n }\n\n // Ensure there is at least enough room for the following structures:\n // 24 byte PE Signature & Header\n // 28 byte Standard Fields (24 bytes for PE32+)\n // 68 byte NT Fields (88 bytes for PE32+)\n // >= 128 byte Data Dictionary Table\n if (peHeaderPointer > fileStream.Length - 256)\n {\n return false;\n }\n\n // Check the PE signature. Should equal 'PE\\0\\0'.\n fileStream.Position = peHeaderPointer;\n uint peHeaderSignature = binaryReader.ReadUInt32();\n if (peHeaderSignature != 0x00004550)\n {\n return false;\n }\n\n // skip over the PEHeader fields\n fileStream.Position += 20;\n\n const ushort PE32 = 0x10b;\n const ushort PE32Plus = 0x20b;\n\n // Read PE magic number from Standard Fields to determine format.\n var peFormat = binaryReader.ReadUInt16();\n if (peFormat != PE32 && peFormat != PE32Plus)\n {\n return false;\n }\n\n // Read the 15th Data Dictionary RVA field which contains the CLI header RVA.\n // When this is non-zero then the file contains CLI data otherwise not.\n ushort dataDictionaryStart = (ushort)(peHeaderPointer + (peFormat == PE32 ? 232 : 248));\n fileStream.Position = dataDictionaryStart;\n\n uint cliHeaderRva = binaryReader.ReadUInt32();\n if (cliHeaderRva == 0)\n {\n return false;\n }\n\n return true;\n }\n}\n // Read PE magic number from Standard Fields to determine format.\n var peFormat = binaryReader.ReadUInt16();\n if (peFormat != PE32 && peFormat != PE32Plus)\n {\n return false;\n }\n\n // Read the 15th Data Dictionary RVA field which contains the CLI header RVA.\n // When this is non-zero then the file contains CLI data otherwise not.\n ushort dataDictionaryStart = (ushort)(peHeaderPointer + (peFormat == PE32 ? 232 : 248));\n"
},
{
"answer_id": 32676694,
"author": "InteXX",
"author_id": 722393,
"author_profile": "https://Stackoverflow.com/users/722393",
"pm_score": 0,
"selected": false,
"text": "Boolean System.IO.FileInfo Public Module FileSystem\n <Extension>\n Public Function IsManagedAssembly(File As FileInfo) As Boolean\n Dim _\n uHeaderSignature,\n uHeaderPointer As UInteger\n\n Dim _\n uFormat,\n u64,\n u32 As UShort\n\n u64 = &H20B\n u32 = &H10B\n\n IsManagedAssembly = False\n\n If File.Exists AndAlso File.Length.IsAtLeast(64) Then\n Using oStream As New FileStream(File.FullName, FileMode.Open, FileAccess.Read)\n Using oReader As New BinaryReader(oStream)\n 'PE Header starts @ 0x3C (60). Its a 4 byte header.\n oStream.Position = &H3C\n uHeaderPointer = oReader.ReadUInt32\n\n If uHeaderPointer = 0 Then\n uHeaderPointer = &H80\n End If\n\n ' Ensure there is at least enough room for the following structures:\n ' 24 byte PE Signature & Header\n ' 28 byte Standard Fields (24 bytes for PE32+)\n ' 68 byte NT Fields (88 bytes for PE32+)\n ' >= 128 byte Data Dictionary Table\n If uHeaderPointer < oStream.Length - 257 Then\n ' Check the PE signature. Should equal 'PE\\0\\0'.\n oStream.Position = uHeaderPointer\n uHeaderSignature = oReader.ReadUInt32\n\n If uHeaderSignature = &H4550 Then\n ' skip over the PEHeader fields\n oStream.Position += 20\n\n ' Read PE magic number from Standard Fields to determine format.\n uFormat = oReader.ReadUInt16\n\n If uFormat = u32 OrElse uFormat = u64 Then\n ' Read the 15th Data Dictionary RVA field which contains the CLI header RVA.\n ' When this is non-zero then the file contains CLI data, otherwise not.\n Select Case uFormat\n Case u32 : oStream.Position = uHeaderPointer + &HE8\n Case u64 : oStream.Position = uHeaderPointer + &HF8\n End Select\n\n IsManagedAssembly = oReader.ReadUInt32 > 0\n End If\n End If\n End If\n End Using\n End Using\n End If\n End Function\nEnd Module\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46296/"
] |
367,768 | <p>Given a function:</p>
<pre><code>function x(arg) { return 30; }
</code></pre>
<p>You can call it two ways:</p>
<pre><code>result = x(4);
result = new x(4);
</code></pre>
<p>The first returns 30, the second returns an object.</p>
<p>How can you detect which way the function was called <strong>inside the function itself</strong>?</p>
<p>Whatever your solution is, it must work with the following invocation as well:</p>
<pre><code>var Z = new x();
Z.lolol = x;
Z.lolol();
</code></pre>
<p>All the solutions currently think the <code>Z.lolol()</code> is calling it as a constructor.</p>
| [
{
"answer_id": 367794,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 6,
"selected": false,
"text": "this.constructor function x(y)\n{\n if (this.constructor == x)\n alert('called with new');\n else\n alert('called as function');\n}\n new"
},
{
"answer_id": 367825,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 3,
"selected": false,
"text": "this this.constructor this this var a = {};\n\na.foo = function () \n{\n if(this==a) //'a' because the context of foo is the parent 'a'\n {\n //method call\n }\n else\n {\n //constructor call\n }\n}\n\nvar bar = function () \n{\n if(this==window) //and 'window' is the default context here\n {\n //method call\n }\n else\n {\n //constructor call\n }\n}\n\na.baz = function ()\n{\n if(this.constructor==a.baz); //or whatever chain you need to reference this method\n {\n //constructor call\n }\n else\n {\n //method call\n }\n}\n"
},
{
"answer_id": 386903,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 4,
"selected": false,
"text": "function x() {\n if ( (this instanceof arguments.callee) ) {\n alert(\"called as constructor\");\n } else {\n alert(\"called as function\");\n }\n}\n var Z = new x();\nZ.lolol = x;\nZ.lolol();\n function x() {\n if ( (this instanceof arguments.callee && !this.hasOwnProperty(\"__ClaudiusCornerCase\")) ) {\n this.__ClaudiusCornerCase=1;\n alert(\"called as constructor\");\n } else {\n alert(\"called as function\");\n }\n}\n undefined"
},
{
"answer_id": 1876760,
"author": "Eli Grey",
"author_id": 78436,
"author_profile": "https://Stackoverflow.com/users/78436",
"pm_score": -1,
"selected": false,
"text": "this instanceof arguments.callee arguments.callee this.constructor"
},
{
"answer_id": 1880726,
"author": "Tim Down",
"author_id": 96100,
"author_profile": "https://Stackoverflow.com/users/96100",
"pm_score": 8,
"selected": true,
"text": "new x() x x this x x this x x x this x x function x(y) {\n var isConstructor = false;\n if (this instanceof x // <- You could use arguments.callee instead of x here,\n // except in in EcmaScript 5 strict mode.\n && !this.__previouslyConstructedByX) {\n isConstructor = true;\n this.__previouslyConstructedByX = true;\n }\n alert(isConstructor);\n}\n x x"
},
{
"answer_id": 1881048,
"author": "Breton",
"author_id": 51101,
"author_profile": "https://Stackoverflow.com/users/51101",
"pm_score": 0,
"selected": false,
"text": "this this function Thing () {\n var that = Object.create(Thing.prototype);\n that.foo=\"bar\";\n that.bar=\"baz\";\n return that;\n}\n if(!Object.create) {\n Object.create = function(Function){\n // WebReflection Revision\n return function(Object){\n Function.prototype = Object;\n return new Function;\n }}(function(){});\n}\n"
},
{
"answer_id": 1896873,
"author": "Frunsi",
"author_id": 206247,
"author_profile": "https://Stackoverflow.com/users/206247",
"pm_score": 2,
"selected": false,
"text": "function x(y) {\n if( this.constructor == arguments.callee && !this._constructed ) {\n this._constructed = true;\n alert('called with new');\n } else {\n alert('called as function');\n }\n}\n x(4); // OK, function\nvar X = new x(4); // OK, new\n\nvar Z = new x(); // OK, new\nZ.lolol = x; \nZ.lolol(); // OK, function\n\nvar Y = x;\nY(); // OK, function\nvar y = new Y(); // OK, new\ny.lolol = Y;\ny.lolol(); // OK, function\n"
},
{
"answer_id": 3721342,
"author": "haijin",
"author_id": 359535,
"author_profile": "https://Stackoverflow.com/users/359535",
"pm_score": 2,
"selected": false,
"text": "function makecls() {\n\n return function(args) {\n\n if( this instanceof arguments.callee) {\n if ( typeof this.init == \"function\")\n this.init.apply(this, args.callee ? args : arguments)\n }else{\n return new arguments.callee(args);\n }\n };\n}\n\nvar User = makecls();\n\nUser.prototype.init = function(first, last){\n\n this.name = first + last;\n};\n\nvar user = User(\"John\", \"Resig\");\n\nuser.name\n"
},
{
"answer_id": 3722386,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "// Store instances in a variable to compare against the current this\n// Based on Tim Down's solution where instances are tracked\nvar Klass = (function () {\n // Store references to each instance in a \"class\"-level closure\n var instances = [];\n\n // The actual constructor function\n return function () {\n if (this instanceof Klass && instances.indexOf(this) === -1) {\n instances.push(this);\n console.log(\"constructor\");\n } else {\n console.log(\"not constructor\");\n }\n };\n}());\n\nvar instance = new Klass(); // \"constructor\"\ninstance.klass = Klass;\ninstance.klass(); // \"not constructor\"\n"
},
{
"answer_id": 9666084,
"author": "acelent",
"author_id": 800524,
"author_profile": "https://Stackoverflow.com/users/800524",
"pm_score": 2,
"selected": false,
"text": "this this this function MyClass () {\n if ( this === (function () { return this; })() ) {\n // called as a function\n }\n else {\n // called as a constructor\n }\n}\n call apply this function MyClass () {\n if ( this === (function () { return this; })() ) {\n // Maybe the caller forgot the \"new\" keyword\n return new MyClass();\n }\n else {\n // initialize\n }\n}\n [[Call]] [[Construct]] new"
},
{
"answer_id": 9709618,
"author": "Peter Aron Zentai",
"author_id": 1269946,
"author_profile": "https://Stackoverflow.com/users/1269946",
"pm_score": 3,
"selected": false,
"text": " function ClassA() {\n if (this instanceof arguments.callee) {\n console.log(\"called as a constructor\");\n } else {\n console.log(\"called as a function\");\n }\n }\n var instance = new ClassA;\n instance.classAFunction = ClassA;\n instance.classAFunction(); // <-- this will appear as constructor call\n\n ClassA.apply(instance); //<-- this too\n function createConstructor(typeFunction) {\n return typeFunction.bind({});\n }\n\n var ClassA = createConstructor(\n function ClassA() {\n if (this instanceof arguments.callee) {\n console.log(\"called as a function\");\n return;\n }\n console.log(\"called as a constructor\");\n });\n\n var instance = new ClassA();\n function createConstructor(typeFunction) {\n var result = typeFunction.bind({});\n result.apply = function (ths, args) {\n try {\n typeFunction.inApplyMode = true;\n typeFunction.apply(ths, args);\n } finally {\n delete typeFunction.inApplyMode;\n }\n };\n return result;\n }\n\n var ClassA = createConstructor(\n function ClassA() {\n if (this instanceof arguments.callee && !arguments.callee.inApplyMode) {\n console.log(\"called as a constructor\");\n } else {\n console.log(\"called as a function\");\n }\n });\n"
},
{
"answer_id": 12363251,
"author": "Richard JP Le Guen",
"author_id": 248129,
"author_profile": "https://Stackoverflow.com/users/248129",
"pm_score": 0,
"selected": false,
"text": "__previouslyConstructedByX x function x() {\n\n if(this instanceof x) {\n console.log(\"You invoked the new keyword!\");\n return that;\n }\n else {\n console.log(\"No new keyword\");\n return undefined;\n }\n\n}\n\nx();\nvar Z = new x(); \nZ.lolol = x; \nZ.lolol();\nnew Z.lolol();\n x x this instanceof x new instanceof 30 Number x function x() {\n\n if(this instanceof x) {\n console.log(\"You invoked the new keyword!\");\n var that = {};\n return new Number(30);\n }\n else {\n console.log(\"No new\");\n return 30;\n }\n\n}\n\nconsole.log(x());\nvar Z = new x();\nconsole.log(Z);\nZ.lolol = x;\nconsole.log(Z.lolol());\nconsole.log(new Z.lolol());\n"
},
{
"answer_id": 18543216,
"author": "Diogo Schneider",
"author_id": 1004178,
"author_profile": "https://Stackoverflow.com/users/1004178",
"pm_score": 0,
"selected": false,
"text": "function RGB(red, green, blue) {\n if (this) {\n throw new Error(\"RGB can't be instantiated\");\n }\n\n var result = \"#\";\n result += toHex(red);\n result += toHex(green);\n result += toHex(blue);\n\n function toHex(dec) {\n var result = dec.toString(16);\n\n if (result.length < 2) {\n result = \"0\" + result;\n }\n\n return result;\n }\n\n return result;\n}\n"
},
{
"answer_id": 20004640,
"author": "fedeghe",
"author_id": 1080670,
"author_profile": "https://Stackoverflow.com/users/1080670",
"pm_score": 1,
"selected": false,
"text": "function x(arg) {\n //console.debug('_' in this ? 'function' : 'constructor'); //WRONG!!!\n //\n // RIGHT(as accepted)\n console.debug((this instanceof x && !('_' in this)) ? 'function' : 'constructor');\n this._ = 1;\n return 30;\n}\nvar result1 = x(4), // function\n result2 = new x(4), // constructor\n Z = new x(); // constructor\nZ.lolol = x; \nZ.lolol(); // function\n"
},
{
"answer_id": 29724652,
"author": "ymz",
"author_id": 4062197,
"author_profile": "https://Stackoverflow.com/users/4062197",
"pm_score": 2,
"selected": false,
"text": "function Something()\n{\n this.constructed;\n\n if (Something.prototype.isPrototypeOf(this) && !this.constructed)\n {\n console.log(\"called as a c'tor\"); this.constructed = true;\n }\n else\n {\n console.log(\"called as a function\");\n }\n}\n\nSomething(); //\"called as a function\"\nnew Something(); //\"called as a c'tor\"\n"
},
{
"answer_id": 31060154,
"author": "Daniel Weiner",
"author_id": 2498122,
"author_profile": "https://Stackoverflow.com/users/2498122",
"pm_score": 7,
"selected": false,
"text": "new.target new.target new Reflect.construct new undefined function Foo() {\n if (new.target) {\n console.log('called with new');\n } else {\n console.log('not called with new');\n }\n}\n\nnew Foo(); // \"called with new\"\nFoo(); // \"not called with new\"\nFoo.call({}); // \"not called with new\"\n"
},
{
"answer_id": 31484057,
"author": "Joshua Wise",
"author_id": 3968575,
"author_profile": "https://Stackoverflow.com/users/3968575",
"pm_score": 0,
"selected": false,
"text": "function createConstructor(func) {\n return func.bind(Object.create(null));\n}\n\nvar myClass = createConstructor(function myClass() {\n if (this instanceof myClass) {\n console.log('You used the \"new\" keyword');\n } else {\n console.log('You did NOT use the \"new\" keyword');\n return;\n }\n // constructor logic here\n // ...\n});\n"
},
{
"answer_id": 38634166,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "instanceof new.target instanceof let inst = new x;\nx.call(inst);\n WeakSet WeakSet new.target new (function factory()\n{\n 'use strict';\n var log = console.log;\n\n function x()\n {\n log(isConstructing(this) ?\n 'Constructing' :\n 'Not constructing'\n );\n }\n\n var isConstructing, tracks;\n var hasOwnProperty = {}.hasOwnProperty;\n\n if (typeof WeakMap === 'function')\n {\n tracks = new WeakSet;\n isConstructing = function(inst)\n {\n if (inst instanceof x)\n {\n return tracks.has(inst) ?\n false : !!tracks.add(inst);\n }\n return false;\n }\n } else {\n isConstructing = function(inst)\n {\n return inst._constructed ?\n false : inst._constructed = true;\n };\n }\n var z = new x; // Constructing\n x.call(z) // Not constructing\n})();\n instanceof [[HasInstance]] function x() {\n if (this instanceof x) {\n /* Probably invoked as constructor */\n } else return 30;\n}\n"
},
{
"answer_id": 49252254,
"author": "BoB",
"author_id": 520919,
"author_profile": "https://Stackoverflow.com/users/520919",
"pm_score": 1,
"selected": false,
"text": "'use strict' this falsey !this function ctor() { 'use strict';\n if (typeof this === 'undefined') \n console.log('Function called under strict mode (this == undefined)');\n else if (this == (window || global))\n console.log('Function called normally (this == window)');\n else if (this instanceof ctor)\n console.log('Function called with new (this == instance)');\n return this; \n}\n this 'use strict' 'use strict' this window global new this function ctor() { 'use strict';\n if (!this) return ctor.apply(Object.create(ctor.prototype), arguments);\n console.log([this].concat([].slice.call(arguments)));\n return this;\n}\n this this this falsey Object.create(ctor.prototype) Function.apply() this this falsey"
},
{
"answer_id": 54713479,
"author": "Sumer",
"author_id": 6696684,
"author_profile": "https://Stackoverflow.com/users/6696684",
"pm_score": 0,
"selected": false,
"text": "function Car() {\n\n if (!(this instanceof Car)) return new Car();\n\n this.a = 1;\n console.log(\"Called as Constructor\");\n\n}\nlet c1 = new Car();\nconsole.log(c1);\n"
},
{
"answer_id": 66906007,
"author": "Tom Ebel",
"author_id": 4817547,
"author_profile": "https://Stackoverflow.com/users/4817547",
"pm_score": 1,
"selected": false,
"text": "var Vector = (function() {\n \n var Vector__proto__ = function Vector() {\n // Vector methods go here\n }\n \n var vector__proto__ = new Vector__proto__();;\n \n var Vector = function(size) {\n // vector properties and values go here\n this.x = 0;\n this.y = 0;\n this.x = 0;\n this.maxLen = size === undefined? -1 : size;\n \n };\n Vector.prototype = vector__proto__;\n \n return function(size){\n \n if ( Object.getOwnPropertyNames(this).length === 0 ) {\n // the new keyword WAS USED with the wrapper constructor\n return new Vector(size); \n } else { \n // the new keyword was NOT USED with the wrapper constructor\n return; \n };\n };\n})();\n"
},
{
"answer_id": 69041022,
"author": "santosh yadav",
"author_id": 11815280,
"author_profile": "https://Stackoverflow.com/users/11815280",
"pm_score": 0,
"selected": false,
"text": "\"use strict\"\nfunction Name(){\n console.log(this)\nif(this){\n alert(\"called by new\")\n}\nelse\n alert(\"did not called using new\")\n}\nnew Name()\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
367,781 | <p>I have a java me application and now I want to place that application at the server. I want to write the download page with servlet. I mean when the user keys in the servlet url and hit to that servlet, my jad file will send to the phone(user no need to click to download button or link.After page loading, the servlet will automatically send the jad file to the requested mobile phone.). </p>
<p>I tried with this code.</p>
<pre><code>> File exportFile = new File("C:\\Voice.jad");
> response.setContentType("text/vnd.sun.j2me.app-descriptor");
> response.setContentLength((int)
> exportFile.length());
> response.addHeader("Content-Disposition",
> "attachment; filename=" +
> exportFile.getName());
> OutputStream os= response.getOutputStream();
> InputStream is = new FileInputStream("C:\\Voice.jad");
> while (is.available() > 0) { char c =
> (char) is.read();
> os.write(c); }
> os.flush();
> is.close();
</code></pre>
<p>and I tried to download the application from Nokia Series 40th 5rd edition emulator. It shows the jad file's information and try to install. But on the way for installing, it said jar file doesn't exist.</p>
<p>I don't know how to move on. Please give me some information or samples.
How can I write the download page for java me application at the servlet?</p>
<p>Thanks you,
With Regards</p>
| [
{
"answer_id": 368788,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 1,
"selected": false,
"text": "MIDlet-1: BiteTravel, i3.png, main.MainMidlet\nMIDlet-Icon: i1.png\nMIDlet-Jar-Size: 109855 //this is very important -- jar size must match this number!\nMIDlet-Jar-URL: BiteTravelBite.jar\nMIDlet-Name: BiteTravel\nMIDlet-Vendor: Bite\nMIDlet-Version: 1.0\nMicroEdition-Configuration: CLDC-1.0\nMicroEdition-Profile: MIDP-2.0\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,786 | <p>It looks like if I load dynamic content using <code>$.get()</code>, the result is cached in browser.</p>
<p>Adding some random string in QueryString seems to solve this issue (I use <code>new Date().toString()</code>), but this feels like a hack. </p>
<p>Is there any other way to achieve this?
Or, if unique string is the only way to achieve this, any suggestions other than <code>new Date()</code>?</p>
| [
{
"answer_id": 367796,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 5,
"selected": false,
"text": "response.setHeader( \"Pragma\", \"no-cache\" );\nresponse.setHeader( \"Cache-Control\", \"no-cache\" );\nresponse.setDateHeader( \"Expires\", 0 );\n"
},
{
"answer_id": 367799,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": false,
"text": "Math.random()"
},
{
"answer_id": 367827,
"author": "Mark Bell",
"author_id": 43140,
"author_profile": "https://Stackoverflow.com/users/43140",
"pm_score": 9,
"selected": true,
"text": "new Date().getTime() $.get('/getdata?_=' + new Date().getTime(), function(data) {\n console.log(data); \n});\n"
},
{
"answer_id": 735084,
"author": "Jonathan Moffatt",
"author_id": 45031,
"author_profile": "https://Stackoverflow.com/users/45031",
"pm_score": 8,
"selected": false,
"text": "$.get(\"myurl\", myCallback)\n $.ajax({url: \"myurl\", success: myCallback, cache: false});\n"
},
{
"answer_id": 735101,
"author": "Peter J",
"author_id": 56018,
"author_profile": "https://Stackoverflow.com/users/56018",
"pm_score": 9,
"selected": false,
"text": "$.ajaxSetup({ cache: false });\n"
},
{
"answer_id": 16405968,
"author": "Athasach",
"author_id": 200348,
"author_profile": "https://Stackoverflow.com/users/200348",
"pm_score": 2,
"selected": false,
"text": "cache $.ajaxSetup() $.ajax() $.ajaxSetup()"
},
{
"answer_id": 17998639,
"author": "rstackhouse",
"author_id": 726378,
"author_profile": "https://Stackoverflow.com/users/726378",
"pm_score": 1,
"selected": false,
"text": "$.ajaxSetup({cache:false}) Cache-Control: no-cache"
},
{
"answer_id": 20344793,
"author": "xiaoyifang",
"author_id": 968188,
"author_profile": "https://Stackoverflow.com/users/968188",
"pm_score": -1,
"selected": false,
"text": "Math.random()"
},
{
"answer_id": 21286219,
"author": "Santosh Upadhayay",
"author_id": 2849250,
"author_profile": "https://Stackoverflow.com/users/2849250",
"pm_score": 2,
"selected": false,
"text": "cache:false;"
},
{
"answer_id": 29955080,
"author": "Benjamin RD",
"author_id": 3294396,
"author_profile": "https://Stackoverflow.com/users/3294396",
"pm_score": 4,
"selected": false,
"text": "cache $.ajax({\n method: \"GET\",\n url: \"/Home/AddProduct?\",\n data: { param1: value1, param2: value2},\n cache: false,\n success: function (result) {\n // TODO\n }\n});\n"
},
{
"answer_id": 30276834,
"author": "Marius",
"author_id": 362083,
"author_profile": "https://Stackoverflow.com/users/362083",
"pm_score": 1,
"selected": false,
"text": "[OutputCacheAttribute(VaryByParam = \"*\", Duration = 0, NoStore = true)]\n"
},
{
"answer_id": 33883423,
"author": "El Don",
"author_id": 4799029,
"author_profile": "https://Stackoverflow.com/users/4799029",
"pm_score": 1,
"selected": false,
"text": "$(function () {\n var url = 'your url goes here';\n $('#ajaxButton').click(function (e) {\n $.ajax({\n url: url,\n data: {\n test: 'value'\n },\n cache: true, //cache enabled, false to reverse\n complete: doSomething\n });\n });\n });\n //ToDo after ajax call finishes\n function doSomething(data) {\n console.log(data);\n }\n});\n"
},
{
"answer_id": 39606996,
"author": "Aidin",
"author_id": 2321594,
"author_profile": "https://Stackoverflow.com/users/2321594",
"pm_score": 5,
"selected": false,
"text": "$.ajax({\n url: url, \n headers: {\n 'Cache-Control': 'no-cache, no-store, must-revalidate', \n 'Pragma': 'no-cache', \n 'Expires': '0'\n }\n});"
},
{
"answer_id": 59158748,
"author": "Moaz Salem",
"author_id": 12314022,
"author_profile": "https://Stackoverflow.com/users/12314022",
"pm_score": 0,
"selected": false,
"text": "headers: {\n 'Cache-Control':'no-cache'\n }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10629/"
] |
367,789 | <p>Can you someone please point in me in a direction, sample code or an online resource to accomplish the following:</p>
<p><strong>Requirement:</strong>
I would like to write a simple IVR menu option that will run a script (Bash or Python). For example, phone the Asterisk machine and request to restart a service on another Linux box. The 'other Linux box' details would be hard coded to the IVR menu option and not needed to be supplied as part of the IVR interaction - just restart service X on box Y. I am little worried and unsure how one would secure this with a password (even if it is hard coded in version).</p>
<p><strong>Background:</strong>
I am an Asterisk newbie and installed it from the AsteriskNow distribution and I am still learning the product. The basic PBX functionality is working and is administered through FreePBX. Asterisk is not our main focus of development work but rather a tool in the toolbox. We mostly do .NET work but have Unix skills.</p>
<p>If possible I would not like to spend days learning the integrate details of Asterisk to get the job done...</p>
| [
{
"answer_id": 570816,
"author": "Chochos",
"author_id": 10165,
"author_profile": "https://Stackoverflow.com/users/10165",
"pm_score": 2,
"selected": false,
"text": "exten => 9999,1,GotoIf($[\"${CALLERID(num)}\" = \"yournumber\"]?4)\nexten => 9999,2,Playback(sorry)\nexten => 9999,3,Hangup\nexten => 9999,4,Read(Pin,please-enter-pin,4)\nexten => 9999,5,AGI(your-script) exten => 9999,5,GotoIf($[\"Pin\" != \"1234\"]?2)\nexten => 9999,6,AGI(your-script)"
},
{
"answer_id": 3642343,
"author": "Shrikant Soni",
"author_id": 165414,
"author_profile": "https://Stackoverflow.com/users/165414",
"pm_score": 2,
"selected": false,
"text": "exten => x,n,Playback(yourfile) \nexten => x,n,somethingelse...\n exten => x,n,Read(Exit,yourfile,1)\nexten => x,n,GotoIf($[\"${Exit}\" = \"0\"]?0,1) \nexten => x,n,somethingelse...\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11123/"
] |
367,797 | <p>I am using <code>Path.Combine</code>, and one of the strings contain a Unicode characters. I get <code>{System.ArgumentException} exception; illegal characters in path</code>.</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/aa365247.aspx" rel="nofollow noreferrer">MSDN</a> filepath/name can have unicode characters. Why do I get this exception?</p>
<h3>Edit:</h3>
<p>Here is the code:</p>
<pre><code>Path.Combine("C:\PDM\Silver","Amabel Bender QQQ")
</code></pre>
| [
{
"answer_id": 367816,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "Path.InvalidPathChars \"Amabel BenderQQQ\" \"AmabelBenderQQQ\""
},
{
"answer_id": 367835,
"author": "DilbertDave",
"author_id": 31580,
"author_profile": "https://Stackoverflow.com/users/31580",
"pm_score": 2,
"selected": false,
"text": "Path.Combine(\"C:\\\\PDM\\\\Silver\",\"Amabel Bender QQQ\")\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38997/"
] |
367,817 | <p>I want to achieve the following:</p>
<pre><code>ID | Counter
------------
0 | 343
1 | 8344
</code></pre>
<p>Now say that I want to update counter for ID 1,,, what is the easiest way to do it? Do I use sequences? do I simply read the value and update? Is there any special type for it?</p>
<p>I was thinking about using sequence but then I have to create one for each ID (which potentially can be over a 1000. I will also face the problem that I don't know how many sequences I will need so I would have to check if there is a sequence for that ID and etc... and I don't want that.</p>
<p>Assume that the numbers are users belonging to a certain group, then an alternative I was thinking about was to enter a row for each count and when I want to get the number I perform a select group by the id or something and get the numbers of rows.</p>
<p>EDIT: Clarification
I recieve a list of users in a csv that my program handles several times a day (new csv several times a day). Then depending on if the user has has sent a message today (for example) I increment the counter for the group in which this user belongs to. Now at a certain point I want to extract the groups (which can be dynamic, it depends on what I got during the day) and get the number I incremented and reset it.
Hopefully this explains it more :D</p>
<p>Thanks for the help so far, I will experiment :D</p>
<p>What do you think?</p>
| [
{
"answer_id": 367843,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 0,
"selected": false,
"text": "select id, count(users) from foo group by id"
},
{
"answer_id": 367852,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 3,
"selected": false,
"text": "UPDATE Table SET Counter = Counter + 1 WHERE ID = 1\n UPDATE Table SET Counter = 0 WHERE ID = 1\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46303/"
] |
367,819 | <p>In the external code that I am using there is enum: </p>
<pre><code>enum En {VALUE_A, VALUE_B, VALUE_C};
</code></pre>
<p>In another external code that I am using there are 3 #define directives: </p>
<pre><code>#define ValA 5
#define ValB 6
#define ValC 7
</code></pre>
<p>Many times I have int X which is equal to ValA or ValB or ValC, and I have to cast it to the corresponding value of En (ValA to VALUE_A, ValB to VALUEB, etc) because some function signature has enum En. And many times I have to do the opposite operation, translate enum En to ValA or ValB or ValC. I cannot change the signatures of these functions, and there are many such functions.</p>
<p>The question is: How to do the translation? Should I create 2 cast operators, which will be used implicitly? Or should I just have 2 translation functions which will be used explicitly:</p>
<pre><code>En ToEn(int)
int FromEn(En)
</code></pre>
<p>Or any other solution?</p>
| [
{
"answer_id": 367834,
"author": "Patrick",
"author_id": 38892,
"author_profile": "https://Stackoverflow.com/users/38892",
"pm_score": 1,
"selected": false,
"text": "//libFunc( enum a );\n\nlibFuncOverload( define a ) {\n libFunc( toEn( a ) );\n}\n"
},
{
"answer_id": 367968,
"author": "Mr.Ree",
"author_id": 37946,
"author_profile": "https://Stackoverflow.com/users/37946",
"pm_score": -1,
"selected": false,
"text": "#define ValA 5\n #define ValA VALUE_A\n #ifdef ValA\nSTATIC_ASSERT( ValA == VALUE_A, ValA_equal_VALUE_A );\n#undef ValA\n#else\n#warning \"ValA undefined. Defining as VALUE_A\"\n#endif\n#define ValA VALUE_A\n /* Use CONCATENATE_4_AGAIN to expand the arguments to CONCATENATE_4 */\n#define CONCATENATE_4( a,b,c,d) CONCATENATE_4_AGAIN(a,b,c,d)\n#define CONCATENATE_4_AGAIN(a,b,c,d) a ## b ## c ## d\n\n /* Creates a typedef that's legal/illegal depending on EXPRESSION. *\n * Note that IDENTIFIER_TEXT is limited to \"[a-zA-Z0-9_]*\". *\n * (This may be replaced by static_assert() in future revisions of C++.) */\n#define STATIC_ASSERT( EXPRESSION, IDENTIFIER_TEXT) \\\n typedef char CONCATENATE_4( static_assert____, IDENTIFIER_TEXT, \\\n ____failed_at_line____, __LINE__ ) \\\n [ (EXPRESSION) ? 1 : -1 ]\n"
},
{
"answer_id": 368050,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 5,
"selected": true,
"text": "template<typename T>\nT my_enum_convert(int);\n\ntemplate<>\nEn my_enum_convert<En>(int in) {\n switch(in) {\n case ValA: return VALUE_A;\n case ValB: return VALUE_B;\n case ValC: return VALUE_C;\n default: throw std::logic_error(__FILE__ \": enum En out of range\");\n }\n}\n\nint my_enum_convert(En in) {\n switch(in) {\n case VALUE_A: return ValA;\n case VALUE_B: return ValB;\n case VALUE_C: return ValC;\n // no default, so that GCC will warn us if we've forgotten a case\n }\n}\n\nEn enumValue = my_enum_convert<En>(ValA);\nint hashDefineValue = my_enum_convert(VALUE_A);\nenumValue = my_enum_convert<En>(0); // throws exception\n template<typename T>\nT my_enum_convert(En in) {\n switch(in) {\n case VALUE_A: return ValA;\n case VALUE_B: return ValB;\n case VALUE_C: return ValC;\n }\n}\n\nint hashDefineValue = my_enum_convert<int>(VALUE_A);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44673/"
] |
367,823 | <p>Can anyone tell me how to write a nested SQL query like </p>
<p>SELECT * FROM X WHERE X.ID IN (SELECT Y.XID FROM Y WHERE .....)</p>
<p>in LINQ?</p>
| [
{
"answer_id": 367829,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "var yIds = from y in dataContext.Y\n where ...\n select y.XId;\n\nvar query = from x in dataContext.X\n where yIds.Contains(x.Id)\n select x;\n var query = from x in dataContext.X\n join y in dataContext.Y.Where(...) on x.Id equals y.Xid\n select x;\n"
},
{
"answer_id": 367831,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 3,
"selected": false,
"text": "var query = from x in GetX()\n where (from y in GetY() select y.xID).Contains(x.xID)\n select x;\n"
},
{
"answer_id": 5302190,
"author": "MikeM",
"author_id": 222714,
"author_profile": "https://Stackoverflow.com/users/222714",
"pm_score": 3,
"selected": false,
"text": "NOT IN NorthwindDataContext dc = new NorthwindDataContext();\nvar query =\n from c in dc.Customers\n where !(from o in dc.Orders\n select o.CustomerID)\n .Contains(c.CustomerID)\n select c;\n Dim db As New NorthwinDataContext()\nDim query = From c In dc.Customers _\n Where Not (From o in dc.Orders _\n Select o.CustomerID).Contains(c.CustomerID) _\n Select c\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34623/"
] |
367,824 | <p><em>It is a messy question, hopefully you can figure out what I want :)</em></p>
<p><strong>What is the best way to use Win32 functionality in a Qt Open Source Edition project?</strong></p>
<p>Currently I have included the necessary Windows SDK libraries and include directories to qmake project file by hand. It works fine on a small scale, but its inconvenient and cumbersome. </p>
<p>So, should I separate the Win32 stuff into a library or is there a sensible way of combining these two? Or have I just overlooked some Qt aspect that simplifies this?</p>
<p><strong>EDIT</strong></p>
<p>Removed the syntax stuff, its not really relevant, just annoying.</p>
| [
{
"answer_id": 368249,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "wchar_t const*"
},
{
"answer_id": 406663,
"author": "Henrik Hartz",
"author_id": 50830,
"author_profile": "https://Stackoverflow.com/users/50830",
"pm_score": 0,
"selected": false,
"text": "win32:HEADERS+=mywinheader.h\n win32:include( mywinpri.pri )\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40657/"
] |
367,846 | <p>I'm currently using the ModelStateDictionary in asp.net mvc to hold validation errors and pass then back to the user. Being able to check if the whole model is valid with ModelState.IsValid is particularly. However, a current application I'm working on has a need to be able to report warnings. These aren't as critical so the form content can still be saved, but they should be shown to the user so that action can be optionally taken.</p>
<p>I've been looking through the framework to see if there are any obvious place to extend it to allow me to do this. I'm thinking that another dictionary with warnings in and a subclass of model error called model warning. I'm not sure how I'd get the framework to use my new container classes in the view etc. though, I still want all of the existing error stuff to work.</p>
<p>If anyone has tried anything similar or has any thoughts I'd appreciate their input.</p>
<p>Update:</p>
<p>I've got as far as extending the ViewDataDictionary to add some warnings</p>
<pre><code>public class AetherViewDataDictionary : ViewDataDictionary
{
public AetherViewDataDictionary()
{
ModelStateWarning = new ModelStateDictionary();
}
public AetherViewDataDictionary(object model) : base(model)
{
ModelStateWarning = new ModelStateDictionary();
}
public AetherViewDataDictionary(ViewDataDictionary viewDataDictionary) : base(viewDataDictionary)
{
ModelStateWarning = new ModelStateDictionary();
}
public ModelStateDictionary ModelStateWarning { get; private set; }
}
</code></pre>
<p>The problem that I'm having now is that when I get to my view code, this is just for debug I'm losing the fact that its my new type, so when I try to cast it back and get access to my new dictionary I have no joy.</p>
<pre><code>public partial class Index : ViewPage<PageViewData>
{
protected override void SetViewData(ViewDataDictionary viewData)
{
base.SetViewData(viewData);
}
}
</code></pre>
<p>It sets it correctly here, but when I check the type its gone.</p>
<p>Edit:
This turned out to be a dumb way of doing things, see answer below.</p>
| [
{
"answer_id": 368155,
"author": "Mike Scott",
"author_id": 43649,
"author_profile": "https://Stackoverflow.com/users/43649",
"pm_score": 2,
"selected": false,
"text": "ViewData[ \"warnings\" ] = new[] { \"You need to snarfle your aardvark\" } ;\n"
},
{
"answer_id": 370779,
"author": "Simon Farrow",
"author_id": 35047,
"author_profile": "https://Stackoverflow.com/users/35047",
"pm_score": 4,
"selected": true,
"text": "public class AetherModelState : ModelState\n{\n public AetherModelState() { }\n\n public AetherModelState(ModelState state)\n {\n this.AttemptedValue = state.AttemptedValue;\n\n foreach (var error in state.Errors)\n this.Errors.Add(error);\n }\n\n private ModelErrorCollection _warnings = new ModelErrorCollection();\n\n public ModelErrorCollection Warnings { get { return this._warnings; } }\n}\n public static class ModelStateDictionaryExtensions\n{\n public static void AddModelWarning(this ModelStateDictionary msd, string key, Exception exception)\n {\n GetModelStateForKey(key, msd).Warnings.Add(exception);\n }\n\n public static void AddModelWarning(this ModelStateDictionary msd, string key, string errorMessage)\n {\n GetModelStateForKey(key, msd).Warnings.Add(errorMessage);\n }\n\n private static AetherModelState GetModelStateForKey(string key, ModelStateDictionary msd)\n {\n ModelState state;\n if (string.IsNullOrEmpty(key))\n throw new ArgumentException(\"key\");\n\n if (!msd.TryGetValue(key, out state))\n {\n msd[key] = state = new AetherModelState();\n }\n\n if (!(state is AetherModelState))\n {\n msd.Remove(key);\n msd[key] = state = new AetherModelState(state);\n }\n\n return state as AetherModelState;\n }\n\n public static bool HasWarnings(this ModelStateDictionary msd)\n {\n return msd.Values.Any<ModelState>(delegate(ModelState modelState)\n {\n var aState = modelState as AetherModelState;\n if (aState == null) return true;\n return (aState.Warnings.Count == 0);\n });\n }\n}\n"
},
{
"answer_id": 52849657,
"author": "Carsten Franke",
"author_id": 4944034,
"author_profile": "https://Stackoverflow.com/users/4944034",
"pm_score": 0,
"selected": false,
"text": "Data Errors Data Warnings DataSourceResult // The wrapper\npublic class DataSourceResultWithWarnings: DataSourceResult\n{\n public object Warnings { get; }\n\n public DataSourceResultWithWarnings(DataSourceResult dataSourceResult, IDictionary<string, IDictionary<string, IList<string>>> warnings)\n {\n this.AggregateResults = dataSourceResult.AggregateResults;\n this.Data = dataSourceResult.Data;\n this.Errors = dataSourceResult.Errors;\n this.Total = dataSourceResult.Total;\n Warnings = warnings;\n }\n}\n\n// The extension method\npublic static IDictionary<string, IDictionary<string, IList<string>>> GetWarnings(this ModelStateDictionary msd)\n{\n var result = new Dictionary<string, IDictionary<string, IList<string>>>();\n\n for (var i = 0; i < msd.Values.Count; i++)\n {\n var wms = msd.Values.ElementAt(i) as WarningModelState;\n if (wms != null)\n {\n if (!result.ContainsKey(msd.Keys.ElementAt(i)))\n {\n result.Add(msd.Keys.ElementAt(i), new Dictionary<string, IList<string>>() { { \"warnings\", new List<string>() } });\n }\n result[msd.Keys.ElementAt(i)][\"warnings\"].AddRange((from rec in wms.Warnings select rec.ErrorMessage));\n }\n }\n\n return result;\n}\n\n// How to use it in the controller action\nvar result = new DataSourceResultWithWarnings(files.Values.ToDataSourceResult(request, ModelState), ModelState.GetWarnings());\nreturn Json(result, JsonRequestBehavior.AllowGet);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35047/"
] |
367,847 | <p>There is a div that has inner content, a div with a border that's inside a div. Somehow, this div is expanded to encompass the next div. It blows my mind.</p>
<pre><code><div style="background: yellow;">
<div>
<div style="border: 1px solid black; background: green">green background</div>
</div>
</div>
<div style="margin-top: 100px;">
IE gives me a yellow background, unless i take away the border of the green
background div.
</div>
</code></pre>
<p>I'm wondering the cause of this and how to solve it.</p>
| [
{
"answer_id": 367858,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n"
},
{
"answer_id": 367860,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 0,
"selected": false,
"text": "<div style=\"border: 1px solid black; background: green;\">green background</div>\n <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n <head>\n <title>Test</title>\n </head> \n <body>\n <div style=\"background: yellow;\">\n <div>\n <div style=\"border: 1px solid black; background: green;\">green background</div>\n </div>\n </div>\n <div style=\"margin-top: 100px;\">\n IE gives me a yellow background, unless i take away the border of the green \n background div.\n </div>\n </body>\n</html>\n"
},
{
"answer_id": 367900,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 1,
"selected": true,
"text": "<style>\n * html .haslayout {\n display:inline-block;\n }\n</style>\n\n...\n\n<div style=\"background: yellow;\" class=\"haslayout\">\n"
},
{
"answer_id": 369958,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<div style=\"background: yellow;height: 1%;\">\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43005/"
] |
367,853 | <p>Below is my stored procedure. I want use stored procedure select all row of date from tbl_member and insert 2 table. But it's not work. Some one can help me?</p>
<pre><code>Create PROCEDURE sp_test
AS
BEGIN
SET NOCOUNT ON;
Declare @A Varchar(255), @B Varchar(255), @C Varchar(255), @D int
Declare Table_Cursor Cursor
For select A, B, C from tbl_Member Open Table_Cursor
Fetch Next From Table_Cursor
Into @A, @B, @C While(@@Fetch_Status=0)
Begin Exec(
'insert into NewMember (A, B, C, D) values (@A, @B, @C, @D)
set @D = @@IDENTITY
Insert into MemberId (Mid) VALUES(@D)
)
Fetch Next From Table_Cursor Into @A, @B, @C End Close Table_Cursor
Deallocate Table_Cursor
END
GO
</code></pre>
| [
{
"answer_id": 367875,
"author": "Pete OHanlon",
"author_id": 43635,
"author_profile": "https://Stackoverflow.com/users/43635",
"pm_score": 4,
"selected": true,
"text": "INSERT INTO NewMember(A, B, C, D)\nSELECT A, B, C, D\nFROM tbl_member\n create trigger myInsertTrigger\non newmember\nfor insert\nas\ninsert into memberid(mid)\nselect <<identity_column>> from inserted\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44260/"
] |
367,859 | <p>Does any one know of a control that i can use with a ASP.Net gridview that provides the functionality of the ASP.Net Ajax Control PagingBulletedList. I want to provide the users with a easier way to access the data in the grid.</p>
<p>It should ideally work in the same way paging for the grid works except that it should show all the data for the selected option i.e. if the letter a is selected all items that begin with a are shown to the user.</p>
<p>I would prefer not to have to re develop something like this as i am sure it exists, i just have no idea what would you call it.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 380120,
"author": "jpsimard-nyx",
"author_id": 47109,
"author_profile": "https://Stackoverflow.com/users/47109",
"pm_score": 2,
"selected": true,
"text": "<asp:UpdatePanel runat=\"server\" ID=\"UpdatePanel\">\n<asp:GridView runat=\"server\" ID=\"GridView\">\n <PagerTemplate>\n <asp:LinkButton runat=\"server\" Text=\"A\" Command=\"A\" />\n-\n <asp:LinkButton runat=\"server\" Text=\"B\" Command=\"B\" />\n-\n <asp:LinkButton runat=\"server\" Text=\"C\" Command=\"C\" />\n-\n <asp:LinkButton runat=\"server\" Text=\"D\" Command=\"D\" />\n-\n <asp:LinkButton runat=\"server\" Text=\"E\" Command=\"E\" />\n<%-- Continue at will... --%>\n </PagerTemplate>\n</asp:GridView>\n</asp:UpdatePanel>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42069/"
] |
367,862 | <p>I would like to build a regexp in Java that would be passed in a FilenameFilter to filter the files in a dir.</p>
<p>The problem is that I can't get the hang of the regexp "mind model" :)</p>
<p>This is the regexp that I came up with to select the files that I would like to exclude </p>
<p>((ABC|XYZ))+\w*Test.xml</p>
<p>What I would like to do is to select all the files that end with Test.xml but do not start with ABC or XYZ.</p>
<p>Could you please add any resources that could help me in my battle with regexps.</p>
<p>Thanks</p>
<p>The following resource explains a lot of things about regexp <a href="http://www.regular-expressions.info/refadv.html" rel="nofollow noreferrer">regular-expressions.info</a></p>
| [
{
"answer_id": 367868,
"author": "Yoni Roit",
"author_id": 34161,
"author_profile": "https://Stackoverflow.com/users/34161",
"pm_score": 3,
"selected": false,
"text": "if (str.endsWith(\"Test.xml\") && !str.startsWith(\"ABC\"))\n"
},
{
"answer_id": 367882,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "(?ms)^([^\\r\\n]{3}(?<!ABC|XYZ)[^\\r\\n]*?)?Test\\.xml$\n (?<!ABC|XYZ)"
},
{
"answer_id": 367928,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "Test.xml ABC XYZ ^(?:(?:...)(?<!ABC|XYZ).*?)?Test\\.xml$\n ^(?:ABC|XYZ).*?Test\\.xml$\n"
},
{
"answer_id": 369653,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 1,
"selected": false,
"text": "matches() ^ $ \\z public boolean accept(File dir, String name) {\n return name.matches(\"(?!ABC|XYZ).*Test\\\\.xml\");\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38973/"
] |
367,863 | <p>I've got the following two tables (in MySQL):</p>
<pre><code>Phone_book
+----+------+--------------+
| id | name | phone_number |
+----+------+--------------+
| 1 | John | 111111111111 |
+----+------+--------------+
| 2 | Jane | 222222222222 |
+----+------+--------------+
Call
+----+------+--------------+
| id | date | phone_number |
+----+------+--------------+
| 1 | 0945 | 111111111111 |
+----+------+--------------+
| 2 | 0950 | 222222222222 |
+----+------+--------------+
| 3 | 1045 | 333333333333 |
+----+------+--------------+
</code></pre>
<p>How do I find out which calls were made by people whose <code>phone_number</code> is not in the <code>Phone_book</code>? The desired output would be:</p>
<pre><code>Call
+----+------+--------------+
| id | date | phone_number |
+----+------+--------------+
| 3 | 1045 | 333333333333 |
+----+------+--------------+
</code></pre>
| [
{
"answer_id": 367865,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 10,
"selected": true,
"text": "SELECT *\nFROM Call\nWHERE phone_number NOT IN (SELECT phone_number FROM Phone_book)\n SELECT *\nFROM Call\nWHERE NOT EXISTS\n (SELECT *\n FROM Phone_book\n WHERE Phone_book.phone_number = Call.phone_number)\n SELECT * \nFROM Call\nLEFT OUTER JOIN Phone_Book\n ON (Call.phone_number = Phone_book.phone_number)\n WHERE Phone_book.phone_number IS NULL\n *"
},
{
"answer_id": 367873,
"author": "Alterlife",
"author_id": 36848,
"author_profile": "https://Stackoverflow.com/users/36848",
"pm_score": 5,
"selected": false,
"text": "SELECT *\nFROM Call\nWHERE NOT EXISTS (\n SELECT 'x'\n FROM Phone_book\n WHERE Phone_book.phone_number = Call.phone_number\n);\n"
},
{
"answer_id": 368123,
"author": "WOPR",
"author_id": 46255,
"author_profile": "https://Stackoverflow.com/users/46255",
"pm_score": 7,
"selected": false,
"text": "SELECT Call.ID, Call.date, Call.phone_number \nFROM Call \nLEFT OUTER JOIN Phone_Book \n ON (Call.phone_number=Phone_book.phone_number) \n WHERE Phone_book.phone_number IS NULL\n"
},
{
"answer_id": 9293547,
"author": "A dev",
"author_id": 1102016,
"author_profile": "https://Stackoverflow.com/users/1102016",
"pm_score": 3,
"selected": false,
"text": "SELECT CALL.* FROM CALL LEFT JOIN Phone_book ON \nCALL.id = Phone_book.id WHERE Phone_book.name IS NULL\n"
},
{
"answer_id": 14356484,
"author": "Vlado",
"author_id": 1196945,
"author_profile": "https://Stackoverflow.com/users/1196945",
"pm_score": 3,
"selected": false,
"text": "SELECT DISTINCT Call.id \nFROM Call \nLEFT OUTER JOIN Phone_book USING (id) \nWHERE Phone_book.id IS NULL\n"
},
{
"answer_id": 19569328,
"author": "Harvinder Sidhu",
"author_id": 2916371,
"author_profile": "https://Stackoverflow.com/users/2916371",
"pm_score": 2,
"selected": false,
"text": "SELECT t1.ColumnID,\nCASE \n WHEN NOT EXISTS( SELECT t2.FieldText \n FROM Table t2 \n WHERE t2.ColumnID = t1.ColumnID) \n THEN t1.FieldText\n ELSE t2.FieldText\nEND FieldText \nFROM Table1 t1, Table2 t2\n"
},
{
"answer_id": 34183705,
"author": "JoshYates1980",
"author_id": 3175526,
"author_profile": "https://Stackoverflow.com/users/3175526",
"pm_score": 1,
"selected": false,
"text": "SELECT name, phone_number FROM Call a\nWHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b)\n"
},
{
"answer_id": 45796484,
"author": "elifekiz",
"author_id": 6109649,
"author_profile": "https://Stackoverflow.com/users/6109649",
"pm_score": 1,
"selected": false,
"text": "select id from call\nminus\nselect id from phone_number\n"
},
{
"answer_id": 67100401,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 1,
"selected": false,
"text": "phone_number SELECT *\nFROM Call\nWHERE NOT EXISTS\n (SELECT *\n FROM Phone_book\n WHERE Phone_book.phone_number = Call.phone_number)\n Phone_Book Call phone_number ALTER TABLE [dbo].Phone_Book ADD CONSTRAINT [IX_Unique_PhoneNumber] UNIQUE NONCLUSTERED \n(\n Phone_Number\n)\nWITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ONLINE = ON) ON [PRIMARY]\nGO\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
367,870 | <p>If someone logs on to my application this user contains a dictionary with certain permissions.</p>
<pre><code>ex: module.view.workspace = true
module.view.reporting = false
...
</code></pre>
<p>Then we know to what parts of the application the user has access.
What I want to know is how we can apply these permissions on the view.
We are working in an AS 3 (FLEX) environment.</p>
<p>This is what we came up with so far (but I wanna have an idea of other possibilities).
We have a modelLocator storing the loggedOnUser (which contains it's permissions).
these permissions are added to a permissionObject in the modellocator.
We Create a SecurityManager class that has a function called hasAccess("permission").
This object will check the PermissionObject in the modellocator and return true/false.
In the view we just check if the user has access and then show the control.</p>
<pre><code>If (SecurityManager.hasAccess("module.view.workspace") {
// code that generates the workspace;
}
</code></pre>
<p>I just don't know if this is the best practice.
Please help me out here.</p>
| [
{
"answer_id": 367865,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 10,
"selected": true,
"text": "SELECT *\nFROM Call\nWHERE phone_number NOT IN (SELECT phone_number FROM Phone_book)\n SELECT *\nFROM Call\nWHERE NOT EXISTS\n (SELECT *\n FROM Phone_book\n WHERE Phone_book.phone_number = Call.phone_number)\n SELECT * \nFROM Call\nLEFT OUTER JOIN Phone_Book\n ON (Call.phone_number = Phone_book.phone_number)\n WHERE Phone_book.phone_number IS NULL\n *"
},
{
"answer_id": 367873,
"author": "Alterlife",
"author_id": 36848,
"author_profile": "https://Stackoverflow.com/users/36848",
"pm_score": 5,
"selected": false,
"text": "SELECT *\nFROM Call\nWHERE NOT EXISTS (\n SELECT 'x'\n FROM Phone_book\n WHERE Phone_book.phone_number = Call.phone_number\n);\n"
},
{
"answer_id": 368123,
"author": "WOPR",
"author_id": 46255,
"author_profile": "https://Stackoverflow.com/users/46255",
"pm_score": 7,
"selected": false,
"text": "SELECT Call.ID, Call.date, Call.phone_number \nFROM Call \nLEFT OUTER JOIN Phone_Book \n ON (Call.phone_number=Phone_book.phone_number) \n WHERE Phone_book.phone_number IS NULL\n"
},
{
"answer_id": 9293547,
"author": "A dev",
"author_id": 1102016,
"author_profile": "https://Stackoverflow.com/users/1102016",
"pm_score": 3,
"selected": false,
"text": "SELECT CALL.* FROM CALL LEFT JOIN Phone_book ON \nCALL.id = Phone_book.id WHERE Phone_book.name IS NULL\n"
},
{
"answer_id": 14356484,
"author": "Vlado",
"author_id": 1196945,
"author_profile": "https://Stackoverflow.com/users/1196945",
"pm_score": 3,
"selected": false,
"text": "SELECT DISTINCT Call.id \nFROM Call \nLEFT OUTER JOIN Phone_book USING (id) \nWHERE Phone_book.id IS NULL\n"
},
{
"answer_id": 19569328,
"author": "Harvinder Sidhu",
"author_id": 2916371,
"author_profile": "https://Stackoverflow.com/users/2916371",
"pm_score": 2,
"selected": false,
"text": "SELECT t1.ColumnID,\nCASE \n WHEN NOT EXISTS( SELECT t2.FieldText \n FROM Table t2 \n WHERE t2.ColumnID = t1.ColumnID) \n THEN t1.FieldText\n ELSE t2.FieldText\nEND FieldText \nFROM Table1 t1, Table2 t2\n"
},
{
"answer_id": 34183705,
"author": "JoshYates1980",
"author_id": 3175526,
"author_profile": "https://Stackoverflow.com/users/3175526",
"pm_score": 1,
"selected": false,
"text": "SELECT name, phone_number FROM Call a\nWHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b)\n"
},
{
"answer_id": 45796484,
"author": "elifekiz",
"author_id": 6109649,
"author_profile": "https://Stackoverflow.com/users/6109649",
"pm_score": 1,
"selected": false,
"text": "select id from call\nminus\nselect id from phone_number\n"
},
{
"answer_id": 67100401,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 1,
"selected": false,
"text": "phone_number SELECT *\nFROM Call\nWHERE NOT EXISTS\n (SELECT *\n FROM Phone_book\n WHERE Phone_book.phone_number = Call.phone_number)\n Phone_Book Call phone_number ALTER TABLE [dbo].Phone_Book ADD CONSTRAINT [IX_Unique_PhoneNumber] UNIQUE NONCLUSTERED \n(\n Phone_Number\n)\nWITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ONLINE = ON) ON [PRIMARY]\nGO\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29964/"
] |
367,884 | <blockquote>
<p>Possible duplicate
<a href="https://stackoverflow.com/questions/90871/debug-vs-release-in-net">Debug Visual Studio Release in .NET</a></p>
</blockquote>
<p>What is the difference between Debug and Release in Visual Studio?</p>
| [
{
"answer_id": 367903,
"author": "foraidt",
"author_id": 27596,
"author_profile": "https://Stackoverflow.com/users/27596",
"pm_score": 3,
"selected": false,
"text": "MFC90D.DLL MFC90.DLL"
},
{
"answer_id": 33577702,
"author": "jxramos",
"author_id": 1330381,
"author_profile": "https://Stackoverflow.com/users/1330381",
"pm_score": 2,
"selected": false,
"text": "<PropertyGroup>\n <WholeProgramOptimization>true</WholeProgramOptimization>\n\n<ClCompile>\n <Optimization>MaxSpeed</Optimization>\n <FunctionLevelLinking>true</FunctionLevelLinking>\n <IntrinsicFunctions>true</IntrinsicFunctions>\n<Link>\n <EnableCOMDATFolding>true</EnableCOMDATFolding>\n <OptimizeReferences>true</OptimizeReferences>\n <PropertyGroup>\n <UseDebugLibraries>true</UseDebugLibraries>`\n\n<ClCompile>\n <Optimization>Disabled</Optimization>\n GenerateDebugInformation"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45624/"
] |
367,905 | <p>All the generated webservice-stubs from our backend have an equals-method similar to this one:</p>
<pre><code>private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof PropertyData)) return false;
PropertyData other = (PropertyData) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.key==null && other.getKey()==null) ||
(this.key!=null &&
this.key.equals(other.getKey()))) &&
((this.value==null && other.getValue()==null) ||
(this.value!=null &&
this.value.equals(other.getValue())));
__equalsCalc = null;
return _equals;
}
</code></pre>
<p>Can someone please explain to me the purpoise of <code>__equalsCalc</code>? I just don't get it. It is not used somewhere else in the class. The way I see it, it is not null exactly during the calculation of the "equality". However the equals is declared <code>synchronized</code>. Therefore only one thread can be in it at any given time.
I can't see, why <code>if (__equalsCalc != null)</code> should ever be true.</p>
<p>Please show me my stupid misunderstanding ;-)</p>
<p>EDIT: I am new to the project and therefore my answer may be wrong. But if I trace it correctly, the method is generated by axis-wsdl2java</p>
| [
{
"answer_id": 367911,
"author": "David Santamaria",
"author_id": 24097,
"author_profile": "https://Stackoverflow.com/users/24097",
"pm_score": -1,
"selected": false,
"text": "__equalsCalc = null;\n"
},
{
"answer_id": 367923,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": " // The __equalsCalc field and synchronized method are necessary\n // in case the object has direct or indirect references to itself.\n // Have we been here before ? return true if yes otherwise false\n pw.println(\" if (__equalsCalc != null) {\");\n pw.println(\" return (__equalsCalc == obj);\");\n pw.println(\" }\");\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] |
367,907 | <p>I'm trying to follow the directions from this page:<br>
<a href="http://www.opengl.org/resources/faq/technical/color.htm" rel="nofollow noreferrer">http://www.opengl.org/resources/faq/technical/color.htm</a><br>
regarding rendering primitives with a unique color</p>
<p>I've checked the number of bits for every color and the result was 8 for each.<br>
When calling:</p>
<pre><code> glColor3ui(0x80000000, 0, 0xFF000000);
</code></pre>
<p>and reading back the pixel with glReadPixels() I get the color: <code>0xFFFE007F</code><br>
which corresponts to <code>R=0x7F, G=0, B=0xFE</code><br>
The two lower bits of Red and Blue are wrong.</p>
<p>Why is that?<br>
I'm using a brand new nVidia card on a dell laptop with the most current drivers</p>
| [
{
"answer_id": 367921,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 1,
"selected": false,
"text": "In either event, you'll need to ensure that any state that could\naffect the final color has been disabled. The following code will\naccomplish this:\n\nglDisable (GL_BLEND); glDisable (GL_DITHER);\nglDisable (GL_FOG); glDisable (GL_LIGHTING);\nglDisable (GL_TEXTURE_1D); glDisable (GL_TEXTURE_2D);\nglDisable (GL_TEXTURE_3D); glShadeModel (GL_FLAT); \n"
},
{
"answer_id": 367959,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 2,
"selected": false,
"text": "glColor3ui(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF);\n glColor3ui(0xFF000000, 0xFF000000, 0xFF000000);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
] |
367,914 | <p>Say I have accepted() a connection to my server (that runs on a Solaris) and the client has closed the connection. What is the state of the socket (in netstat categories) of the socket on the server side before I close() it on the server side? Is it BOUND?</p>
| [
{
"answer_id": 5734167,
"author": "user595997",
"author_id": 595997,
"author_profile": "https://Stackoverflow.com/users/595997",
"pm_score": 0,
"selected": false,
"text": "CLOSE_WAIT FIN TIME_WAIT CLOSED CLOSE_WAIT"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7593/"
] |
367,934 | <p>Having read an existing post on <a href="https://stackoverflow.com/questions/305605/weird-scope-issue-in-bat-file">stackoverflow</a> and done some reading around on the net. I thought it was time to post my question before I lost too much hair!</p>
<p>I have the following code within a batch file which I double click to run, under Windows XP SP3:</p>
<pre><code>SETLOCAL ENABLEDELAYEDEXPANSION
::Observe variable is not defined
SET test
::Define initial value
SET test = "Two"
::Observe initial value is set
SET test
::Verify if the contents of the variable matches our condition
If "!test!" == "Two" GOTO TWO
::First Place holder
:ONE
::Echo first response
ECHO "One"
::Second Place holder
:TWO
::Echo second response
ECHO "Two"
::Await user input
PAUSE
ENDLOCAL
</code></pre>
<p>Basically I am trying to establish if I can navigate through my script using conditionals. It seems apparent that I am getting some issues with variable scope and delayed variable expansion yet I'm a little lost on what I'm doing wrong.</p>
<p>Can anyone point me in the right direction?</p>
| [
{
"answer_id": 368076,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": true,
"text": "@echo off\n\nSETLOCAL ENABLEDELAYEDEXPANSION\n\n::Observe variable is not defined\nSET test\n\n::Define initial value\nSET test = \"Two\"\n\n::Observe initial value is set\nSET test\necho %test%\necho..%test %.\n\n::Verify if the contents of the variable matches our condition\nIf \"!test!\" == \"Two\" GOTO TWO\n\n::First Place holder\n:ONE\n\n::Echo first response\nECHO \"One\"\n\n::Second Place holder\n:TWO\n\n::Echo second response\nECHO \"Two\"\n\n::Await user input\nPAUSE\n\nENDLOCAL\n Environment variable test not defined\ntest = \"Two\"\n. \"Two\".\n\"One\"\n\"Two\"\nPress any key to continue . . .\n set test=Two\n if \"!test!\" == \"Two\" (\n set test=TwoAndABit\n echo !test!\n)\n"
},
{
"answer_id": 738558,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "SET test = \"Two\"\n If \"!test!\" == \"Two\" GOTO TWO\n If \" \"Two\"\" == \"Two\" GOTO TWO\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40593/"
] |
367,940 | <p>I hope it is correct term-wise to say that components in a GUI is like JButton, JPanel, JTextField, all that good stuff.</p>
<p>I want to create a text field that takes in an integer. Then a submit button can be pressed and based on the integer that was inputted, create that many textfields in a popup window or whatever.</p>
<p>I have no clue, could someone get me started in the right direction?</p>
<p>The trouble I'm having is that I have no clue how to create a for loop to create the GUI components. I mean if I have a for loop and do something like:</p>
<pre><code>print("JTextField num1 = new JTextField()");
</code></pre>
<p>then in a for loop it will only create 1 text field when I want many. How do I generically create variables of JTextFields?</p>
<p>Thanks for your help...</p>
| [
{
"answer_id": 367943,
"author": "Mario Ortegón",
"author_id": 2309,
"author_profile": "https://Stackoverflow.com/users/2309",
"pm_score": 0,
"selected": false,
"text": "List fields = new ArrayList();\n\n// Create as many elements as you need\nfor (int i = 0; i < numberOfElements; i++){\n JTextField field = new JTextField();\n // Add the fields to some panel so they are shown in the screen. \n // I assume that the component is called parent panel\n parentPanel.add(field);\n\n // Store the component in the list so you can retrieve it later\n fields.add(field);\n}\n\n// ...\n\n// When you want to retrieve a particular one:\n\nJTextField field = (JTextField)fields.get( indexToRetrieve );\n"
},
{
"answer_id": 367948,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 4,
"selected": true,
"text": "for (i = 0; i < numberOfTextFields; i++) {\n JTextField textField = new JTextField();\n container.add(textField);\n /* also store textField somewhere else. */\n}\n"
},
{
"answer_id": 367949,
"author": "Daniel Rikowski",
"author_id": 23368,
"author_profile": "https://Stackoverflow.com/users/23368",
"pm_score": 1,
"selected": false,
"text": "List<JTextField> nums = new ArrayList<JTextField>();\nJTextField tempField;\n\nfor (int i = 0; i < 10; i++) {\n tempField = new JTextField();\n jPanel1.add(tempField); // Assuming all JTextFields are on a JPanel\n nums.add(tempField);\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51518/"
] |
367,947 | <p>What is the c# equivalent of the following c++:</p>
<pre><code>srand((unsigned)(time(NULL)));
weight=(double)(rand())/(RAND_MAX/2) - 1;
</code></pre>
| [
{
"answer_id": 367955,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 2,
"selected": false,
"text": "Random rnd = new Random((int)DateTime.Now.Ticks);\nreturn rnd.Next(-1,1);\n"
},
{
"answer_id": 368942,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 2,
"selected": false,
"text": "Random rnd = new Random();\nreturn rnd.Next(-1, 1);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
367,966 | <p>For testing purposes I'm planning to put together a little app that will listen for a particular event coming from an application and interact with it at that point. </p>
<p>Given that we're at a point in the testing process where changing the application code is out of the question, the ideal from my point of view would be to listen to the debugging trace from the application, a little like debugview does, and respond to that.</p>
<p>Can anyone offer guidance on how best to go about this?</p>
| [
{
"answer_id": 368028,
"author": "Arnout",
"author_id": 3496,
"author_profile": "https://Stackoverflow.com/users/3496",
"pm_score": 1,
"selected": false,
"text": "System.Diagnostics"
},
{
"answer_id": 374392,
"author": "glenatron",
"author_id": 15394,
"author_profile": "https://Stackoverflow.com/users/15394",
"pm_score": 4,
"selected": true,
"text": " MDbgEngine mg;\n MDbgProcess mgProcess;\n try\n {\n mg = new MDbgEngine();\n mgProcess = mg.Attach(debugProcess.Id);\n }\n catch (Exception ed)\n {\n Console.WriteLine(\"Exception attaching to process \" + debugProcess.Id );\n throw (ed);\n }\n mgProcess.CorProcess.EnableLogMessages(true);\n mgProcess.CorProcess.OnLogMessage += new LogMessageEventHandler(HandleLogMessage);\n mg.Options.StopOnLogMessage = true;\n mgProcess.Go().WaitOne();\n bool running = true;\n Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);\n while (running)\n {\n try\n {\n running =mgProcess.IsAlive;\n mgProcess.Go().WaitOne();\n }\n catch\n {\n running = false;\n }\n }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15394/"
] |
367,971 | <p>Is there a function, that clears last line in command prompt? I dont mean "cls" - it clears the whole sreen, I want to delete just the last line.</p>
<p>e.g. I am searching for a file in a folder and its subfolders and I want to print to cmd current folder - but I want to rewrite it, when the folder changes, not just append to the end. I know, this is just a banality, but I am interested how could be it done.</p>
| [
{
"answer_id": 367977,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 2,
"selected": false,
"text": "\"\\r\" print(\"\\rNew text in the line\");\n"
},
{
"answer_id": 368108,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "c:\\directory\\really_big_name_too_long_..._so_Ive_put_some_ellipses_in.txt\n"
},
{
"answer_id": 33849284,
"author": "CleverEagle",
"author_id": 5590315,
"author_profile": "https://Stackoverflow.com/users/5590315",
"pm_score": 1,
"selected": false,
"text": "(\necho (Previous Outputs)\n(This may happen as many times as needed)\n) >> C:\\file.txt\nset /P thing=\ncls\ntype C:\\file.txt\npause\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46289/"
] |
367,984 | <p>What C++ HTTP frameworks are available that will help in adding HTTP/SOAP serving support to an application?</p>
| [
{
"answer_id": 36845066,
"author": "Vinnie Falco",
"author_id": 150679,
"author_profile": "https://Stackoverflow.com/users/150679",
"pm_score": 2,
"selected": false,
"text": "#include <beast/http.hpp>\n#include <boost/asio.hpp>\n#include <iostream>\n#include <string>\n\nint main()\n{\n // Normal boost::asio setup\n std::string const host = \"boost.org\";\n boost::asio::io_service ios;\n boost::asio::ip::tcp::resolver r(ios);\n boost::asio::ip::tcp::socket sock(ios);\n boost::asio::connect(sock,\n r.resolve(boost::asio::ip::tcp::resolver::query{host, \"http\"}));\n\n using namespace beast::http;\n\n // Send HTTP request using beast\n request<empty_body> req({method_t::http_get, \"/\", 11});\n req.headers.replace(\"Host\", host + \":\" + std::to_string(sock.remote_endpoint().port()));\n req.headers.replace(\"User-Agent\", \"Beast\");\n write(sock, req);\n\n // Receive and print HTTP response using beast\n beast::streambuf sb;\n response<streambuf_body> resp;\n read(sock, sb, resp);\n std::cout << resp;\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/367984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
] |
368,001 | <p>I have a .NET assembly which I have exposed to COM via a tlb file, and an installer which registers the tlb. I have manually checked that the installer works correctly and that COM clients can access the library. So far, so good...</p>
<p>However, I am trying to put together some automated system tests which check that the installer is working correctly. As part of that I have automated the installation on a VM, and I now want to make some calls to the installed COM library to verify that it is working correctly. I originally thought about writing some tests in VB6, but I already have a large suite of tests written in C#, which reference the .NET assembly. I was hoping that I could change these to reference the .tlb, but I get an error when I try this within VS2008:</p>
<p>The ActiveX type library 'blah.tlb' was exported from a .NET assembly and cannot be added as a reference.</p>
<p>Is there any way I can fool VS2008 into allowing me to add this reference, perhaps by editing the tlb file? </p>
<p>Googling hasn't come up with any solutions. All I've found is a Microsoft Connect article stating that this is "By Design": <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=120882" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=120882</a></p>
| [
{
"answer_id": 5707462,
"author": "Warren",
"author_id": 479921,
"author_profile": "https://Stackoverflow.com/users/479921",
"pm_score": 5,
"selected": true,
"text": "using System;\nclass ComClass\n{\n public bool CallFunction(arg1, arg2)\n {\n Type ComType;\n object ComObject;\n\n ComType = Type.GetTypeFromProgID(\"Registered.ComClass\");\n // Create an instance of your COM Registered Object.\n ComObject = Activator.CreateInstance(ComType);\n\n object[] args = new object[2];\n args[0] = arg1;\n args[1] = arg2;\n\n // Call the Method and cast return to whatever it should be.\n return (bool)ComType.InvokeMember(\"MethodToCall\", BindingFlags.InvokeMethod, null, ComObject, args))\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32413/"
] |
368,003 | <p>I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would like to oder by received for files addressed to me, and sent for files sent by me. Would it perhaps be easier to use maildir files or such?</p>
<p>The emails currently exist in the format:</p>
<pre><code>From x@blah.com Fri Aug 12 09:34:09 2005
Message-ID: <42FBEE81.9090701@blah.com>
Date: Fri, 12 Aug 2005 09:34:09 +0900
From: me <x@blah.com>
User-Agent: Mozilla Thunderbird 1.0.6 (Windows/20050716)
X-Accept-Language: en-us, en
MIME-Version: 1.0
To: someone <someone@hotmail.com>
Subject: Re: (no subject)
References: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl>
In-Reply-To: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Status: RO
X-Status:
X-Keywords:
X-UID: 371
X-Evolution-Source: imap://x+blah.com@blah.com/
X-Evolution: 00000002-0010
Hey
the actual content of the email
someone wrote:
> lines of quotedtext
</code></pre>
<p>I am wondering if there is a way to use this information to easily reorganize the file, perhaps with perl or such.</p>
| [
{
"answer_id": 368067,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "#!/usr/bin/python2.5\nfrom email.utils import parsedate\nimport mailbox\n\ndef extract_date(email):\n date = email.get('Date')\n return parsedate(date)\n\nthe_mailbox = mailbox.mbox('/path/to/mbox')\nsorted_mails = sorted(the_mailbox, key=extract_date)\nthe_mailbox.update(enumerate(sorted_mails))\nthe_mailbox.flush()\n"
},
{
"answer_id": 2749746,
"author": "Denis Barmenkov",
"author_id": 116373,
"author_profile": "https://Stackoverflow.com/users/116373",
"pm_score": 2,
"selected": false,
"text": "From - Tue Apr 27 19:42:22 2010\n From - Sat May 01 2010 15:07:31 GMT+0400 (Russian Daylight Time)\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/368003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.