qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
359,359 | <p>I am in need of a case insensitive string enumeration type in my XML schema (.xsd) file. I can get case insensitive by doing the following.</p>
<pre><code><xs:simpleType name="setDigitalPointType">
<xs:restriction base="xs:string">
<xs:pattern value="[Oo][Nn]" />
<xs:pattern value="[Oo][Ff][Ff]" />
</xs:restriction>
</xs:simpleType>
</code></pre>
<p>The only problem is that I get no enumeration values. I will not get the nice intellesense when using Visual Studio to write my XML. The following will give me enumerations but it is case sensitive.</p>
<pre><code><xs:simpleType name="setDigitalPointType">
<xs:restriction base="xs:string">
<xs:enumeration value="on" />
<xs:enumeration value="off" />
</xs:restriction>
</xs:simpleType>
</code></pre>
<p>This will give me my enumerations but if I ever receive a value of "On", "ON", or "oN" it will fail verification.</p>
<p>I want enumeration of "on", "off" and allow entry of case insensitive versions.</p>
| [
{
"answer_id": 15445351,
"author": "Orvid King",
"author_id": 776797,
"author_profile": "https://Stackoverflow.com/users/776797",
"pm_score": 4,
"selected": false,
"text": "<xs:simpleType name=\"setDigitalPointType\">\n <xs:union>\n <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"on\" />\n <xs:enumeration value=\"off\" />\n </xs:restriction>\n </xs:simpleType>\n <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:pattern value=\"[Oo][Nn]\" />\n <xs:pattern value=\"[Oo][Ff][Ff]\" />\n </xs:restriction>\n </xs:simpleType>\n </xs:union>\n</xs:simpleType>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43976/"
] |
359,381 | <p>I'm preparing to send mass email to customers which is in html + images.
What are general rules to do make it display correctly in most popular mail clients?</p>
<p>EDIT:</p>
<p>Well it's for my customers - about few k clients.</p>
<p>My question is - how to code this email that it will display correctly in customer mailclient(thunderbird, outlook, gmail). What css tags can I use?</p>
| [
{
"answer_id": 359399,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<style> <link> style=\"\""
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33093/"
] |
359,393 | <p>I've got a list of links which have a click event attached to them, I need to get the ID from the child A link. So in the example below if I clicked the first list element I'd need google retuned. </p>
<p>I've tried <code>'$this a'</code> but can't quite work out the syntax.</p>
<pre><code>$("ul li").click(function(event){
$("input").val($(this).html());
});
</code></pre>
<pre><code><ul>
<li><a href="http://www.google.com" id="google">Google</a>
</ul>
</code></pre>
| [
{
"answer_id": 359407,
"author": "smoothdeveloper",
"author_id": 17049,
"author_profile": "https://Stackoverflow.com/users/17049",
"pm_score": 7,
"selected": true,
"text": "$(this).find('a:first').attr('id')\n"
},
{
"answer_id": 359500,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 2,
"selected": false,
"text": "children $(this).children('a').eq(0).attr('id');\n"
},
{
"answer_id": 359501,
"author": "Wayne Austin",
"author_id": 31109,
"author_profile": "https://Stackoverflow.com/users/31109",
"pm_score": 2,
"selected": false,
"text": "$('ul li').bind('click', getAnchorId);\n function getAnchorId() {\n var anchorId = $(this).children('a').attr('id');\n alert(anchorId);\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45350/"
] |
359,400 | <p>I want to get the path name and arguments of running processes using java code. Is there any solution?</p>
| [
{
"answer_id": 359437,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "TASKLIST.EXE Process p = Runtime.getRuntime().exec(\"tasklist.exe /fo csv /nh\");\n BufferedReader input = new BufferedReader\n (new InputStreamReader(p.getInputStream()));\n while ((line = input.readLine()) != null) {\n if (!line.trim().equals(\"\")) {\n // keep only the process name\n line = line.substring(1);\n processes.add(line.substring(0, line.indexOf(\"\"\")));\n }\n\n }\n tasklist /V"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,422 | <p>I have an ASP.Net web user control that contains a TextBox and a calendar from the Ajax Control Toolkit.</p>
<p>When I include this user control on my page I would like it to participate in input validation (there is a required filed validator set on the TextBox inside the UC), ie. when the page is validated the content of the UC should also be validated. So I had my UC implement the IValidator interface, which worked well except that I could not set the validation group on the user control. Apparently I'm supposed to inherit from BaseValidator to do that, but I can't since I'm already inheriting UserControl.</p>
<p>There's got to be a way to deal with this common scenario.</p>
| [
{
"answer_id": 359455,
"author": "Scott Ivey",
"author_id": 36297,
"author_profile": "https://Stackoverflow.com/users/36297",
"pm_score": 5,
"selected": true,
"text": "public string ValidationGroup\n{\n get\n {\n return MyRequiredFieldValidator.ValidationGroup;\n }\n set\n {\n MyRequiredFieldValidator.ValidationGroup = value;\n }\n}\n"
},
{
"answer_id": 359465,
"author": "Aleksandar",
"author_id": 29511,
"author_profile": "https://Stackoverflow.com/users/29511",
"pm_score": 2,
"selected": false,
"text": "[ValidationProperty(\"NameOfPropertyToBeValidated\")"
},
{
"answer_id": 6504850,
"author": "Sjoerd",
"author_id": 182971,
"author_profile": "https://Stackoverflow.com/users/182971",
"pm_score": 4,
"selected": false,
"text": "<asp:RequiredFieldValidator ControlToValidate=\"MyUserControl$ControlId\" runat=\"server\" />\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77004/"
] |
359,424 | <p>I have a <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> repository which contains a number of subdirectories. Now I have found that one of the subdirectories is unrelated to the other and should be detached to a separate repository.</p>
<p>How can I do this while keeping the history of the files within the subdirectory?</p>
<p>I guess I could make a clone and remove the unwanted parts of each clone, but I suppose this would give me the complete tree when checking out an older revision etc. This might be acceptable, but I would prefer to be able to pretend that the two repositories doesn't have a shared history.</p>
<p>Just to make it clear, I have the following structure:</p>
<pre><code>XYZ/
.git/
XY1/
ABC/
XY2/
</code></pre>
<p>But I would like this instead:</p>
<pre><code>XYZ/
.git/
XY1/
XY2/
ABC/
.git/
ABC/
</code></pre>
| [
{
"answer_id": 359759,
"author": "Paul",
"author_id": 23356,
"author_profile": "https://Stackoverflow.com/users/23356",
"pm_score": 11,
"selected": true,
"text": "git subtree git filter-branch git clone /XYZ /ABC\n cd /ABC\nfor i in branch1 br2 br3; do git branch -t $i origin/$i; done\ngit remote rm origin\n cd /ABC\nfor i in $(git branch -r | sed \"s/.*origin\\///\"); do git branch -t $i origin/$i; done\ngit remote rm origin\n WARNING: Ref 'refs/tags/v0.1' is unchanged git filter-branch git tag -l | xargs git tag -d --tag-name-filter cat --prune-empty git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC -- --all\n git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC HEAD\n git reset --hard\ngit for-each-ref --format=\"%(refname)\" refs/original/ | xargs -n 1 git update-ref -d\ngit reflog expire --expire=now --all\ngit gc --aggressive --prune=now\n git filter-branch -- --all all"
},
{
"answer_id": 955793,
"author": "pgs",
"author_id": 103421,
"author_profile": "https://Stackoverflow.com/users/103421",
"pm_score": 7,
"selected": false,
"text": "git filter-branch --tree-filter \"rm -rf ABC\" --prune-empty HEAD\n"
},
{
"answer_id": 1591174,
"author": "Josh Lee",
"author_id": 19750,
"author_profile": "https://Stackoverflow.com/users/19750",
"pm_score": 7,
"selected": false,
"text": "filter-branch git clone --no-hardlinks foo bar; cd bar\ngit filter-branch --subdirectory-filter subdir/you/want\n git remote rm origin\ngit update-ref -d refs/original/refs/heads/master\ngit reflog expire --expire=now --all\n git repack -ad\n"
},
{
"answer_id": 2495675,
"author": "D W",
"author_id": 255312,
"author_profile": "https://Stackoverflow.com/users/255312",
"pm_score": 4,
"selected": false,
"text": "git subtree"
},
{
"answer_id": 4039311,
"author": "cmcginty",
"author_id": 64313,
"author_profile": "https://Stackoverflow.com/users/64313",
"pm_score": 2,
"selected": false,
"text": "git filter-branch --index-filter \\\n\"git rm -r -f --cached --ignore-unmatch DIR\" --prune-empty \\\n--tag-name-filter cat -- --all\n"
},
{
"answer_id": 6295550,
"author": "Simon A. Eugster",
"author_id": 271961,
"author_profile": "https://Stackoverflow.com/users/271961",
"pm_score": 5,
"selected": false,
"text": "git clone --no-hardlinks file:///SOURCE /tmp/blubb\ncd blubb\ngit filter-branch --subdirectory-filter ./PATH_TO_EXTRACT --prune-empty --tag-name-filter cat -- --all\ngit clone file:///tmp/blubb/ /tmp/blooh\ncd /tmp/blooh\ngit reflog expire --expire=now --all\ngit repack -ad\ngit gc --prune=now\n !/bin/bash\n\nif (( $# < 3 ))\nthen\n echo \"Usage: $0 </path/to/repo/> <directory/to/extract/> <newName>\"\n echo\n echo \"Example: $0 /Projects/42.git first/answer/ firstAnswer\"\n exit 1\nfi\n\n\nclone=/tmp/${3}Clone\nnewN=/tmp/${3}\n\ngit clone --no-hardlinks file://$1 ${clone}\ncd ${clone}\n\ngit filter-branch --subdirectory-filter $2 --prune-empty --tag-name-filter cat -- --all\n\ngit clone file://${clone} ${newN}\ncd ${newN}\n\ngit reflog expire --expire=now --all\ngit repack -ad\ngit gc --prune=now\n"
},
{
"answer_id": 9182278,
"author": "James Lawruk",
"author_id": 88204,
"author_profile": "https://Stackoverflow.com/users/88204",
"pm_score": 2,
"selected": false,
"text": "C:\\dir1 C:\\dir1\\dir2\\dir3 dir3 MyTeam/mynewrepo $ cd c:/Dir1 $ git filter-branch --prune-empty --subdirectory-filter dir2/dir3 HEAD Ref 'refs/heads/master' was rewritten $ git remote add some_name git@github.com:MyTeam/mynewrepo.git git remote add origin etc remote origin already exists $ git push --progress some_name master"
},
{
"answer_id": 15710792,
"author": "grosser",
"author_id": 110333,
"author_profile": "https://Stackoverflow.com/users/110333",
"pm_score": 1,
"selected": false,
"text": "reduce-to-subfolder = !sh -c 'git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter cookbooks/unicorn HEAD && git reset --hard && git for-each-ref refs/original/ | cut -f 2 | xargs -n 1 git update-ref -d && git reflog expire --expire=now --all && git gc --aggressive --prune=now && git remote rm origin'\n"
},
{
"answer_id": 16854710,
"author": "Jay Allen",
"author_id": 255642,
"author_profile": "https://Stackoverflow.com/users/255642",
"pm_score": 2,
"selected": false,
"text": "dir/subdir/targetdir filter-branch filter-branch"
},
{
"answer_id": 17864475,
"author": "coolaj86",
"author_id": 151312,
"author_profile": "https://Stackoverflow.com/users/151312",
"pm_score": 11,
"selected": false,
"text": " cd <big-repo>\n git subtree split -P <name-of-folder> -b <name-of-new-branch>\n <name-of-folder> subproject subproject ./subproject/ <name-of-folder> path1\\path2\\subproject path1/path2/subproject mkdir ~/<new-repo> && cd ~/<new-repo>\n git init\n git pull </path/to/big-repo> <name-of-new-branch>\n git remote add origin <git@github.com:user/new-repo.git>\n git push -u origin master\n <big-repo> git rm -rf <name-of-folder>\n .git <meta-named-things> tree ~/node-browser-compat\n\nnode-browser-compat\n├── ArrayBuffer\n├── Audio\n├── Blob\n├── FormData\n├── atob\n├── btoa\n├── location\n└── navigator\n btoa cd ~/node-browser-compat/\ngit subtree split -P btoa -b btoa-only\n btoa-only btoa mkdir ~/btoa/ && cd ~/btoa/\ngit init\ngit pull ~/node-browser-compat btoa-only\n origin git remote add origin git@github.com:node-browser-compat/btoa.git\ngit push -u origin master\n README.md .gitignore LICENSE git pull origin master\ngit push origin master\n git rm -rf btoa\n brew install git\n sudo apt-get update\nsudo apt-get install git\ngit --version\n sudo add-apt-repository ppa:git-core/ppa\nsudo apt-get update\nsudo apt-get install git\n sudo chmod +x /usr/share/doc/git/contrib/subtree/git-subtree.sh\nsudo ln -s \\\n/usr/share/doc/git/contrib/subtree/git-subtree.sh \\\n/usr/lib/git-core/git-subtree\n git filter-branch --prune-empty --tree-filter 'rm -rf <name-of-folder>' HEAD\n git log -- <name-of-folder> # should show nothing\n git pull git push .git rm -rf .git/refs/original/ && \\\ngit reflog expire --all && \\\ngit gc --aggressive --prune=now\n\ngit reflog expire --all --expire-unreachable=0\ngit repack -A -d\ngit prune\n"
},
{
"answer_id": 25406990,
"author": "jeremyjjbrown",
"author_id": 914763,
"author_profile": "https://Stackoverflow.com/users/914763",
"pm_score": 5,
"selected": false,
"text": "git filter-branch --prune-empty --subdirectory-filter <YOUR_SUBDIR_TO_KEEP> master\ngit push <MY_NEW_REMOTE_URL> -f .\n"
},
{
"answer_id": 26888022,
"author": "Oleksandr Shapovalov",
"author_id": 1980129,
"author_profile": "https://Stackoverflow.com/users/1980129",
"pm_score": 3,
"selected": false,
"text": "git filter-branch --prune-empty --subdirectory-filter FOLDER_NAME [first_branch] [another_branch] git filter-branch"
},
{
"answer_id": 28451972,
"author": "AndrewD",
"author_id": 3306354,
"author_profile": "https://Stackoverflow.com/users/3306354",
"pm_score": 2,
"selected": false,
"text": "git splits \n #change into your repo's directory\n cd /path/to/repo\n #checkout the branch\n git checkout XYZ\n #split multiple directories into new branch XYZ\n git splits -b XYZ XY1 XY2\n xyz git@github.com:simpliwp/xyz.git \n #add a new remote origin for the empty repo so we can push to the empty repo on GitHub\n git remote add origin_xyz git@github.com:simpliwp/xyz.git\n #push the branch to the empty repo's master branch\n git push origin_xyz XYZ:master\n \n #change current directory out of the old repo\n cd /path/to/where/you/want/the/new/local/repo\n #clone the remote repo you just pushed to \n git clone git@github.com:simpliwp/xyz.git\n"
},
{
"answer_id": 31859803,
"author": "Anthony O.",
"author_id": 535203,
"author_profile": "https://Stackoverflow.com/users/535203",
"pm_score": 4,
"selected": false,
"text": "sub1 sub2 pushd <big-repo>\ngit filter-branch --tree-filter \"mkdir <name-of-folder>; mv <sub1> <sub2> <name-of-folder>/\" HEAD\ngit subtree split -P <name-of-folder> -b <name-of-new-branch>\npopd\n <name-of-folder> subproject subproject ./subproject/ <name-of-folder> path1\\path2\\subproject path1/path2/subproject mv move git filter-branch... mkdir <new-repo>\npushd <new-repo>\n\ngit init\ngit pull </path/to/big-repo> <name-of-new-branch>\n git remote add origin <git@github.com:my-user/new-repo.git>\ngit push origin -u master\n popd # get out of <new-repo>\npushd <big-repo>\n\ngit rm -rf <name-of-folder>\n .git"
},
{
"answer_id": 34624761,
"author": "vangorra",
"author_id": 1267536,
"author_profile": "https://Stackoverflow.com/users/1267536",
"pm_score": 2,
"selected": false,
"text": "./git_split.sh <src_repo> <src_branch> <relative_dir_path> <dest_repo>\n src_repo - The source repo to pull from.\n src_branch - The branch of the source repo to pull from. (usually master)\n relative_dir_path - Relative path of the directory in the source repo to split.\n dest_repo - The repo to push to.\n"
},
{
"answer_id": 39580074,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 3,
"selected": false,
"text": "git filter-branch --subdirectory-filter ABC/\n /move_this_dir # did some work here, then renamed it to\n\nABC/\n /move_this_dir_renamed\n git branch -a git checkout --track origin/branchABC cp -r oldmultimod simple cd simple git rm otherModule1 other2 other3 git mv moduleSubdir1/* . rmdir moduleSubdir1 git status git remote set-url origin http://mygithost:8080/git/our-splitted-module-repo git remote -v git push git checkout branch2"
},
{
"answer_id": 45983384,
"author": "Stevoisiak",
"author_id": 3357935,
"author_profile": "https://Stackoverflow.com/users/3357935",
"pm_score": 3,
"selected": false,
"text": "git clone OLD-REPOSITORY-FOLDER NEW-REPOSITORY-FOLDER\n cd REPOSITORY-NAME\n git filter-branch FOLDER-NAME / BRANCH-NAME master gh-pages git filter-branch --prune-empty --subdirectory-filter FOLDER-NAME BRANCH-NAME \n# Filter the specified branch in your directory and remove empty commits\nRewrite 48dc599c80e20527ed902928085e7861e6b3cbe6 (89/89)\nRef 'refs/heads/BRANCH-NAME' was rewritten\n"
},
{
"answer_id": 54123678,
"author": "Barath Ravichander",
"author_id": 6743632,
"author_profile": "https://Stackoverflow.com/users/6743632",
"pm_score": 1,
"selected": false,
"text": "git filter-branch --prune-empty --subdirectory-filter FOLDER-NAME BRANCH-NAME BRANCH-NAME"
},
{
"answer_id": 55399619,
"author": "Vlad Troyan",
"author_id": 6258088,
"author_profile": "https://Stackoverflow.com/users/6258088",
"pm_score": 0,
"selected": false,
"text": "git clone git@git.thehost.io:testrepo/test.git\n cd test/\n rm -r ABC/\ngit add .\nenter code here\ngit commit -m 'Remove ABC'\n cd ..\njava -jar bfg.jar --delete-folders \"{ABC}\" test\ncd test/\ngit reflog expire --expire=now --all && git gc --prune=now --aggressive\n java -jar bfg.jar --delete-folders \"{ABC1,ABC2}\" metric.git\n git log --diff-filter=D --summary | grep delete\n remote add origin git@github.com:username/new_repo\ngit push -u origin master\n"
},
{
"answer_id": 58983975,
"author": "lpearson",
"author_id": 1541457,
"author_profile": "https://Stackoverflow.com/users/1541457",
"pm_score": 5,
"selected": false,
"text": "git filter-branch git 2.22+ XYZ # create local clone of original repo in directory XYZ\ntmp $ git clone git@github.com:user/original.git XYZ\n\n# switch to working in XYZ\ntmp $ cd XYZ\n\n# keep subdirectories XY1 and XY2 (dropping ABC)\nXYZ $ git filter-repo --path XY1 --path XY2\n\n# note: original remote origin was dropped\n# (protecting against accidental pushes overwriting original repo data)\n\n# XYZ $ ls -1\n# XY1\n# XY2\n\n# XYZ $ git log --oneline\n# last commit modifying ./XY1 or ./XY2\n# first commit modifying ./XY1 or ./XY2\n\n# point at new hosted, dedicated repo\nXYZ $ git remote add origin git@github.com:user/XYZ.git\n\n# push (and track) remote master\nXYZ $ git push -u origin master\n filter-repo git mv dir-to-rename --path-rename 5 hours ago last year git filter-repo --path XY1 --path XY2 --path inconsistent\ngit mv inconsistent XY3 # which updates last modification time\n git filter-repo --path XY1 --path XY2 --path inconsistent --path-rename inconsistent:XY3\n git filter-repo --subdirectory-filter dir-matching-new-repo-name --path git reset commit-before-subdir-move --hard clone --force filter-repo git clone ...\ngit reset HEAD~7 --hard # roll back before mistake\ngit filter-repo ... --force # tell filter-repo the alterations are expected\n git $(git --exec-path) ln -s ~/github/newren/git-filter-repo/git-filter-repo $(git --exec-path)\n"
},
{
"answer_id": 68327597,
"author": "infiniteLearner",
"author_id": 3649496,
"author_profile": "https://Stackoverflow.com/users/3649496",
"pm_score": 0,
"selected": false,
"text": "$ cd path/to/repository\n$ git subtree split -P my-folder -b my-folder\nCreated branch 'my-folder'\naecbdc3c8fe2932529658f5ed40d95c135352eff\n $ cd my-folder\n$ git init\nInitialized empty Git repository in /Users/adamwest/Projects/learngit/shop/my-folder/.git/\n$ git add .\n$ git commit -m \"initial commit\"\n[master (root-commit) 192c10b] initial commit\n 1 file changed, 0 insertions(+), 0 deletions(-)\n create mode 100644 file\n $ git remote add origin git@github.com:robertlyall/my-folder.git\n$ git push origin -u master\nEnumerating objects: 3, done.\nCounting objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 199 bytes | 199.00 KiB/s, done.\nTotal 3 (delta 0), reused 0 (delta 0)\nTo github.com:robertlyall/my-folder.git\n * [new branch] master -> master\nBranch 'master' set up to track remote branch 'master' from 'origin'.\n $ cd ../\n$ git rm -rf my-folder\nrm 'my-folder/file'\n$ git commit -m \"Remove old folder\"\n[master 56aedbe] remove old folder\n 1 file changed, 0 insertions(+), 0 deletions(-)\n delete mode 100644 my-folder/file\n$ git push\nEnumerating objects: 3, done.\nCounting objects: 100% (3/3), done.\nDelta compression using up to 4 threads\nCompressing objects: 100% (2/2), done.\nWriting objects: 100% (2/2), 217 bytes | 217.00 KiB/s, done.\nTotal 2 (delta 1), reused 0 (delta 0)\nremote: Resolving deltas: 100% (1/1), completed with 1 local object.\nTo github.com:robertlyall/shop.git\n 74dd8b3..56aedbe master -> master\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23896/"
] |
359,426 | <p>Does anyone know a simple load balance algorithm (formula) that relates users connected, cpu load, network load and memory usage?
This will be used to compare various servers and assign to a new user the best at the moment.
Thank You.</p>
| [
{
"answer_id": 359581,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 2,
"selected": false,
"text": "mod_proxy mod_proxy_balancer mod_proxy_balancer"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,434 | <p>I am training in web developement and am learning about <strong>JSP</strong> & <strong>Servlets</strong>. I have some knowledge of <code>HttpSession</code> - I have used it in some of my sample projects.</p>
<p>In browsers I have seen the option to "delete cookies". If I delete the cookies it deletes the <code>HttpSession</code> also.</p>
<p>Are cookies and session the same? What are the differences between them?</p>
| [
{
"answer_id": 359482,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 8,
"selected": false,
"text": "name=bob; password=asdfas www.myserver.com/myApp.jsp www.myserver.com/myApp.jsp?sessionID=asdf www.myserver.com/asdf/myApp.jsp"
},
{
"answer_id": 29387911,
"author": "Elangovan",
"author_id": 2614459,
"author_profile": "https://Stackoverflow.com/users/2614459",
"pm_score": 0,
"selected": false,
"text": "<html> \n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44848/"
] |
359,436 | <p>Should be simple and quick: I want a C# equivalent to the following Java code:</p>
<pre><code>orig: for(String a : foo) {
for (String b : bar) {
if (b.equals("buzz")) {
continue orig;
}
}
// other code comes here...
}
</code></pre>
<hr>
<p><strong><em>Edit</em></strong>:
OK it seems there is no such equivalent (hey - Jon Skeet himself said there isn't, that settles it ;)). So the "solution" for me (in its Java equivalent) is:</p>
<pre><code>for(String a : foo) {
bool foundBuzz = false;
for (String b : bar) {
if (b.equals("buzz")) {
foundBuzz = true;
break;
}
}
if (foundBuzz) {
continue;
}
// other code comes here...
}
</code></pre>
| [
{
"answer_id": 359449,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "using System;\n\npublic class Test\n{\n static void Main()\n {\n for (int i=0; i < 5; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n Console.WriteLine(\"i={0} j={1}\", i, j);\n if (j == i + 2)\n {\n goto end_of_loop; \n }\n }\n Console.WriteLine(\"After inner loop\");\n end_of_loop: {}\n }\n }\n}\n"
},
{
"answer_id": 359464,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "while for exit break;"
},
{
"answer_id": 359513,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 0,
"selected": false,
"text": "foreach(int i in new int[] {1,2,3,5,6,7})\n{\n if(i % 2 == 0)\n continue;\n else\n Console.WriteLine(i.ToString()); \n}\n foreach(int i in new int[] {1,2,3,5,6,7})\n{\n if(i % 2 == 0)\n break;\n else\n Console.WriteLine(i.ToString()); \n}\n"
},
{
"answer_id": 359518,
"author": "Sergio",
"author_id": 32037,
"author_profile": "https://Stackoverflow.com/users/32037",
"pm_score": 0,
"selected": false,
"text": "for(int i=0; i< foo.Length -1 ; i++) {\n for (int j=0; j< bar.Length -1; j++) {\n if (condition) {\n break;\n }\n if(j != bar.Length -1)\n continue;\n /*The rest of the code that will not run if the previous loop doesn't go all the way*/\n }\n}\n"
},
{
"answer_id": 5006587,
"author": "GX Cristian",
"author_id": 618189,
"author_profile": "https://Stackoverflow.com/users/618189",
"pm_score": 4,
"selected": false,
"text": "void mainFunc(string[] foo, string[] bar)\n{\n foreach (string a in foo)\n if (hasBuzz(bar))\n continue;\n // other code comes here...\n}\n\nbool hasBuzz(string[] bar)\n{\n foreach (string b in bar)\n if (b.equals(\"buzz\"))\n return true;\n return false;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
359,438 | <p>Does anyone know of any optimization packages out there for R (similar to NUOPT for S+)?</p>
| [
{
"answer_id": 1190707,
"author": "gappy",
"author_id": 143813,
"author_profile": "https://Stackoverflow.com/users/143813",
"pm_score": 4,
"selected": false,
"text": "optim()"
},
{
"answer_id": 14179446,
"author": "dwstu",
"author_id": 1764155,
"author_profile": "https://Stackoverflow.com/users/1764155",
"pm_score": 3,
"selected": false,
"text": "# Maximize \n# x1 + 9 x2 + x3 \n# Subject to: \n# x1 + 2 x2 + 3 x3 <= 9\n# 3 x1 + 2 x2 + 2 x3 <= 15\nf.obj <- c(1, 9, 3)\nf.con <- matrix(c(1, 2, 3, 3, 2, 2), nrow = 2, byrow = TRUE)\nf.dir <- c(\"<=\", \"<=\")\nf.rhs <- c(9, 15)\n\nlp(\"max\", f.obj, f.con, f.dir, f.rhs)\nlp(\"max\", f.obj, f.con, f.dir, f.rhs)$solution\n"
},
{
"answer_id": 14179534,
"author": "dwstu",
"author_id": 1764155,
"author_profile": "https://Stackoverflow.com/users/1764155",
"pm_score": 3,
"selected": false,
"text": "## Simple linear program.\n## maximize: 2 x_1 + 4 x_2 + 3 x_3\n## subject to: 3 x_1 + 4 x_2 + 2 x_3 <= 60\n## 2 x_1 + x_2 + x_3 <= 40\n## x_1 + 3 x_2 + 2 x_3 <= 80\n## x_1, x_2, x_3 are non-negative real numbers\n\nobj <- c(2, 4, 3)\nmat <- matrix(c(3, 2, 1, 4, 1, 3, 2, 2, 2), nrow = 3)\ndir <- c(\"<=\", \"<=\", \"<=\")\nrhs <- c(60, 40, 80)\nmax <- TRUE\n\nRglpk_solve_LP(obj, mat, dir, rhs, max = max)\n $status $optimum\n[1] 76.66667\n\n$solution\n[1] 0.000000 6.666667 16.666667\n\n$status\n[1] 0\n"
},
{
"answer_id": 69820207,
"author": "Shibaprasadb",
"author_id": 15851978,
"author_profile": "https://Stackoverflow.com/users/15851978",
"pm_score": 2,
"selected": false,
"text": "binary continuous integer library(tidyverse)\nlibrary(ompr)\nlibrary(ompr.roi)\n\n\nmodel <- MIPModel() %>%\n add_variable(x1, type = \"integer\") %>%\n add_variable(x2, type = \"integer\") %>%\n set_bounds(x1, lb = 0) %>%\n set_bounds(x2, lb = 0) %>%\n set_objective(x1 - x2, \"max\") %>%\n add_constraint(x1 + 2*x2 <= 150) %>%\n add_constraint(x1 >= 30) %>%\n add_constraint(x2 >= 40)\n glpk library(ROI.plugin.glpk)\nresult <- solve_model(model, with_ROI(solver = \"glpk\", verbose = TRUE))\n\nget_solution(result, x1)\nget_solution(result, x2)\n symphony gap_limit library(ROI.plugin.symphony)\nresult <- solve_model(model, with_ROI(solver = \"symphony\",\n verbosity=-1, gap_limit=1.5))\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2173/"
] |
359,439 | <p>I want to use HTTP GET and POST commands to retrieve URLs from a website and parse the HTML. How do I do this?</p>
| [
{
"answer_id": 360291,
"author": "Rob Hruska",
"author_id": 29995,
"author_profile": "https://Stackoverflow.com/users/29995",
"pm_score": 5,
"selected": true,
"text": "URL url = new URL(\"http://example.com\");\nHttpURLConnection connection = (HttpURLConnection)url.openConnection();\nconnection.setRequestMethod(\"GET\");\nconnection.connect();\n\nInputStream stream = connection.getInputStream();\n// read the contents using an InputStreamReader\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16616/"
] |
359,459 | <p>Given the schema:</p>
<pre>
MACHINE_TYPE { machine_type }
MACHINE { machine, machine_type }
SORT_PLAN { sort_plan, machine_type }
SCHEDULE { day_of_week, machine, sort_plan }
</pre>
<p>and the business rule:</p>
<blockquote>
<p>A sort plan can be assigned to any
machine of the same machine_type.</p>
</blockquote>
<p>How do I enforce that, in SCHEDULE, the tuples referenced by <em>machine</em> and <em>sort_plan</em> have the same <em>machine_type</em>?</p>
<p>The schema can be changed, if necessary.</p>
| [
{
"answer_id": 359508,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": true,
"text": "MACHINE_TYPE { machine_type }\nMACHINE { machine, machine_type }\nSORT_PLAN { sort_plan}\nMACHINE_SORTPLAN {machine, sort_plan }\nSCHEDULE { day_of_week, machine_Sortplan }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21294/"
] |
359,467 | <p>I have a question similar to the one here: <a href="https://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure#341759">Event handlers inside a Javascript loop - need a closure?</a> but I'm using jQuery and the solution given seems to fire the event when it's bound rather than on click.</p>
<p>Here's my code:</p>
<pre><code>for(var i in DisplayGlobals.Indicators)
{
var div = d.createElement("div");
div.style.width = "100%";
td.appendChild(div);
for(var j = 0;j<3;j++)
{
var test = j;
if(DisplayGlobals.Indicators[i][j].length > 0)
{
var img = d.createElement("img");
jQuery(img).attr({
src : DisplayGlobals.Indicators[i][j],
alt : i,
className: "IndicatorImage"
}).click(
function(indGroup,indValue){
jQuery(".IndicatorImage").removeClass("active");
_this.Indicator.TrueImage = DisplayGlobals.Indicators[indGroup][indValue];
_this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial["BlankSmall"];
jQuery(this).addClass("active");
}(i,j)
);
div.appendChild(img);
}
}
}
</code></pre>
<p>I've tried a couple of different ways without success...</p>
<p>The original problem was that _this.Indicator.TrueImage was always the last value because I was using the loop counters rather than parameters to choose the right image.</p>
| [
{
"answer_id": 359505,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 5,
"selected": true,
"text": ".click(\n function(indGroup,indValue)\n {\n return function()\n {\n jQuery(\".IndicatorImage\").removeClass(\"active\");\n _this.Indicator.TrueImage = DisplayGlobals.Indicators[indGroup][indValue];\n _this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial[\"BlankSmall\"];\n jQuery(this).addClass(\"active\"); \n }\n }(i,j);\n);\n"
},
{
"answer_id": 3989988,
"author": "Nikita Rybak",
"author_id": 330565,
"author_profile": "https://Stackoverflow.com/users/330565",
"pm_score": 4,
"selected": false,
"text": "eventData .click({indGroup: i, indValue : j}, function(event) {\n alert(event.data.indGroup);\n alert(event.data.indValue);\n ...\n});\n"
},
{
"answer_id": 5446502,
"author": "Dave Oleksy",
"author_id": 308504,
"author_profile": "https://Stackoverflow.com/users/308504",
"pm_score": 3,
"selected": false,
"text": ".bind('click', {indGroup: i, indValue : j}, function(event) {\n alert(event.data.indGroup);\n alert(event.data.indValue);\n ...\n});\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950/"
] |
359,472 | <p><strong>How can I verify a Google authentication access token?</strong></p>
<p><strong>I need to somehow query Google and ask: Is [given access token] valid for the [example@example.com] Google account?</strong></p>
<h2>Short version</h2>
<p>It's clear how an access token supplied through the <a href="https://code.google.com/apis/accounts/docs/OAuth.html" rel="noreferrer">Google Authentication Api :: OAuth Authentication for Web Applications</a> can be used to then request data from a range of Google services. It is not clear how to check if a given access token is valid for a given Google account. I'd like to know how.</p>
<h2>Long version</h2>
<p>I'm developing an API that uses token-based authentication. A token will be returned upon provision of a valid username+password or upon provision of a third-party token from any one of <i>N</i> verifiable services.</p>
<p>One of the third-party services will be Google, allowing a user to authenticate against my service using their Google account. This will later be extended to include Yahoo accounts, trusted OpenID providers and so on.</p>
<p><strong>Schematic example of Google-based access:</strong></p>
<p><img src="https://webignition.net/images/figures/auth_figure002.png" alt="alt text" /></p>
<p>The 'API' entity is under my full control. The 'public interface' entity is any web- or desktop-based app. Some public interfaces are under my control, others will not be and others still I may never even know about.</p>
<p>Therefore I cannot trust the token supplied to the API in step 3. This will be supplied along with the corresponding Google account email address.</p>
<p>I need to somehow query Google and ask: <em>Is this access token valid for example@example.com</em>?</p>
<p>In this case, example@example.com is the Google account unique identifier - the email address someone uses to log in to their Google account. This cannot be assumed to be a Gmail address - someone can have a Google account without having a Gmail account.</p>
<p>The Google documentation clearly states how, with an access token, data can be retrieved from a number of Google services. Nothing seems to state how you can check if a given access token is valid in the first place.</p>
<p><strong>Update</strong>
The token is valid for N Google services. I can't try a token against a Google service as means of verifying it as I won't know which subset of all Google's services a given user actually uses.</p>
<p>Furthermore, I'll never be using the Google authentication access token to access any Google services, merely as a means of verifying a supposed Google user actually is who they say they are. If there is another way of doing this I'm happy to try.</p>
| [
{
"answer_id": 10498732,
"author": "ahmed",
"author_id": 855406,
"author_profile": "https://Stackoverflow.com/users/855406",
"pm_score": 4,
"selected": false,
"text": "function authenticate_google_OAuthtoken($user_id)\n{\n $access_token = google_get_user_token($user_id); // get existing token from DB\n $redirecturl = $Google_Permissions->redirecturl;\n $client_id = $Google_Permissions->client_id;\n $client_secret = $Google_Permissions->client_secret;\n $redirect_uri = $Google_Permissions->redirect_uri;\n $max_results = $Google_Permissions->max_results;\n\n $url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$access_token;\n $response_contacts = curl_get_responce_contents($url);\n $response = (json_decode($response_contacts));\n\n if(isset($response->issued_to))\n {\n return true;\n }\n else if(isset($response->error))\n {\n return false;\n }\n}\n"
},
{
"answer_id": 24646356,
"author": "Vinoj John Hosan",
"author_id": 1587156,
"author_profile": "https://Stackoverflow.com/users/1587156",
"pm_score": 7,
"selected": false,
"text": "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken\n {\n \"issued_to\": \"xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\",\n \"audience\": \"xxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\",\n \"user_id\": \"xxxxxxxxxxxxxxxxxxxxxxx\",\n \"scope\": \"https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com\",\n \"expires_in\": 3340,\n \"access_type\": \"offline\"\n }\n https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123\n {\n // These six fields are included in all Google ID Tokens.\n \"iss\": \"https://accounts.google.com\",\n \"sub\": \"110169484474386276334\",\n \"azp\": \"1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com\",\n \"aud\": \"1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com\",\n \"iat\": \"1433978353\",\n \"exp\": \"1433981953\",\n\n // These seven fields are only included when the user has granted the \"profile\" and\n // \"email\" OAuth scopes to the application.\n \"email\": \"testuser@gmail.com\",\n \"email_verified\": \"true\",\n \"name\" : \"Test User\",\n \"picture\": \"https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg\",\n \"given_name\": \"Test\",\n \"family_name\": \"User\",\n \"locale\": \"en\"\n}\n"
},
{
"answer_id": 31374878,
"author": "mpen",
"author_id": 65387,
"author_profile": "https://Stackoverflow.com/users/65387",
"pm_score": 1,
"selected": false,
"text": "/**\n * @param string $accessToken JSON-encoded access token as returned by \\Google_Client->getAccessToken() or raw access token\n * @return array|false False if token is invalid or array in the form\n * \n * array (\n * 'issued_to' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',\n * 'audience' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',\n * 'scope' => 'https://www.googleapis.com/auth/calendar',\n * 'expires_in' => 3350,\n * 'access_type' => 'offline',\n * )\n */\npublic static function tokenInfo($accessToken) {\n if(!strlen($accessToken)) {\n return false;\n }\n\n if($accessToken[0] === '{') {\n $accessToken = json_decode($accessToken)->access_token;\n }\n\n $guzzle = new \\GuzzleHttp\\Client();\n\n try {\n $resp = $guzzle->get('https://www.googleapis.com/oauth2/v1/tokeninfo', [\n 'query' => ['access_token' => $accessToken],\n ]);\n } catch(ClientException $ex) {\n return false;\n }\n\n return $resp->json();\n}\n"
},
{
"answer_id": 31597027,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 3,
"selected": false,
"text": "access_token id_token"
},
{
"answer_id": 44192619,
"author": "Nick Tsai",
"author_id": 4767939,
"author_profile": "https://Stackoverflow.com/users/4767939",
"pm_score": 5,
"selected": false,
"text": "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access_token>\n OAUTH 2.0 ENDPOINTS"
},
{
"answer_id": 66957524,
"author": "Steev James",
"author_id": 7866757,
"author_profile": "https://Stackoverflow.com/users/7866757",
"pm_score": 4,
"selected": false,
"text": "https://www.googleapis.com/oauth2/v3/userinfo?access_token=<access token>\n https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access token>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5343/"
] |
359,492 | <p>Well I am querying my DB, a table called bookBilling, to get a value under the column of billingID. </p>
<p>In my first query I get the customer ID from a table based on what value the cookie holds.
In my second query I take that custID value and am looking to get the billingID associated with it.</p>
<pre><code>query = "SELECT custID FROM bookSession WHERE session='"&theCookie&"'"
'--Connect to DB'
Set objConn = ConnectDB()
'--Query to DB'
Set objRS = objConn.Execute(query)
custID = objRS.Fields("custID")
query = "SELECT billingID FROM bookBilling WHERE custID="&custID&""
objConn.Execute(query)
</code></pre>
<p>Here is where it becomes an issue. I tried using this to obtain the value:</p>
<pre><code>billingID = objRS.Fields("billingID")
</code></pre>
<p>When that didn't work I printed the query to my browser to make sure it worked and it came back good, I checked it in SQL Server Management Studio to make sure. After that I decided to play with it a bit and found that using "0" as the reference works since it is the first item in my table. </p>
<pre><code>billingID = objRS.Fields(0)
</code></pre>
<p>So that worked, I know my table column header is correct I have looked at it and used it in other queries before. Does anyone know why this might happen? Is it a result of not clearing my connection or closing it afterward?</p>
<p>Thanks</p>
| [
{
"answer_id": 359537,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "SELECT billingID\nFROM bookBilling bb\nINNER JOIN bookSession bs ON bs.custID=bb.custID\nWHERE bs.session= @theCookie\n objConn.Execute(query)\n objRS.Fields(0) custID"
},
{
"answer_id": 359611,
"author": "Kablam",
"author_id": 42389,
"author_profile": "https://Stackoverflow.com/users/42389",
"pm_score": 0,
"selected": false,
"text": "query = \"SELECT billingID FROM bookBilling WHERE custID=\"&custID&\"\"\nobjConn.Execute(query)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27620/"
] |
359,494 | <p>I'm using <a href="http://en.wikipedia.org/wiki/JSLint" rel="noreferrer">JSLint</a> to go through JavaScript, and it's returning many suggestions to replace <code>==</code> (two equals signs) with <code>===</code> (three equals signs) when doing things like comparing <code>idSele_UNVEHtype.value.length == 0</code> inside of an <code>if</code> statement.</p>
<p>Is there a performance benefit to replacing <code>==</code> with <code>===</code>? </p>
<p>Any performance improvement would be welcomed as many comparison operators exist.</p>
<p>If no type conversion takes place, would there be a performance gain over <code>==</code>?</p>
| [
{
"answer_id": 359509,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 14,
"selected": true,
"text": "=== == == === === false === !== == != === true !== false '' == '0' // false\n0 == '' // true\n0 == '0' // true\n\nfalse == 'false' // false\nfalse == '0' // true\n\nfalse == undefined // false\nfalse == null // false\nnull == undefined // true\n\n' \\t\\r\\n ' == 0 // true\n === !== false === == === var a = [1,2,3];\nvar b = [1,2,3];\n\nvar c = { x: 1, y: 2 };\nvar d = { x: 1, y: 2 };\n\nvar e = \"text\";\nvar f = \"te\" + \"xt\";\n\na == b // false\na === b // false\n\nc == d // false\nc === d // false\n\ne == f // true\ne === f // true\n toString valueOf String \"abc\" == new String(\"abc\") // true\n\"abc\" === new String(\"abc\") // false\n == true === false String"
},
{
"answer_id": 359547,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 10,
"selected": false,
"text": "== true == 1; //true, because 'true' is converted to 1 and then compared\n\"2\" == 2; //true, because \"2\" is converted to 2 and then compared\n === true === 1; //false\n\"2\" === 2; //false\n == ==="
},
{
"answer_id": 359629,
"author": "Doctor Jones",
"author_id": 39277,
"author_profile": "https://Stackoverflow.com/users/39277",
"pm_score": 7,
"selected": false,
"text": "var a = 1;\nvar b = \"1\";\n\nif (a == b) //evaluates to true as a and b are both 1\n{\n alert(\"a == b\");\n}\n\nif (a === b) //evaluates to false as a is not the same type as b\n{\n alert(\"a === b\");\n}\n"
},
{
"answer_id": 371472,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 6,
"selected": false,
"text": "('\\t\\r\\n' == 0)"
},
{
"answer_id": 392748,
"author": "Simon Scarfe",
"author_id": 39353,
"author_profile": "https://Stackoverflow.com/users/39353",
"pm_score": 7,
"selected": false,
"text": "console.time(\"testEquality\");\nvar n = 0;\nwhile (true) {\n n++;\n if (n == 100000)\n break;\n}\nconsole.timeEnd(\"testEquality\"); console.time(\"testTypeEquality\");\nvar n = 0;\nwhile (true) {\n n++;\n if (n === 100000)\n break;\n}\nconsole.timeEnd(\"testTypeEquality\"); ==: 115.2\n===: 114.4\n ==="
},
{
"answer_id": 397583,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 5,
"selected": false,
"text": "var x = 0;\nvar isTrue = x == null;\nvar isFalse = x === null;\n CString x;\ndelete x;\n"
},
{
"answer_id": 957602,
"author": "Philippe Leybaert",
"author_id": 113570,
"author_profile": "https://Stackoverflow.com/users/113570",
"pm_score": 9,
"selected": false,
"text": "=== var a = [1,2,3];\nvar b = [1,2,3];\nvar c = a;\n\nvar ab_eq = (a === b); // false (even though a and b are the same type)\nvar ac_eq = (a === c); // true\n var a = { x: 1, y: 2 };\nvar b = { x: 1, y: 2 };\nvar c = a;\n\nvar ab_eq = (a === b); // false (even though a and b are the same type)\nvar ac_eq = (a === c); // true\n var a = { };\nvar b = { };\nvar c = a;\n\nvar ab_eq = (a === b); // false (even though a and b are the same type)\nvar ac_eq = (a === c); // true\n a === b a b a === b a b a === b a b var a = \"12\" + \"3\";\nvar b = \"123\";\n\nalert(a === b); // returns true, because strings behave like value types\n var a = new String(\"123\");\nvar b = \"123\";\n\nalert(a === b); // returns false !! (but they are equal and of the same type)\n a Object b string String Object"
},
{
"answer_id": 2818945,
"author": "vsync",
"author_id": 104380,
"author_profile": "https://Stackoverflow.com/users/104380",
"pm_score": 6,
"selected": false,
"text": "=== '1' === 1 // will return \"false\" because `string` is not a `number`\n 0 == '' // will be \"true\", but it's very common to want this check to be \"false\"\n null == undefined // returns \"true\", but in most cases a distinction is necessary\n undefined null 0 \"\""
},
{
"answer_id": 2818947,
"author": "Dimitar",
"author_id": 236521,
"author_profile": "https://Stackoverflow.com/users/236521",
"pm_score": 7,
"selected": false,
"text": "4 == \"4\" // will return true\n 4 === \"4\" // will return false \n"
},
{
"answer_id": 2818955,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 6,
"selected": false,
"text": "0==false // true,although they are different types\n\n0===false // false,as they are different types\n\n2=='2' //true,different types,one is string and another is integer but \n javaScript convert 2 to string by using == operator \n\n2==='2' //false because by using === operator ,javaScript do not convert \n integer to string \n\n2===2 //true because both have same value and same types \n"
},
{
"answer_id": 2818957,
"author": "Paul Butcher",
"author_id": 150882,
"author_profile": "https://Stackoverflow.com/users/150882",
"pm_score": 5,
"selected": false,
"text": "=== true"
},
{
"answer_id": 2818982,
"author": "Niraj CHoubey",
"author_id": 333371,
"author_profile": "https://Stackoverflow.com/users/333371",
"pm_score": 5,
"selected": false,
"text": "=== =="
},
{
"answer_id": 2819117,
"author": "Daniel",
"author_id": 250195,
"author_profile": "https://Stackoverflow.com/users/250195",
"pm_score": 5,
"selected": false,
"text": "$a = 0;\n $a==0; \n$a==NULL;\n$a==false;\n $a = 0;\n\n$a===0; // returns true\n$a===NULL; // returns false\n$a===false; // returns false\n"
},
{
"answer_id": 7446163,
"author": "CuongHuyTo",
"author_id": 487785,
"author_profile": "https://Stackoverflow.com/users/487785",
"pm_score": 6,
"selected": false,
"text": "'' == 0 == false // Any two values among these 3 ones are equal with the == operator\n'0' == 0 == false // Also a set of 3 equal values, note that only 0 and false are repeated\n'\\t' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n'\\r' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n'\\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n'\\t\\r\\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n\nnull == undefined // These two \"default\" values are not-equal to any of the listed values above\nNaN // NaN is not equal to any thing, even to itself.\n"
},
{
"answer_id": 10893560,
"author": "ashes",
"author_id": 582509,
"author_profile": "https://Stackoverflow.com/users/582509",
"pm_score": 5,
"selected": false,
"text": "=== == == === if (a == 'test')"
},
{
"answer_id": 16253116,
"author": "mar10",
"author_id": 19166,
"author_profile": "https://Stackoverflow.com/users/19166",
"pm_score": 5,
"selected": false,
"text": "=== == !== != == null if( value == null ){\n // value is either null or undefined\n}\n eqnull // Check for both undefined and null values, for some important reason. \nundefOrNull == null;\n ?? (??=) if (a.speed == null) {\n // Set default if null or undefined\n a.speed = 42;\n}\n a.speed ??= 42;\na.speed ?? a.speed = 42;\na.speed = a.speed ?? 42;\n"
},
{
"answer_id": 17439518,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "=== == 0==false // true\n0===false // false, because they are of a different type\n1==\"1\" // true, auto type coercion\n1===\"1\" // false, because they are of a different type\n"
},
{
"answer_id": 18694319,
"author": "Harry He",
"author_id": 1092195,
"author_profile": "https://Stackoverflow.com/users/1092195",
"pm_score": 5,
"selected": false,
"text": "var a = [1, 2, 3]; \nvar b = [1, 2, 3]; \nconsole.log(a == b) // false \nconsole.log(a === b) // false \n"
},
{
"answer_id": 19147489,
"author": "user2601995",
"author_id": 2601995,
"author_profile": "https://Stackoverflow.com/users/2601995",
"pm_score": 5,
"selected": false,
"text": "== >>> 1 == 1\ntrue\n>>> 1 == 2\nfalse\n>>> 1 == '1'\ntrue\n === >>> 1 === '1'\nfalse\n>>> 1 === 1\ntrue\n"
},
{
"answer_id": 22505350,
"author": "Mr.G",
"author_id": 3048442,
"author_profile": "https://Stackoverflow.com/users/3048442",
"pm_score": 4,
"selected": false,
"text": "1 == true => true\ntrue == true => true\n1 === true => false\ntrue === true => true\n"
},
{
"answer_id": 22675800,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 4,
"selected": false,
"text": "== ==="
},
{
"answer_id": 23056538,
"author": "vivek_nk",
"author_id": 1984606,
"author_profile": "https://Stackoverflow.com/users/1984606",
"pm_score": 4,
"selected": false,
"text": "var a;\nvar b = null;\n a b"
},
{
"answer_id": 23465314,
"author": "SNag",
"author_id": 979621,
"author_profile": "https://Stackoverflow.com/users/979621",
"pm_score": 10,
"selected": false,
"text": "== === var1 === var2 === var1 == var2 == === =="
},
{
"answer_id": 25208410,
"author": "garakchy",
"author_id": 2948746,
"author_profile": "https://Stackoverflow.com/users/2948746",
"pm_score": 4,
"selected": false,
"text": "=== == == x == y 3 == 3 // true\n\"3\" == 3 // true\n3 == '3' // true\n === x === y 3 === 3 // true"
},
{
"answer_id": 26923895,
"author": "Aniket Thakur",
"author_id": 2396539,
"author_profile": "https://Stackoverflow.com/users/2396539",
"pm_score": 5,
"selected": false,
"text": "=== == <script>\n\nfunction onPageLoad()\n{\n var x = \"5\";\n var y = 5;\n alert(x === 5);\n};\n\n</script>\n\n</head>\n\n<body onload='onPageLoad();'>\n onPageLoad() alert(x == 5);"
},
{
"answer_id": 27195277,
"author": "Sake Salverda",
"author_id": 3711267,
"author_profile": "https://Stackoverflow.com/users/3711267",
"pm_score": 4,
"selected": false,
"text": "===\n var check = 1;\nif(check == '1') {\n //someone continued with a string instead of number, most of the time useless for your webapp, most of the time entered by a user who does not now what he is doing (this will sometimes let your app crash), or even worse it is a hacker searching for weaknesses in your webapp!\n}\n var check = 1;\nif(check === 1) {\n //some continued with a number (no string) for your script\n} else {\n alert('please enter a real number');\n}\n ===\n"
},
{
"answer_id": 29159784,
"author": "Amit",
"author_id": 2424040,
"author_profile": "https://Stackoverflow.com/users/2424040",
"pm_score": 5,
"selected": false,
"text": "== === 123 == \"123\" // Returns true, because JS coerces string \"123\" to number 123\n // and then goes on to compare `123 == 123`.\n\n123 === \"123\" // Returns false, because JS does not coerce values of different types here.\n"
},
{
"answer_id": 29335281,
"author": "hopper",
"author_id": 4718716,
"author_profile": "https://Stackoverflow.com/users/4718716",
"pm_score": 4,
"selected": false,
"text": "=== new String(\"Hello world\") === \"Hello world\" == new String(\"Hello world\") == \"Hello world\""
},
{
"answer_id": 30240294,
"author": "Vikas",
"author_id": 1392727,
"author_profile": "https://Stackoverflow.com/users/1392727",
"pm_score": 5,
"selected": false,
"text": "2 == '2' -> true, values are SAME because of type conversion.\n\n2 === '2' -> false, values are NOT SAME because of no type conversion.\n"
},
{
"answer_id": 31564584,
"author": "Akshay Khale",
"author_id": 2541634,
"author_profile": "https://Stackoverflow.com/users/2541634",
"pm_score": 4,
"selected": false,
"text": "var i = 20;var j = \"20\";\n i==j //result is true\n j != i//result is false\n i===j //result is false\n"
},
{
"answer_id": 31847679,
"author": "CodeFarmer",
"author_id": 479008,
"author_profile": "https://Stackoverflow.com/users/479008",
"pm_score": 4,
"selected": false,
"text": "| use == | '' | '0' | false | 'false' | undefined | null | ' \\t\\r\\n ' |\n| '' | x | f | t | f | f | f | f |\n| '0' | | x | t | f | f | f | f |\n| false | | | x | f | f | f | t |\n| 'false' | | | | x | f | f | f |\n| undefined | | | | | x | t | f |\n| null | | | | | | x | f |\n| ' \\t\\r\\n ' | | | | | | | x | \n\n\n\n| use === | '' | '0' | false | 'false' | undefined | null | ' \\t\\r\\n ' |\n| '' | x | f | f | f | f | f | f |\n| '0' | | x | f | f | f | f | f |\n| false | | | x | f | f | f | f |\n| 'false' | | | | x | f | f | f |\n| undefined | | | | | x | f | f |\n| null | | | | | | x | f |\n| ' \\t\\r\\n ' | | | | | | | x |\n var rowItems = ['', '0', false, 'false', undefined, null, ' \\t\\r\\n ']\nvar colItems = rowItems\n\nfor(var i = 0; i < rowItems.length; i++) {\n for (var j = 0; j < colItems.length; j++) {\n var r = (rowItems[i] === colItems[j]) ? true : false;\n console.log(rowItems[i] + \" = \" + colItems[j] + \" \" + r + \" [\" + i + \"] ==> [\" + j + \"]\")\n };\n}\n"
},
{
"answer_id": 34592242,
"author": "Dmitri Pavlutin",
"author_id": 1894471,
"author_profile": "https://Stackoverflow.com/users/1894471",
"pm_score": 3,
"selected": false,
"text": "== ==="
},
{
"answer_id": 37233133,
"author": "Alex Gray",
"author_id": 547214,
"author_profile": "https://Stackoverflow.com/users/547214",
"pm_score": 3,
"selected": false,
"text": "=== coffee-script coffee-script === coffee-script"
},
{
"answer_id": 38150563,
"author": "yanguya995",
"author_id": 6486347,
"author_profile": "https://Stackoverflow.com/users/6486347",
"pm_score": 1,
"selected": false,
"text": "var x = \"20\";\nvar y =20;\n\nif (x===y) // false\n If(x==y)//true\n"
},
{
"answer_id": 38204022,
"author": "Orri Scott",
"author_id": 4712641,
"author_profile": "https://Stackoverflow.com/users/4712641",
"pm_score": 0,
"selected": false,
"text": "var a = new String(\"123\");\nvar b = \"123\";\n\nalert(a === b); // returns false !! (but they are equal and of the same type)\n a b typeof(a) typeof(b)"
},
{
"answer_id": 38856418,
"author": "Luis Perez",
"author_id": 984780,
"author_profile": "https://Stackoverflow.com/users/984780",
"pm_score": 7,
"selected": false,
"text": "== \"\" 0 true == '0' == false // true\n [1] == true // true\n[] == false // true\n[[]] == false // true\n[0] == false // true\n [1,2,3] == '1,2,3' // true - REALLY?!\n'\\r\\n\\t' == 0 // true - Come on!\n let A = '' // empty string\nlet B = 0 // zero\nlet C = '0' // zero string\n\nA == B // true - ok... \nB == C // true - so far so good...\nA == C // **FALSE** - Plot twist!\n (A == B) && (B == C) // true\n(A == C) // **FALSE**\n == === == == function isEqual(x, y) { // if `==` were a function\n if(typeof y === typeof x) return y === x;\n // treat null and undefined the same\n var xIsNothing = (y === undefined) || (y === null);\n var yIsNothing = (x === undefined) || (x === null);\n\n if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);\n\n if(typeof y === \"function\" || typeof x === \"function\") {\n // if either value is a string \n // convert the function into a string and compare\n if(typeof x === \"string\") {\n return x === y.toString();\n } else if(typeof y === \"string\") {\n return x.toString() === y;\n } \n return false;\n }\n\n if(typeof x === \"object\") x = toPrimitive(x);\n if(typeof y === \"object\") y = toPrimitive(y);\n if(typeof y === typeof x) return y === x;\n\n // convert x and y into numbers if they are not already use the \"+\" trick\n if(typeof x !== \"number\") x = +x;\n if(typeof y !== \"number\") y = +y;\n // actually the real `==` is even more complicated than this, especially in ES6\n return x === y;\n}\n\nfunction toPrimitive(obj) {\n var value = obj.valueOf();\n if(obj !== value) return value;\n return obj.toString();\n}\n == === =="
},
{
"answer_id": 43587762,
"author": "Rotimi",
"author_id": 7104527,
"author_profile": "https://Stackoverflow.com/users/7104527",
"pm_score": 1,
"selected": false,
"text": "console.log(3 == \"3\"); // true\nconsole.log(3 === \"3\"); // false.\nconsole.log(3 == \"3\"); // true\nconsole.log(3 === \"3\"); // false.\n console.log(true == '1'); // true\nconsole.log(true === '1'); // false\nconsole.log(true == '1'); // true\nconsole.log(true === '1'); // false\n console.log(undefined == null); // true\nconsole.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.\nconsole.log(undefined == null); // true \nconsole.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.\n\nconsole.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.\nconsole.log(true === 'true'); // false\nconsole.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.\nconsole.log(true === 'true'); // false\n console.log(\"This is a string.\" == new String(\"This is a string.\")); // true\nconsole.log(\"This is a string.\" === new String(\"This is a string.\")); // false\nconsole.log(\"This is a string.\" == new String(\"This is a string.\")); // true\nconsole.log(\"This is a string.\" === new String(\"This is a string.\")); // false\n"
},
{
"answer_id": 43672227,
"author": "Sharad Kale",
"author_id": 3178139,
"author_profile": "https://Stackoverflow.com/users/3178139",
"pm_score": 4,
"selected": false,
"text": "== === 1 == \"1\" //true\n\n1 === \"1\" //false\n \"===\" \"===\""
},
{
"answer_id": 43831317,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 1,
"selected": false,
"text": "=== == var num = 0;\nvar obj = new String('0');\nvar str = '0';\n\nconsole.log(num === num); // true\nconsole.log(obj === obj); // true\nconsole.log(str === str); // true\n\nconsole.log(num === obj); // false\nconsole.log(num === str); // false\nconsole.log(obj === str); // false\nconsole.log(null === undefined); // false\nconsole.log(obj === null); // false\nconsole.log(obj === undefined); // false\n var num = 0;\nvar obj = new String('0');\nvar str = '0';\n\nconsole.log(num == num); // true\nconsole.log(obj == obj); // true\nconsole.log(str == str); // true\n\nconsole.log(num == obj); // true\nconsole.log(num == str); // true\nconsole.log(obj == str); // true\nconsole.log(null == undefined); // true\n\n// both false, except in rare cases\nconsole.log(obj == null);\nconsole.log(obj == undefined);\n"
},
{
"answer_id": 44745396,
"author": "RïshïKêsh Kümar",
"author_id": 6056671,
"author_profile": "https://Stackoverflow.com/users/6056671",
"pm_score": 3,
"selected": false,
"text": "= = = = = = = value = = values datatype = = = values datatype"
},
{
"answer_id": 45433694,
"author": "Narendra Kalekar",
"author_id": 7338983,
"author_profile": "https://Stackoverflow.com/users/7338983",
"pm_score": 1,
"selected": false,
"text": "== === === == === ==="
},
{
"answer_id": 47500217,
"author": "Bekim Bacaj",
"author_id": 5896426,
"author_profile": "https://Stackoverflow.com/users/5896426",
"pm_score": 1,
"selected": false,
"text": "== === == === == ==="
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44990/"
] |
359,495 | <p>Why are the lists <code>list1Instance</code> and <code>p</code> in the <code>Main</code> method of the below code pointing to the same collection? </p>
<pre><code>class Person
{
public string FirstName = string.Empty;
public string LastName = string.Empty;
public Person(string firstName, string lastName) {
this.FirstName = firstName;
this.LastName = lastName;
}
}
class List1
{
public List<Person> l1 = new List<Person>();
public List1()
{
l1.Add(new Person("f1","l1"));
l1.Add(new Person("f2", "l2"));
l1.Add(new Person("f3", "l3"));
l1.Add(new Person("f4", "l4"));
l1.Add(new Person("f5", "l5"));
}
public IEnumerable<Person> Get()
{
foreach (Person p in l1)
{
yield return p;
}
//return l1.AsReadOnly();
}
}
class Program
{
static void Main(string[] args)
{
List1 list1Instance = new List1();
List<Person> p = new List<Person>(list1Instance.Get());
UpdatePersons(p);
bool sameFirstName = (list1Instance.l1[0].FirstName == p[0].FirstName);
}
private static void UpdatePersons(List<Person> list)
{
list[0].FirstName = "uf1";
}
}
</code></pre>
<p>Can we change this behavior with out changing the return type of <code>List1.Get()</code>? </p>
<p>Thanks</p>
| [
{
"answer_id": 359507,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 6,
"selected": true,
"text": "IEnumerable<T> Person Person class struct Person"
},
{
"answer_id": 359515,
"author": "Szymon Rozga",
"author_id": 7583,
"author_profile": "https://Stackoverflow.com/users/7583",
"pm_score": 2,
"selected": false,
"text": "Person List<Person> p = new List<Person>(list1Instance.Get()); \n list1Instance.Get() p IEnumerable Person IEnumerable<T>"
},
{
"answer_id": 359529,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "p p public IEnumerable<Person> Get()\n{\n foreach (Person p in l1)\n {\n yield return p.Clone();\n }\n}\n"
},
{
"answer_id": 359533,
"author": "DonkeyMaster",
"author_id": 5178,
"author_profile": "https://Stackoverflow.com/users/5178",
"pm_score": 0,
"selected": false,
"text": "IEnumerable<T> p list1instance list[0].FirstName = \"uf1\"; Person"
},
{
"answer_id": 359545,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 1,
"selected": false,
"text": "return l1.AsReadOnly().GetEnumerator();\n"
},
{
"answer_id": 359566,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "public IEnumerable<Person> Get()\n{\n return l1\n .Select(p => new Person(){\n FirstName = p.FirstName,\n LastName = p.LastName\n });\n}\n"
},
{
"answer_id": 359578,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 1,
"selected": false,
"text": " public class Person\n {\n public FirstName {get; private set;}\n public LastName {get; private set;}\n public Person(firstName, lastName)\n {\n FirstName = firstName;\n LastName = lastName;\n }\n }\n"
},
{
"answer_id": 53510939,
"author": "PJJ",
"author_id": 10270820,
"author_profile": "https://Stackoverflow.com/users/10270820",
"pm_score": 0,
"selected": false,
"text": "class Person\n{\n public virtual string FirstName { get; set; }\n public virtual string LastName { get; set; }\n\n\n public Person(string firstName, string lastName) {\n this.FirstName = firstName;\n this.LastName = lastName;\n }\n\n}\n\nclass PersonReadOnly : Person\n{\n public override string FirstName { get { return base.FirstName; } set { throw new Exception(\"setting a readonly field\"); } }\n public override string LastName { get { return base.LastName; } set { throw new Exception(\"setting a readonly field\"); } }\n\n public PersonReadOnly(string firstName, string lastName) : base(firstName, lastName)\n {\n }\n public PersonReadOnly(Person p) : base(p.FirstName, p.LastName)\n {\n\n }\n\n}\n\nclass List1\n{\n public List<Person> l1 = new List<Person>();\n\n public List1()\n {\n l1.Add(new Person(\"f1\", \"l1\"));\n l1.Add(new Person(\"f2\", \"l2\"));\n l1.Add(new Person(\"f3\", \"l3\"));\n l1.Add(new Person(\"f4\", \"l4\"));\n l1.Add(new Person(\"f5\", \"l5\"));\n }\n public IEnumerable<Person> Get()\n {\n foreach (Person p in l1)\n {\n yield return new PersonReadOnly(p);\n }\n //return l1.AsReadOnly(); \n }\n\n} \nclass Program\n{\n\n static void Main(string[] args)\n {\n List1 list1Instance = new List1();\n\n List<Person> p = new List<Person>(list1Instance.Get()); \n\n UpdatePersons(p);\n\n bool sameFirstName = (list1Instance.l1[0].FirstName == p[0].FirstName);\n }\n\n private static void UpdatePersons(List<Person> list)\n {\n // readonly message thrown\n list[0].FirstName = \"uf1\";\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26036/"
] |
359,497 | <p>I have seen a few suggestions on making emacs portable (on Windows). I have this in my site-start.el:</p>
<pre><code>(defvar program-dir (substring data-directory 0 -4))
(setq inhibit-startup-message t)
(setenv "HOME" program-dir)
</code></pre>
<p>I changed the HOME variable so that not only my .emacs init files (and other init files) are read, but everything generated by emacs will stay in the program directory, not needing me to specify the path for everything one by one. </p>
<p>Well this works well but the emacs server is not working; I get error message "no connection could be made because target machine actively refused it." If I don't change my HOME var then emacs server works. Is there way to fix this?</p>
| [
{
"answer_id": 359554,
"author": "ShreevatsaR",
"author_id": 4958,
"author_profile": "https://Stackoverflow.com/users/4958",
"pm_score": 3,
"selected": false,
"text": "emacsclient ${program-dir}/.emacs.d/server/ -f EMACS_SERVER_FILE emacsclient -s /tmp/emacs501/server"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,498 | <p>I'm using ctypes to load a DLL in Python. This works great.</p>
<p>Now we'd like to be able to reload that DLL at runtime. </p>
<p>The straightforward approach would seem to be:
1. Unload DLL
2. Load DLL</p>
<p>Unfortunately I'm not sure what the correct way to unload the DLL is.</p>
<p>_ctypes.FreeLibrary is available, but private.</p>
<p>Is there some other way to unload the DLL?</p>
| [
{
"answer_id": 359570,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 5,
"selected": true,
"text": "mydll = ctypes.CDLL('...')\ndel mydll\nmydll = ctypes.CDLL('...')\n _handle mydll = ctypes.CDLL('./mylib.so')\nhandle = mydll._handle\ndel mydll\nwhile isLoaded('./mylib.so'):\n dlclose(handle)\n def isLoaded(lib):\n libp = os.path.abspath(lib)\n ret = os.system(\"lsof -p %d | grep %s > /dev/null\" % (os.getpid(), libp))\n return (ret == 0)\n\ndef dlclose(handle)\n libdl = ctypes.CDLL(\"libdl.so\")\n libdl.dlclose(handle)\n"
},
{
"answer_id": 28610285,
"author": "pyHazard",
"author_id": 2852852,
"author_profile": "https://Stackoverflow.com/users/2852852",
"pm_score": 3,
"selected": false,
"text": "REBUILD = True\nif REBUILD:\n from subprocess import call\n call('g++ -c -DBUILDING_EXAMPLE_DLL test.cpp')\n call('g++ -shared -o test.dll test.o -Wl,--out-implib,test.a')\n\nimport ctypes\nimport numpy\n\n# Simplest way to load the DLL\nmydll = ctypes.cdll.LoadLibrary('test.dll')\n\n# Call a function in the DLL\nprint mydll.test(10)\n\n# Unload the DLL so that it can be rebuilt\nlibHandle = mydll._handle\ndel mydll\nctypes.windll.kernel32.FreeLibrary(libHandle)\n"
},
{
"answer_id": 62326340,
"author": "anroesti",
"author_id": 602216,
"author_profile": "https://Stackoverflow.com/users/602216",
"pm_score": 2,
"selected": false,
"text": "Traceback (most recent call last):\n...\nctypes.ArgumentError: argument 1: <class 'OverflowError'>: int too long to convert\n FreeLibrary import ctypes, ctypes.windll\n\ndef free_library(handle):\n kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)\n kernel32.FreeLibrary.argtypes = [ctypes.wintypes.HMODULE]\n kernel32.FreeLibrary(handle)\n lib = ctypes.CDLL(\"foobar.dll\")\nfree_library(lib._handle)\n"
},
{
"answer_id": 64483246,
"author": "Markus Dutschke",
"author_id": 7128154,
"author_profile": "https://Stackoverflow.com/users/7128154",
"pm_score": 2,
"selected": false,
"text": "extern \"C\" int my_fct(int n)\n{\n int factor = 10;\n return factor * n;\n}\n #!/bin/bash\ng++ cpp_code.cpp -shared -o myso.so\n set gpp=\"C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe\"\n%gpp% cpp_code.cpp -shared -o mydll.dll\nPAUSE\n from sys import platform\nimport ctypes\n\n\nif platform == \"linux\" or platform == \"linux2\":\n # https://stackoverflow.com/a/50986803/7128154\n # https://stackoverflow.com/a/52223168/7128154\n\n dlclose_func = ctypes.cdll.LoadLibrary('').dlclose\n dlclose_func.argtypes = [ctypes.c_void_p]\n\n fn_lib = './myso.so'\n ctypes_lib = ctypes.cdll.LoadLibrary(fn_lib)\n handle = ctypes_lib._handle\n\n valIn = 42\n valOut = ctypes_lib.my_fct(valIn)\n print(valIn, valOut)\n\n del ctypes_lib\n dlclose_func(handle)\n\nelif platform == \"win32\": # Windows\n # https://stackoverflow.com/a/13129176/7128154\n # https://stackoverflow.com/questions/359498/how-can-i-unload-a-dll-using-ctypes-in-python\n\n lib = ctypes.WinDLL('./mydll.dll')\n libHandle = lib._handle\n\n # do stuff with lib in the usual way\n valIn = 42\n valOut = lib.my_fct(valIn)\n print(valIn, valOut)\n\n del lib\n ctypes.windll.kernel32.FreeLibrary(libHandle)\n dependencies OpenCv #include <opencv2/core/core.hpp>\n#include <iostream> \n\n\nextern \"C\" int my_fct(int n)\n{\n cv::Mat1b mat = cv::Mat1b(10,8,(unsigned char) 1 ); // change 1 to test unloading\n \n return mat(0,1) * n;\n}\n g++ code.cpp -shared -fPIC -Wall -std=c++17 -I/usr/include/opencv4 -lopencv_core -o so_opencv.so from sys import platform\nimport ctypes\n\n\nclass CtypesLib:\n\n def __init__(self, fp_lib, dependencies=[]):\n self._dependencies = [CtypesLib(fp_dep) for fp_dep in dependencies]\n\n if platform == \"linux\" or platform == \"linux2\": # Linux\n self._dlclose_func = ctypes.cdll.LoadLibrary('').dlclose\n self._dlclose_func.argtypes = [ctypes.c_void_p]\n self._ctypes_lib = ctypes.cdll.LoadLibrary(fp_lib)\n elif platform == \"win32\": # Windows\n self._ctypes_lib = ctypes.WinDLL(fp_lib)\n\n self._handle = self._ctypes_lib._handle\n\n def __getattr__(self, attr):\n return self._ctypes_lib.__getattr__(attr)\n\n def __del__(self):\n for dep in self._dependencies:\n del dep\n\n del self._ctypes_lib\n\n if platform == \"linux\" or platform == \"linux2\": # Linux\n self._dlclose_func(self._handle)\n elif platform == \"win32\": # Windows\n ctypes.windll.kernel32.FreeLibrary(self._handle)\n\n\nfp_lib = './so_opencv.so'\n\nctypes_lib = CtypesLib(fp_lib, ['/usr/lib64/libopencv_core.so'])\n\nvalIn = 1\nctypes_lib.my_fct.argtypes = [ctypes.c_int]\nctypes_lib.my_fct.restype = ctypes.c_int\nvalOut = ctypes_lib.my_fct(valIn)\nprint(valIn, valOut)\n\ndel ctypes_lib\n"
},
{
"answer_id": 66971833,
"author": "pullmyteeth",
"author_id": 7390688,
"author_profile": "https://Stackoverflow.com/users/7390688",
"pm_score": 2,
"selected": false,
"text": "dlclose() import sys\nimport ctypes\nimport platform\n\nOS = platform.system()\n\nif OS == \"Windows\": # pragma: Windows\n dll_close = ctypes.windll.kernel32.FreeLibrary\n\nelif OS == \"Darwin\":\n try:\n try:\n # macOS 11 (Big Sur). Possibly also later macOS 10s.\n stdlib = ctypes.CDLL(\"libc.dylib\")\n except OSError:\n stdlib = ctypes.CDLL(\"libSystem\")\n except OSError:\n # Older macOSs. Not only is the name inconsistent but it's\n # not even in PATH.\n stdlib = ctypes.CDLL(\"/usr/lib/system/libsystem_c.dylib\")\n dll_close = stdlib.dlclose\n\nelif OS == \"Linux\":\n try:\n stdlib = ctypes.CDLL(\"\")\n except OSError:\n # Alpine Linux.\n stdlib = ctypes.CDLL(\"libc.so\")\n dll_close = stdlib.dlclose\n\nelif sys.platform == \"msys\":\n # msys can also use `ctypes.CDLL(\"kernel32.dll\").FreeLibrary()`. Not sure\n # if or what the difference is.\n stdlib = ctypes.CDLL(\"msys-2.0.dll\")\n dll_close = stdlib.dlclose\n\nelif sys.platform == \"cygwin\":\n stdlib = ctypes.CDLL(\"cygwin1.dll\")\n dll_close = stdlib.dlclose\n\nelif OS == \"FreeBSD\":\n # FreeBSD uses `/usr/lib/libc.so.7` where `7` is another version number.\n # It is not in PATH but using its name instead of its path is somehow the\n # only way to open it. The name must include the .so.7 suffix.\n stdlib = ctypes.CDLL(\"libc.so.7\")\n dll_close = stdlib.close\n\nelse:\n raise NotImplementedError(\"Unknown platform.\")\n\ndll_close.argtypes = [ctypes.c_void_p]\n\n dll_close(dll._handle) dll = ctypes.CDLL(\"your-library\")"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6839/"
] |
359,516 | <p>Id like to be able to write a function that reads an external news site and returns the source code of the target page. Any ideas and/or information to get me started?</p>
| [
{
"answer_id": 359522,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": true,
"text": "string GetOtherPage(System.Uri url)\n{\n return new System.Net.WebClient().DownloadString(url);\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
359,528 | <p>I have Visual Studio 2008 Professional and I am having issues with expanding and collapsing method code blocks in ASP.Net Generic Handler pages (.ashx)</p>
<p>I would have thought you could do the same thing like in the code behind of .aspx web pages.</p>
<p>I have this same issue on other boxes even with VS 2008 Standard and VS 2005 Professional. All boxes have been fully patched (OS and Visual Studio.)</p>
<p>Does anybody have any suggestions as to enabling this feature?</p>
| [
{
"answer_id": 5741158,
"author": "bigEsmurf",
"author_id": 718525,
"author_profile": "https://Stackoverflow.com/users/718525",
"pm_score": 4,
"selected": false,
"text": "App_Code <%@ WebHandler Language=\"C#\" Class=\"SomethingHandler\" %>\n App_Code SomethingHandler.cs SomethingHandler using System;\nusing System.Web;\n// using blabla...\n\npublic class SomethingHandler : IHttpHandler\n{\n public void ProcessRequest(HttpContext c)\n {\n etc...\n"
},
{
"answer_id": 6829083,
"author": "Kaspars",
"author_id": 863309,
"author_profile": "https://Stackoverflow.com/users/863309",
"pm_score": 3,
"selected": false,
"text": "///<%@ WebHandler Language=\"C#\" Class=\"FooBar\"%>\n"
},
{
"answer_id": 31144103,
"author": "KakashiJack",
"author_id": 5030017,
"author_profile": "https://Stackoverflow.com/users/5030017",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Web;\nusing System.Web.Security;\nusing System.Collections.Generic;\nusing System.Configuration;\nusing System.Data.SqlClient;\nusing System.Data;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24522/"
] |
359,541 | <p>I have a small C library in a DLL and I need to call a handful of its methods.</p>
<p>It uses pointers and a few structs but is otherwise quite simple. Problem is I'm not terribly knowledgable on .NET's interop with the unmanaged world and my attempts so far keep hitting memory access violation exceptions (presumably due to me not getting the pointers quite right).</p>
<p>Could anyone give me some pointers (ooh a pun!) on the best way to approach this?</p>
<p>Thank you</p>
<pre><code>extern vconfig_t *Pobsopen(Ppoly_t ** obstacles, int n_obstacles);
extern int Pobspath(vconfig_t * config, Ppoint_t p0, int poly0,
Ppoint_t p1, int poly1,
Ppolyline_t * output_route);
extern void Pobsclose(vconfig_t * config);
struct vconfig_t {
int Npoly;
int N;
Ppoint_t *P;
int *start;
int *next;
int *prev;
};
typedef struct Ppoly_t {
Ppoint_t *ps;
int pn;
} Ppoly_t;
typedef Ppoly_t Ppolyline_t;
typedef struct Pxy_t {
double x, y;
} Pxy_t;
typedef struct Pxy_t Ppoint_t;
typedef struct Pxy_t Pvector_t;
</code></pre>
| [
{
"answer_id": 359843,
"author": "mherle",
"author_id": 42913,
"author_profile": "https://Stackoverflow.com/users/42913",
"pm_score": 3,
"selected": false,
"text": "[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\npublic struct vconfig_t {\n\n /// int\n public int Npoly;\n\n /// int\n public int N;\n\n /// Ppoint_t*\n public System.IntPtr P;\n\n /// int*\n public System.IntPtr start;\n\n /// int*\n public System.IntPtr next;\n\n /// int*\n public System.IntPtr prev;\n}\n\n[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\npublic struct Ppoly_t {\n\n /// Ppoint_t*\n public System.IntPtr ps;\n\n /// int\n public int pn;\n}\n\n[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\npublic struct Pxy_t {\n\n /// double\n public double x;\n\n /// double\n public double y;\n}\n\npublic partial class NativeMethods {\n\n /// Return Type: vconfig_t*\n ///obstacles: Ppoly_t**\n ///n_obstacles: int\n [System.Runtime.InteropServices.DllImportAttribute(\"<Unknown>\", EntryPoint=\"Pobsopen\")]\npublic static extern System.IntPtr Pobsopen(ref System.IntPtr obstacles, int n_obstacles) ;\n\n\n /// Return Type: int\n ///config: vconfig_t*\n ///p0: Ppoint_t->Pxy_t\n ///poly0: int\n ///p1: Ppoint_t->Pxy_t\n ///poly1: int\n ///output_route: Ppolyline_t*\n [System.Runtime.InteropServices.DllImportAttribute(\"<Unknown>\", EntryPoint=\"Pobspath\")]\npublic static extern int Pobspath(ref vconfig_t config, Pxy_t p0, int poly0, Pxy_t p1, int poly1, ref Ppoly_t output_route) ;\n\n\n /// Return Type: void\n ///config: vconfig_t*\n [System.Runtime.InteropServices.DllImportAttribute(\"<Unknown>\", EntryPoint=\"Pobsclose\")]\npublic static extern void Pobsclose(ref vconfig_t config) ;\n\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41475/"
] |
359,553 | <p>While debugging a Linux app, I found a pointer with the suspicious value 0x7c7c7c7c. Does that particular value indicate anything?</p>
<p>(I ask because I know from my MSVC days that in a debug build, values like 0xcdcdcdcd or 0xdddddddd would be stored into heap blocks that were uninitialized, freed, or otherwise invalid. Some people use magic values like 0xdeadbeef or 0xcafebabe in uninitialized memory. I'm guessing something in libc or elsewhere uses 0x7c7c7c7c as a magic value, but I can't find it documented.)</p>
| [
{
"answer_id": 359574,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "memset()"
},
{
"answer_id": 359792,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 1,
"selected": false,
"text": "MALLOC_PERTURB_"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
359,582 | <p>A client has installed Sql server 2005 reporting services. When we go to the web bit at <code>http://servername/reports/</code> we just see a blank screen like:
<img src="https://i.stack.imgur.com/nGQXH.jpg" alt="http://img91.imageshack.us/img91/3787/rsblankqx4.jpg"></p>
<p>We are using windows authentication and I think it has authenticated us as the "site settings" button is appearing and we can alter site security, add to roles etc. </p>
<p>I have had this before and cant remember how I fixed it. </p>
<p>Any ideas?</p>
<p>Thanks,</p>
<p>Alex</p>
| [
{
"answer_id": 359574,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "memset()"
},
{
"answer_id": 359792,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 1,
"selected": false,
"text": "MALLOC_PERTURB_"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
359,590 | <p>How do I get the reference to a folder for storing per-user-per-application settings when writing an Objective-C Cocoa app in Xcode?</p>
<p>In .NET I would use the <code>Environment.SpecialFolder</code> enumeration:</p>
<pre><code>Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
</code></pre>
<p>What's the Cocoa equivalent?</p>
| [
{
"answer_id": 359819,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 5,
"selected": true,
"text": "~/Library/Preferences/ ~/Library/Application Support/Your App Name/ + (NSString *)applicationSupportFolder;\n{\n // Find this application's Application Support Folder, creating it if \n // needed.\n\n NSString *appName, *supportPath = nil;\n NSArray *paths = NSSearchPathForDirectoriesInDomains( NSApplicationSupportDirectory, NSUserDomainMask, YES );\n\n if ( [paths count] > 0)\n {\n appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@\"CFBundleExecutable\"];\n supportPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:appName];\n\n if ( ![[NSFileManager defaultManager] fileExistsAtPath:supportPath] )\n if ( ![[NSFileManager defaultManager] createDirectoryAtPath:supportPath attributes:nil] )\n supportPath = nil;\n }\n\n return supportPath;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6408/"
] |
359,596 | <p>In a .NET application, how can I identify which network interface is used to communicate to a given IP address?</p>
<p>I am running on workstations with multiple network interfaces, IPv4 and v6, and I need to get the address of the "correct" interface used for traffic to my given database server.</p>
| [
{
"answer_id": 359640,
"author": "Paul Nearney",
"author_id": 24071,
"author_profile": "https://Stackoverflow.com/users/24071",
"pm_score": 2,
"selected": false,
"text": "using System.Management;\nstring query = \"SELECT * FROM Win32_NetworkAdapterConfiguration\";\nManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);\nManagementObjectCollection moCollection = moSearch.Get();// Every record in this collection is a network interface\nforeach (ManagementObject mo in moCollection)\n{ \n // Do what you need to here....\n}\n"
},
{
"answer_id": 359650,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": 2,
"selected": false,
"text": "IPHostEntry hostEntry = Dns.GetHostEntry(Environment.MachineName);\n\nforeach (System.Net.IPAddress address in hostEntry.AddressList)\n{\n Console.WriteLine(address);\n}\n"
},
{
"answer_id": 360176,
"author": "Coderer",
"author_id": 26286,
"author_profile": "https://Stackoverflow.com/users/26286",
"pm_score": 3,
"selected": false,
"text": "route PRINT (destination IP)"
},
{
"answer_id": 621702,
"author": "Yariv",
"author_id": 55052,
"author_profile": "https://Stackoverflow.com/users/55052",
"pm_score": 6,
"selected": true,
"text": "UdpClient u = new UdpClient(remoteAddress, 1);\nIPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;\n \nforeach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())\n{\n IPInterfaceProperties ipProps = nic.GetIPProperties();\n // check if localAddr is in ipProps.UnicastAddresses\n}\n GetIPProperties() IPv4InterfaceProperties.Index"
},
{
"answer_id": 20092907,
"author": "lxa",
"author_id": 167195,
"author_profile": "https://Stackoverflow.com/users/167195",
"pm_score": 2,
"selected": false,
"text": "Socket.IOControl( SIO_ROUTING_INTERFACE_QUERY, ... )"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38567/"
] |
359,601 | <p>I'm looking for a single line regex which does the following:</p>
<p>Given a HTML tag with the "name" attribute, I want to replace it with my own attribute. If that tag lacks the name attribute, I want to implant my own attribute. The result should look like this:</p>
<pre><code><IMG name="img1" ...> => <IMG name="myImg1" ...>
<IMG ...> => <IMG name="myImg1" ...>
</code></pre>
<p>Can this be done with a single line regex?</p>
| [
{
"answer_id": 359724,
"author": "Tim Pietzcker",
"author_id": 20670,
"author_profile": "https://Stackoverflow.com/users/20670",
"pm_score": 0,
"selected": false,
"text": "<(?!/)(/w+)\\s+(name=\"[^\"]+\")? <\\1 name=\"myImg1\""
},
{
"answer_id": 359773,
"author": "Sean",
"author_id": 45364,
"author_profile": "https://Stackoverflow.com/users/45364",
"pm_score": 1,
"selected": false,
"text": "s/(<IMG)((\\s+[^>]*)name=\"[^\"]*\")?(.*)/$1$3 name=\"myID\"$4/g\n"
},
{
"answer_id": 361343,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 3,
"selected": true,
"text": "s/<IMG\n ((?:\\s+(?!name\\b)\\w+=\"[^\"]+\")*)\n (?:\\s+name=\"[^\"]+\")?\n ((?:\\s+(?!name\\b)\\w+=\"[^\"]+\")*)\n >\n /<IMG name=\"myName\"$1$2>\n /xg;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9941/"
] |
359,612 | <p>How can I convert a RGB Color to HSV using C#?<br/>
I've searched for a fast method without using any external library.</p>
| [
{
"answer_id": 637025,
"author": "georged",
"author_id": 70347,
"author_profile": "https://Stackoverflow.com/users/70347",
"pm_score": 6,
"selected": true,
"text": "System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);\nfloat hue = color.GetHue();\nfloat saturation = color.GetSaturation();\nfloat lightness = color.GetBrightness();\n"
},
{
"answer_id": 1187552,
"author": "Captain Lepton",
"author_id": 106426,
"author_profile": "https://Stackoverflow.com/users/106426",
"pm_score": 2,
"selected": false,
"text": "Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)\n Dim i As Integer\n Dim f, p, q, t As Double\n\n If (s = 0) Then\n ' achromatic (grey)\n r = v\n g = v\n b = v\n Exit Sub\n End If\n\n h /= 60 'sector 0 to 5\n i = Math.Floor(h)\n f = h - i 'factorial part of h\n p = v * (1 - s)\n q = v * (1 - s * f)\n t = v * (1 - s * (1 - f))\n\n Select Case (i)\n Case 0\n r = v\n g = t\n b = p\n Exit Select\n Case 1\n r = q\n g = v\n b = p\n Exit Select\n Case 2\n r = p\n g = v\n b = t\n Exit Select\n Case 3\n r = p\n g = q\n b = v\n Exit Select\n Case 4\n r = t\n g = p\n b = v\n Exit Select\n Case Else 'case 5:\n r = v\n g = p\n b = q\n Exit Select\n End Select\nEnd Sub\n"
},
{
"answer_id": 1626175,
"author": "Greg",
"author_id": 12971,
"author_profile": "https://Stackoverflow.com/users/12971",
"pm_score": 7,
"selected": false,
"text": "Color.GetSaturation() Color.GetBrightness() Color original = Color.FromArgb(50, 120, 200);\n// original = {Name=ff3278c8, ARGB=(255, 50, 120, 200)}\n\ndouble hue;\ndouble saturation;\ndouble value;\nColorToHSV(original, out hue, out saturation, out value);\n// hue = 212.0\n// saturation = 0.75\n// value = 0.78431372549019607\n\nColor copy = ColorFromHSV(hue, saturation, value);\n// copy = {Name=ff3278c8, ARGB=(255, 50, 120, 200)}\n\n// Compare that to the HSL values that the .NET framework provides: \noriginal.GetHue(); // 212.0\noriginal.GetSaturation(); // 0.6\noriginal.GetBrightness(); // 0.490196079\n hue saturation value public static void ColorToHSV(Color color, out double hue, out double saturation, out double value)\n{\n int max = Math.Max(color.R, Math.Max(color.G, color.B));\n int min = Math.Min(color.R, Math.Min(color.G, color.B));\n\n hue = color.GetHue();\n saturation = (max == 0) ? 0 : 1d - (1d * min / max);\n value = max / 255d;\n}\n\npublic static Color ColorFromHSV(double hue, double saturation, double value)\n{\n int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6;\n double f = hue / 60 - Math.Floor(hue / 60);\n\n value = value * 255;\n int v = Convert.ToInt32(value);\n int p = Convert.ToInt32(value * (1 - saturation));\n int q = Convert.ToInt32(value * (1 - f * saturation));\n int t = Convert.ToInt32(value * (1 - (1 - f) * saturation));\n\n if (hi == 0)\n return Color.FromArgb(255, v, t, p);\n else if (hi == 1)\n return Color.FromArgb(255, q, v, p);\n else if (hi == 2)\n return Color.FromArgb(255, p, v, t);\n else if (hi == 3)\n return Color.FromArgb(255, p, q, v);\n else if (hi == 4)\n return Color.FromArgb(255, t, p, v);\n else\n return Color.FromArgb(255, v, p, q);\n}\n"
},
{
"answer_id": 38159684,
"author": "Matthias K.",
"author_id": 5321960,
"author_profile": "https://Stackoverflow.com/users/5321960",
"pm_score": -1,
"selected": false,
"text": "Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();\npaintcolor = bmp.GetPixel(e.X, e.Y);\n hue = yourcolor.Gethue;\nsaturation = yourcolor.GetSaturation;\nbrightness = yourcolor.GetBrightness;\n Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();\n paintcolor = bmp.GetPixel(e.X, e.Y);\n float hue;\n float saturation;\n float brightness;\n hue = paintcolor.GetHue();\n saturation = paintcolor.GetSaturation();\n brightness = paintcolor.GetBrightness();\n yourlabelname.Text = hue.ToString;\nyourlabelname.Text = saturation.ToString;\nyourlabelname.Text = brightness.ToString;\n"
},
{
"answer_id": 69759878,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " /// <summary> Convert RGB Color to HSV. </summary>\n /// <param name=\"color\"></param>\n /// <returns> A double[] Containing HSV Color Values. </returns>\n public double[] rgbToHSV(Color color)\n {\n double[] output = new double[3];\n\n double hue, saturation, value;\n\n int max = Math.Max(color.R, Math.Max(color.G, color.B));\n int min = Math.Min(color.R, Math.Min(color.G, color.B));\n\n hue = color.GetHue();\n saturation = (max == 0) ? 0 : 1d - (1d * min / max);\n value = max / 255d;\n\n output[0] = hue;\n output[1] = saturation;\n output[2] = value;\n\n return output;\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38940/"
] |
359,620 | <p>Can you use a Spring-WS WebserviceTemplate for calling a webservice and avoid that it generates a SOAP-envelope? That is, the message already contains an SOAP-Envelope and I don't want that the WebserviceTemplate wraps another one around it. :-)</p>
<p>The reason I want this is that I'd like to call a webservice that uses ws-security and do not want to put the ws-security stuff into the WebserviceTemplate, but just want to feed it a message with pre-generated ws-security information in the SOAP-envelope. I tried calling the method <a href="http://static.springsource.org/spring-ws/sites/1.5/apidocs/org/springframework/ws/client/core/WebServiceTemplate.html#sendSourceAndReceiveToResult(java.lang.String,%20javax.xml.transform.Source,%20javax.xml.transform.Result)" rel="nofollow noreferrer">sendSourceAndReceiveToResult</a> with a Source already contains a Soap-Envelope with the WS-Security stuff and the webservice template wraps around another Soap-Envelope and thus destroys the message.</p>
| [
{
"answer_id": 415769,
"author": "Domchi",
"author_id": 29192,
"author_profile": "https://Stackoverflow.com/users/29192",
"pm_score": 3,
"selected": true,
"text": "<bean id=\"webServiceTemplate\" class=\"org.springframework.ws.client.core.WebServiceTemplate\">\n <property name=\"messageFactory\" ref=\"poxMessageFactory\" />\n</bean> \n\n<bean id=\"poxMessageFactory\" class=\"org.springframework.ws.pox.dom.DomPoxMessageFactory\" />\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21499/"
] |
359,625 | <p>Is there a better, more elegant (and/or possibly faster) way than</p>
<pre><code>boolean isNumber = false;
try{
Double.valueOf(myNumber);
isNumber = true;
} catch (NumberFormatException e) {
}
</code></pre>
<p>...?</p>
<hr>
<p><strong>Edit</strong>:
Since I can't pick two answers I'm going with the regex one because a) it's elegant and b) saying "Jon Skeet solved the problem" is a tautology because Jon Skeet himself is the solution to all problems.</p>
| [
{
"answer_id": 359632,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "String.matches(\"^[\\\\d\\\\-\\\\.]+$\");"
},
{
"answer_id": 359634,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "public boolean isDouble(String value)\n{ \n boolean seenDot = false;\n boolean seenExp = false;\n boolean justSeenExp = false;\n boolean seenDigit = false;\n for (int i=0; i < value.length(); i++)\n {\n char c = value.charAt(i);\n if (c >= '0' && c <= '9')\n {\n seenDigit = true;\n continue;\n }\n if ((c == '-' || c=='+') && (i == 0 || justSeenExp))\n {\n continue;\n }\n if (c == '.' && !seenDot)\n {\n seenDot = true;\n continue;\n }\n justSeenExp = false;\n if ((c == 'e' || c == 'E') && !seenExp)\n {\n seenExp = true;\n justSeenExp = true;\n continue;\n }\n return false;\n }\n if (!seenDigit)\n {\n return false;\n }\n try\n {\n Double.parseDouble(value);\n return true;\n }\n catch (NumberFormatException e)\n {\n return false;\n }\n}\n"
},
{
"answer_id": 359645,
"author": "Nick Holt",
"author_id": 41423,
"author_profile": "https://Stackoverflow.com/users/41423",
"pm_score": 2,
"selected": false,
"text": "StringUtils.isDouble(String)"
},
{
"answer_id": 359674,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "String.matches(\"^-?\\\\d+(\\\\.\\\\d+)?$\");\n"
},
{
"answer_id": 359845,
"author": "Ran Biron",
"author_id": 931,
"author_profile": "https://Stackoverflow.com/users/931",
"pm_score": 3,
"selected": false,
"text": "NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);\nNumber myNumber = nf.parse(myString);\nint myInt = myNumber.intValue();\ndouble myDouble = myNumber.doubleValue();\n"
},
{
"answer_id": 359860,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "private boolean IsValidDoubleChar(char c)\n{\n return \"0123456789.+-eE\".indexOf(c) >= 0;\n}\n\npublic boolean isDouble(String value)\n{\n for (int i=0; i < value.length(); i++)\n {\n char c = value.charAt(i);\n if (IsValidDoubleChar(c))\n continue;\n return false;\n }\n try\n {\n Double.parseDouble(value);\n return true;\n }\n catch (NumberFormatException e)\n {\n return false;\n }\n}\n"
},
{
"answer_id": 363249,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 3,
"selected": false,
"text": " final String Digits = \"(\\\\p{Digit}+)\";\n final String HexDigits = \"(\\\\p{XDigit}+)\";\n // an exponent is 'e' or 'E' followed by an optionally \n // signed decimal integer.\n final String Exp = \"[eE][+-]?\"+Digits;\n final String fpRegex =\n (\"[\\\\x00-\\\\x20]*\"+ // Optional leading \"whitespace\"\n \"[+-]?(\" + // Optional sign character\n \"NaN|\" + // \"NaN\" string\n \"Infinity|\" + // \"Infinity\" string\n\n // A decimal floating-point string representing a finite positive\n // number without a leading sign has at most five basic pieces:\n // Digits . Digits ExponentPart FloatTypeSuffix\n // \n // Since this method allows integer-only strings as input\n // in addition to strings of floating-point literals, the\n // two sub-patterns below are simplifications of the grammar\n // productions from the Java Language Specification, 2nd \n // edition, section 3.10.2.\n\n // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt\n \"(((\"+Digits+\"(\\\\.)?(\"+Digits+\"?)(\"+Exp+\")?)|\"+\n\n // . Digits ExponentPart_opt FloatTypeSuffix_opt\n \"(\\\\.(\"+Digits+\")(\"+Exp+\")?)|\"+\n\n // Hexadecimal strings\n \"((\" +\n // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt\n \"(0[xX]\" + HexDigits + \"(\\\\.)?)|\" +\n\n // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt\n \"(0[xX]\" + HexDigits + \"?(\\\\.)\" + HexDigits + \")\" +\n\n \")[pP][+-]?\" + Digits + \"))\" +\n \"[fFdD]?))\" +\n \"[\\\\x00-\\\\x20]*\");// Optional trailing \"whitespace\"\n\n if (Pattern.matches(fpRegex, myString))\n Double.valueOf(myString); // Will not throw NumberFormatException\n else {\n // Perform suitable alternative action\n }\n"
},
{
"answer_id": 368416,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "package tias;\n\npublic class Main {\n private static final String NUMERIC = \"123456789\";\n private static final String NOT_NUMERIC = \"1L5C\";\n\n public static void main(String[] args) {\n System.out.println(isStringNumeric(NUMERIC));\n System.out.println(isStringNumeric(NOT_NUMERIC));\n }\n\n private static boolean isStringNumeric(String aString) {\n if (aString == null || aString.length() == 0) {\n return false;\n }\n for (char c : aString.toCharArray() ) {\n if (!Character.isDigit(c)) {\n return false;\n }\n }\n return true;\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
359,633 | <p>Is it best practice to wrap a web service method/call into a try/catch block?</p>
<p>I don't web service requests tend to be the reason why the .NET desktop applications crash? So I was thinking all calls should be wrapped in try/catch to prevent this.</p>
<p>Good idea?</p>
<p>Also, should it throw an exception or just have an empty catch?</p>
| [
{
"answer_id": 359710,
"author": "Maghis",
"author_id": 45355,
"author_profile": "https://Stackoverflow.com/users/45355",
"pm_score": 2,
"selected": false,
"text": "#if !DEBUG\ncatch (Exception ex)\n{\n // show messagebox, log, etc\n}\n#endif\n"
},
{
"answer_id": 4593824,
"author": "rumplin",
"author_id": 562568,
"author_profile": "https://Stackoverflow.com/users/562568",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.ServiceModel;\nusing Entities; //my entities\nusing AuthenticationService; //my webservice reference\n\nnamespace Application.SL.Model\n{\n public class AuthenticationServiceHelper\n {\n /// <summary>\n /// User log in\n /// </summary>\n /// <param name=\"callback\"></param>\n public void UserLogIn(Action<C48PR01IzhodOut, Exception> callback)\n {\n var proxy = new AuthenticationServiceClient();\n\n try\n {\n proxy.UserLogInCompleted += (sender, eventargs) =>\n {\n var userCallback = eventargs.UserState as Action<C48PR01IzhodOut, Exception>;\n if (userCallback == null)\n return;\n\n if (eventargs.Error != null)\n {\n userCallback(null, eventargs.Error);\n return;\n }\n userCallback(eventargs.Result, null);\n };\n proxy.UserLogInAsync(callback);\n }\n catch (Exception ex)\n {\n proxy.Abort();\n ErrorHelper.WriteErrorLog(ex.ToString());\n }\n finally\n {\n if (proxy.State != CommunicationState.Closed)\n {\n proxy.CloseAsync();\n }\n }\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] |
359,635 | <p>What's the best way to implement a classic curry function in actionscript with a nice syntax?</p>
<p>I've tried:</p>
<pre><code>Function.prototype.curry = function()
{
return "helloWorld";
}
trace((function():void {}).curry());
</code></pre>
<p>...approach but that didn't work. </p>
<p>I guess I'm stuck with a ugly approach such as:</p>
<pre><code>FunctionUtils.curry(fp, ... args)
</code></pre>
<p>???</p>
| [
{
"answer_id": 359774,
"author": "Niels Bosma",
"author_id": 40939,
"author_profile": "https://Stackoverflow.com/users/40939",
"pm_score": 1,
"selected": false,
"text": "public static function curry(func:Function, ... args:Array):*\n{\n var arity:int = func.length;\n var currying:Function = function(func:Function, arity:int, args:Array):*\n {\n return function(... moreArgs:Array):* {\n if(moreArgs.length + args.length < arity)\n {\n return currying(func, arity, args.concat(moreArgs));\n }\n return func.apply(this, args.concat(moreArgs));\n }\n }\n return currying(func, arity, args);\n}\n function foo(i:int, j:int):void\n{\n trace(i+j);\n}\n\nfunction bar(fp:Function):void\n{\n fp(2);\n}\n\nbar(FunctionUtils.curry(foo, 1)); //trace==3\n"
},
{
"answer_id": 365357,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": true,
"text": "package {\n public function partial( func : Function, ...boundArgs ) : Function {\n return function( ...dynamicArgs ) : * {\n return func.apply(null, boundArgs.concat(dynamicArgs))\n }\n }\n}\n var multiply : Function = function( a : Number, b : Number ) : Number { return a * b; }\nvar multiplyByFour : Function = partial(multiply, 4);\n\ntrace(multiplyByFour(3)); // => 12\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40939/"
] |
359,656 | <p>We are trying to develop an application to view and annotate PDF files in ASP.net. </p>
<p>The function involves capturing x,y coordinates from a click and placing the annotation on that specific location.</p>
<p>Are there available components to do this?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 359774,
"author": "Niels Bosma",
"author_id": 40939,
"author_profile": "https://Stackoverflow.com/users/40939",
"pm_score": 1,
"selected": false,
"text": "public static function curry(func:Function, ... args:Array):*\n{\n var arity:int = func.length;\n var currying:Function = function(func:Function, arity:int, args:Array):*\n {\n return function(... moreArgs:Array):* {\n if(moreArgs.length + args.length < arity)\n {\n return currying(func, arity, args.concat(moreArgs));\n }\n return func.apply(this, args.concat(moreArgs));\n }\n }\n return currying(func, arity, args);\n}\n function foo(i:int, j:int):void\n{\n trace(i+j);\n}\n\nfunction bar(fp:Function):void\n{\n fp(2);\n}\n\nbar(FunctionUtils.curry(foo, 1)); //trace==3\n"
},
{
"answer_id": 365357,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": true,
"text": "package {\n public function partial( func : Function, ...boundArgs ) : Function {\n return function( ...dynamicArgs ) : * {\n return func.apply(null, boundArgs.concat(dynamicArgs))\n }\n }\n}\n var multiply : Function = function( a : Number, b : Number ) : Number { return a * b; }\nvar multiplyByFour : Function = partial(multiply, 4);\n\ntrace(multiplyByFour(3)); // => 12\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,657 | <p>I've use Moq to mock my <a href="http://martinfowler.com/eaaCatalog/repository.html" rel="nofollow noreferrer">repositories</a>. However, someone recently said that they prefer to create hard-coded test implementations of their repository interfaces.</p>
<p>What are the pros and cons of each approach?</p>
<p><strong>Edit:</strong> clarified meaning of repository with link to Fowler.</p>
| [
{
"answer_id": 359692,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "public interface UserDao {\n User getUser(int userid);\n User getUser(String login);\n}\n\npublic class InMemoryUserDao implements UserDao {\n\n private List users;\n\n public InMemoryUserDao(List users) {\n this.users = users;\n }\n\n public User getUser(int userid) {\n for (Iterator it = users.iterator(); it.hasNext();) {\n User user = (User) it.next();\n if (userid == user.getId()) {\n return user;\n }\n }\n\n return null;\n }\n\n public User getUser(String login) {\n for (Iterator it = users.iterator(); it.hasNext();) {\n User user = (User) it.next();\n if (login.equals(user.getLogin())) {\n return user;\n }\n }\n\n return null;\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43649/"
] |
359,660 | <p>I have an xml string </p>
<pre><code><grandparent>
<parent>
<child>dave</child>
<child>laurie</child>
<child>gabrielle</child>
</parent>
</grandparrent>
</code></pre>
<p>What I want to get is the data raw xml that's inside the parent.
I'm using MSXML </p>
<pre><code>iXMLElm->get_xml(&bStr);
</code></pre>
<p>is returning</p>
<pre><code><parent>
<child>dave</child>
<child>laurie</child>
<child>gabrielle</child>
</parent>
</code></pre>
<p>.</p>
<pre><code>iXMLElm->get_text(&bStr);
</code></pre>
<p>returns
davelauriegabrielle</p>
<p><strong>What function do I use if I want to get?</strong> </p>
<pre><code><child>dave</child>
<child>laurie</child>
<child>gabrielle</child>
</code></pre>
<p>Is anyone aware of some good documentation on these functions? Everything I've seen is a linked nightmare. </p>
| [
{
"answer_id": 361142,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 0,
"selected": false,
"text": "iXMLElm iXMLElm->get_firstChild(&iXMLChildElm)\n iXMLChildElm->get_xml(&bStr)\n child grandparent selectSingleNode"
},
{
"answer_id": 6261202,
"author": "psp",
"author_id": 724917,
"author_profile": "https://Stackoverflow.com/users/724917",
"pm_score": -1,
"selected": false,
"text": "HRESULT getAttribute(\n BSTR name,\n VARIANT *value);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31325/"
] |
359,672 | <p>Is there a way other than looping through the Files in a SPFolder to determine if a give filename (string) exists?</p>
| [
{
"answer_id": 363869,
"author": "Lars Fastrup",
"author_id": 27393,
"author_profile": "https://Stackoverflow.com/users/27393",
"pm_score": 6,
"selected": true,
"text": "using (SPSite site = new SPSite(\"http://server/site\"))\nusing (SPWeb web = site.OpenWeb())\n{\n SPFile file = web.GetFile(\"/site/doclib/folder/filename.ext\");\n if (file.Exists)\n {\n ...\n }\n}\n"
},
{
"answer_id": 8011028,
"author": "Ben",
"author_id": 1029887,
"author_profile": "https://Stackoverflow.com/users/1029887",
"pm_score": 3,
"selected": false,
"text": "using(var clientContext = new ClientContext(site))\n{\n Web web = clientContext.Web;\n Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(\"/site/doclib/folder/filename.ext\");\n bool bExists = false;\n try\n {\n clientContext.Load(file);\n clientContext.ExecuteQuery(); //Raises exception if the file doesn't exist\n bExists = file.Exists; //may not be needed - here for good measure\n }\n catch{ }\n\n if (bExists )\n {\n .\n .\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7001/"
] |
359,675 | <h2>Goal</h2>
<p>Java client for Yahoo's HotJobs <a href="http://developer.yahoo.com/hotjobs/resume_search_user_guide/index.html" rel="nofollow noreferrer">Resumé Search REST API</a>. </p>
<h2>Background</h2>
<p>I'm used to writing web-service clients for SOAP APIs, where <a href="https://jax-ws.dev.java.net/jax-ws-ea3/docs/wsimport.html" rel="nofollow noreferrer">wsimport</a> generates proxy stubs and you're off and running. But this is a REST API, which is new to me.</p>
<h2>Details</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" rel="nofollow noreferrer">REST</a> API</li>
<li>No <a href="http://en.wikipedia.org/wiki/Web_Application_Description_Language" rel="nofollow noreferrer">WADL</a></li>
<li>No formal XML schema (XSD or DTD files). There are <a href="http://developer.yahoo.com/hotjobs/resume_search_user_guide/auth.html" rel="nofollow noreferrer">example XML request/response pairs</a>.</li>
<li>No example code provided</li>
</ul>
<h2>Progress</h2>
<p>I looked at question <a href="https://stackoverflow.com/questions/221442/rest-clients-for-java">Rest clients for Java?</a>, but the automated solutions there assume you are providing both the server and the client, with JAXB invoked on POJOs to generate a schema and a REST API.</p>
<p>Using <a href="http://jersey.java.net/" rel="nofollow noreferrer">Jersey</a> (a <a href="http://jcp.org/en/jsr/detail?id=311" rel="nofollow noreferrer">JAX-RS</a> implementation), I have been able to make a manual HTTP request:</p>
<pre><code>import com.sun.jersey.api.client.*;
...
ClientConfig clientConfig = new DefaultClientConfig();
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("https://hj.yahooapis.com/v1/HJAuthTokens");
webResource.accept("application/xml");
// body is a hard-coded string, with replacements for the variable bits
String response = webResource.post(String.class, body);
// parse response into a org.w3c.dom.Document
// interface with Document via XPATH, or write my own POJO mappings
</code></pre>
<p>The response can look like:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Response>
<ResponseCode>0</ResponseCode>
<ResponseMessage>Login successful</ResponseMessage>
<Token>NTlEMTdFNjk3Qjg4NUJBNDA3MkJFOTI3NzJEMTdDNDU7bG9jYWxob3N0LmVnbGJwLmNvcnAueWFob28uY29tO0pVNWpzRGRhN3VhSS4yQVRqRi4wWE5jTWl0RHVVYzQyX3luYWd1TjIxaGx6U0lhTXN3LS07NjY2MzM1OzIzNDY3NTsxMjA5MDE2OTE5OzZCM1RBMVNudHdLbl9VdFFKMFEydWctLQ==</Token>
</Response>
</code></pre>
<p>Or, it can look like:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<yahoo:error xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" xml:lang="en-US">
<yahoo:description>description</yahoo:description>
<yahoo:detail>
<ErrorCode>errorCode</ErrorCode>
</yahoo:detail>
</yahoo:error>
</code></pre>
<h2>Questions</h2>
<ul>
<li>Is there a way to auto-generate <a href="http://en.wikipedia.org/wiki/POJO" rel="nofollow noreferrer">POJOs</a> which can be marshalled/unmarshalled without a formal schema? </li>
<li>Should I attempt to generate those POJOs by hand, with <a href="http://jaxb.java.net/" rel="nofollow noreferrer">JAXB</a> annotations?</li>
<li><strong><em>Is there some tool I should be leveraging so I don't have to do all this manually?</em></strong></li>
</ul>
| [
{
"answer_id": 597248,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 2,
"selected": false,
"text": "@XmlRootElement(\"Response\")\nclass Response {\n public int responseCode;\n public String responseMessage;\n public String token; // or perhaps byte[] works for automated base64?\n}\n"
},
{
"answer_id": 24474313,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 0,
"selected": false,
"text": "JdkRequest String body = new JdkRequest(\"http://www.google.com\")\n .header(\"User-Agent\", \"it's me\")\n .fetch()\n .body()\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7679/"
] |
359,699 | <p>I want to pass an enum value as command parameter in WPF, using something like this:</p>
<pre><code><Button
x:Name="uxSearchButton"
Command="{Binding Path=SearchMembersCommand}"
CommandParameter="SearchPageType.First"
Content="Search">
</Button>
</code></pre>
<p><code>SearchPageType</code> is an enum and this is to know from which button search command is invoked.</p>
<p>Is this possible in WPF, or how can you pass an enum value as command parameter?</p>
| [
{
"answer_id": 360076,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 9,
"selected": true,
"text": "<Button CommandParameter=\"{x:Static local:SearchPageType.First}\" .../>\n local"
},
{
"answer_id": 360639,
"author": "Robert Macnee",
"author_id": 19273,
"author_profile": "https://Stackoverflow.com/users/19273",
"pm_score": 6,
"selected": false,
"text": "<Button x:Name=\"uxSearchButton\"\n Command=\"{Binding Path=SearchMembersCommand}\"\n Content=\"Search\">\n <Button.CommandParameter>\n <SearchPageType>First</SearchPageType>\n </Button.CommandParameter>\n</Button>\n"
},
{
"answer_id": 4352112,
"author": "tbergelt",
"author_id": 321481,
"author_profile": "https://Stackoverflow.com/users/321481",
"pm_score": 8,
"selected": false,
"text": "+ <Button CommandParameter=\"{x:Static local:MyOuterType+SearchPageType.First}\".../>\n"
},
{
"answer_id": 25440213,
"author": "hartmape",
"author_id": 2281877,
"author_profile": "https://Stackoverflow.com/users/2281877",
"pm_score": 5,
"selected": false,
"text": "Flags <Button>\n <Button.CommandParameter>\n <SearchPageType>First,Second</SearchPageType>\n <Button.CommandParameter>\n</Button>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45382/"
] |
359,706 | <p>I'm using PIL (Python Imaging Library). I'd like to draw transparent polygons. It seems that specifying a fill color that includes alpha level does not work. Are their workarounds?</p>
<p>If it can't be done using PIL I'm willing to use something else.</p>
<p>If there is more than one solution, then performance should be factored in. The drawing needs to be as fast as possible.</p>
| [
{
"answer_id": 433638,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 3,
"selected": false,
"text": "color_layer = Image.new('RGBA', base_layer.size, fill_rgb)\nalpha_mask = Image.new('L', base_layer.size, 0)\nalpha_mask_draw = ImageDraw.Draw(alpha_mask)\nalpha_mask_draw.polygon(self.outline, fill=fill_alpha)\nbase_layer = Image.composite(color_layer, base_layer, alpha_mask)\n"
},
{
"answer_id": 9686308,
"author": "ivy",
"author_id": 193886,
"author_profile": "https://Stackoverflow.com/users/193886",
"pm_score": 0,
"selected": false,
"text": "(255,255,255,0) image = Image.new(\"RGBA\", (100,100))\ndrawing = ImageDraw.Draw(i)\nfor index, p in enumerate(polygons):\n if index == 0:\n options = { 'fill': \"#AA5544\",\n 'outline': \"#993300\"}\n else:\n options = {'fill': (255,255,255,0)}\n drawing.polygon( p, **options )\n\nbuf= StringIO.StringIO()\ni.save(buf, format= 'PNG')\n# do something with buf\n"
},
{
"answer_id": 10555216,
"author": "Matt Campbell",
"author_id": 1389862,
"author_profile": "https://Stackoverflow.com/users/1389862",
"pm_score": 1,
"selected": false,
"text": " MIN_ALPHA = 50\n MAX_ALPHA = 100\n\n WIDTH = 500\n HEIGHT = 250\n\n #\n # Utilities\n #\n def hex2tuple(hex_color):\n return tuple([int(hex_color[i:i+2], 16) for i in range(1,9,2)])\n\n def tuple2hex(tuple_color):\n return \"#%0.2X%0.2X%0.2X%0.2X\" % tuple_color\n\n def ints2floats(tuple_color):\n return tuple([c / 255.0 for c in tuple_color])\n\n def inc_point(p, dp):\n return (p[0] + dp[0]) % WIDTH, (p[1] + dp[1]) % HEIGHT\n\n def inc_triangle(t, dt):\n return tuple([inc_point(t[i], dt[i]) for i in range(3)])\n\n def inc_color(c, dc):\n new_c = [(c[i] + dc[i]) % 256 for i in range(3)]\n new_a = (c[3] + dc[3]) % MAX_ALPHA\n if new_a < MIN_ALPHA: new_a += MIN_ALPHA\n new_c.append(new_a)\n return tuple(new_c)\n\n def draw_all(draw_fn):\n triangle = start_t\n color = start_c\n for i in range(50):\n triangle = inc_triangle(triangle, dt)\n color = inc_color(color, dc)\n draw_fn(triangle, color)\n\n #\n # Starting and incrementing values\n #\n start_c = hex2tuple('E6A20644')\n start_t = (127, 132), (341, 171), (434, 125)\n dt = (107, 23), (47, 73), (13, 97)\n dc = 61, 113, 109, 41\n from random_polys_util import *\n\ndef cairo_poly(pts, clr):\n ctx.set_source_rgba(*ints2floats(clr))\n ctx.move_to(*pts[-1])\n for pt in pts:\n ctx.line_to(*pt)\n ctx.close_path()\n ctx.fill()\n\ndef cairo_main():\n # Setup Cairo\n import cairo\n global ctx\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)\n ctx = cairo.Context(surface)\n # fill background white\n cairo_poly(((0,0),(WIDTH,0),(WIDTH,HEIGHT),(0,HEIGHT)),(255,255,255,255))\n draw_all(cairo_poly)\n surface.write_to_png('cairo_example.png')\n\ndef main():\n cairo_main()\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"answer_id": 21768191,
"author": "Matt",
"author_id": 3308255,
"author_profile": "https://Stackoverflow.com/users/3308255",
"pm_score": 6,
"selected": false,
"text": "from PIL import Image, ImageDraw\n\nimg = Image.new('RGB', (100, 100))\ndrw = ImageDraw.Draw(img, 'RGBA')\ndrw.polygon(xy=[(50, 0), (100, 100), (0, 100)], fill=(255, 0, 0, 125))\ndrw.polygon(xy=[(50, 100), (100, 0), (0, 0)], fill=(0, 255, 0, 125))\ndel drw\n\nimg.save('out.png', 'PNG')\n"
},
{
"answer_id": 62066751,
"author": "tsveti_iko",
"author_id": 4137497,
"author_profile": "https://Stackoverflow.com/users/4137497",
"pm_score": 2,
"selected": false,
"text": "import cv2\nimport numpy as np\nfrom shapely.geometry import Polygon\n\nalpha = 0.5 # that's your transparency factor\npath = 'path_to_image.jpg'\nimage = cv2.imread(path)\n(H, W) = image.shape[:2]\n\nxmin = 0\nymin = 0 \nxmax = int(W / 2)\nymax = int(H / 2)\n\npolygon = Polygon([(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)])\nint_coords = lambda x: np.array(x).round().astype(np.int32)\nexterior = [int_coords(polygon.exterior.coords)]\n\noverlay = image.copy()\ncv2.fillPoly(overlay, exterior, color=(255, 255, 0))\ncv2.addWeighted(overlay, alpha, image, 1 - alpha, 0, image)\ncv2.imshow(\"Polygon\", image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498/"
] |
359,707 | <p>I've done most of my work on VisualStudio and don't have much experience with gcc or g++. When I tried to compile a (ex. aprogram.cpp) this morning on my pc using cygwin, I got (aprogram.exe) when I tried to compile the same thing on my Ubuntu box I got (aprogram) w/o any extension. I am just wondering if someone be kind enough to tell me why. This question is just out of curiosity. :)</p>
<p>Thanks in advance!</p>
<p>EDIT:
(from Jimmy's comment)
g++ under Cygwin defaults to .exe </p>
| [
{
"answer_id": 359714,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 4,
"selected": false,
"text": "-o a.out"
},
{
"answer_id": 359726,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 2,
"selected": false,
"text": "./aprogram\n"
},
{
"answer_id": 411991,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "cat.bin file.txt | less.bin\n 7f 45 4c 46"
},
{
"answer_id": 11941351,
"author": "Camilo Martin",
"author_id": 124119,
"author_profile": "https://Stackoverflow.com/users/124119",
"pm_score": 1,
"selected": false,
"text": ".elf $ file MyFile\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41104/"
] |
359,722 | <p>I own a website and I wonder if there is a script that get files for me from other links on the net a load it to my server.</p>
<p>Suppose I found a file with a size of 400 mb, I want to host it on my server. The normal way I used is to download the file to my pc then upload it to my server but is there a script or a way to transfer and host the file directly without downloading it.</p>
| [
{
"answer_id": 359749,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 2,
"selected": true,
"text": "<?php\n$remotefh = fopen('http://domain.tld/path/to/file.ext', 'r'); \n$localfh = fopen('local/file.ext', 'w');\nwhile(!feof($remotefh)) \n {\n fwrite($localfh, fread($remotefh, '4096'));\n }\nfclose($remotefh);\nfclose($localfh);\n?>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,727 | <p>I've run into strange problem in my Flex/Flashcom application. If client application unexpectedly disconnects from server latter does not call application.onDisconnect handler function. In witch direction should I look? Thank you.</p>
<p><strong>Update</strong> I'm not using server components, but I do host this thing on Linux.</p>
| [
{
"answer_id": 486543,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "onConnectAccept onConnectReject application.onConnect application.onConnectAccept application.onConnectReject onConnect application.acceptConnection() application.rejectConnection() acceptConnection() rejectConnection() application.onConnectAccept application.onConnectReject application.onConnectAccept application.onConnectReject Error #2044: NetStatusEvent non pris en charge : level=error, code=NetStream.Play.Failed\n at MethodInfo-1()\nError #2044: NetStatusEvent non pris en charge : level=error, code=NetStream.Record.NoAccess\n at MethodInfo-1()\n var status:Function = function( e:NetStatusEvent ):void\n{\n trace( \"status : \" + e.info.code ) ;\n if ( e.info.code == \"NetConnection.Connect.Success\" )\n {\n streamOut = new NetStream( nc ) ;\n streamOut.addEventListener( NetStatusEvent.NET_STATUS , status ) ;\n \n streamIn = new NetStream( nc ) ;\n streamIn.addEventListener( NetStatusEvent.NET_STATUS , status ) ;\n \n streamOut.attachCamera( cam ) ;\n video.attachNetStream( streamIn ) ;\n \n streamOut.publish( \"private\" ) ;\n streamIn.play( \"private\" ) ; \n }\n}\n"
},
{
"answer_id": 501826,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 2,
"selected": false,
"text": "// add method to standard class\nClient.prototype.isAlive = function() {\n var stats = this.getStats();\n var timeout_value = 3 * 1000; // in ms.\n //trace('Measured timeout: ' + stats['ping_rtt']);\n if (stats)\n return (stats['ping_rtt'] < timeout_value);\n}\n\n// use this in an interval which traverses the application.clients list\nif (! client.isAlive())\n application.disconnect(client);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] |
359,732 | <p>Why does everyone tell me writing code like this is a bad practice?</p>
<pre><code>if (foo)
Bar();
//or
for(int i = 0 i < count; i++)
Bar(i);
</code></pre>
<p>My biggest argument for omitting the curly braces is that it can sometimes be twice as many lines with them. For example, here is some code to paint a glow effect for a label in C#.</p>
<pre><code>using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
{
for (int x = 0; x <= GlowAmount; x++)
{
for (int y = 0; y <= GlowAmount; y++)
{
g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
}
}
}
//versus
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
for (int x = 0; x <= GlowAmount; x++)
for (int y = 0; y <= GlowAmount; y++)
g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
</code></pre>
<p>You can also get the added benefit of chaining <code>usings</code> together without having to indent a million times.</p>
<pre><code>using (Graphics g = Graphics.FromImage(bmp))
{
using (Brush brush = new SolidBrush(backgroundColor))
{
using (Pen pen = new Pen(Color.FromArgb(penColor)))
{
//do lots of work
}
}
}
//versus
using (Graphics g = Graphics.FromImage(bmp))
using (Brush brush = new SolidBrush(backgroundColor))
using (Pen pen = new Pen(Color.FromArgb(penColor)))
{
//do lots of work
}
</code></pre>
<hr>
<p>The most common argument for curly braces revolves around maintance programming, and the problems that would ensue by inserting code between the original if statement and its intended result:</p>
<pre><code>if (foo)
Bar();
Biz();
</code></pre>
<hr>
<h3>Questions:</h3>
<ol>
<li>Is it wrong to want to use the more compact syntax which the language offers? The people that design these languages are smart, I can't imagine they would put a feature which is always bad to use.</li>
<li>Should we or Shouldn't we write code so the lowest common denominator can understand and have no problems working with it? </li>
<li>Is there another argument that I'm missing?</li>
</ol>
| [
{
"answer_id": 359747,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 3,
"selected": false,
"text": "if (foo)\n bar();\n if (foo)\n snafu();\n bar();\n"
},
{
"answer_id": 359750,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 1,
"selected": false,
"text": "if(foo)\nbar();\nbar(delete);\n if(foo) {\nbar();\n}\n bar(delete);\n"
},
{
"answer_id": 359752,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": false,
"text": "if(x == y)\n for(/* loop */)\n {\n //200 lines\n }\n\n//rampion's example:\nfor(/* loop */)\n{\n for(/* loop */)\n for(/* loop */)\n {\n //several lines\n }\n}\n"
},
{
"answer_id": 359753,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 9,
"selected": true,
"text": "if(foo)\n // bar();\ndoSomethingElse();\n if(foo) bar();\n"
},
{
"answer_id": 359754,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "if (...)\n foo();\n bar();\n"
},
{
"answer_id": 359762,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 3,
"selected": false,
"text": "for if for (...)\n{\n for (...)\n for (...) \n {\n // a couple pages of code\n }\n // which for block is ending here? A good text editor will tell you, \n // but it's not obvious when you're reading the code\n}\n"
},
{
"answer_id": 359771,
"author": "Nathan Prather",
"author_id": 44595,
"author_profile": "https://Stackoverflow.com/users/44595",
"pm_score": 3,
"selected": false,
"text": "if (...) {\n foo();\n bar();\n}\nelse {\n ...\n}\n"
},
{
"answer_id": 359776,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 3,
"selected": false,
"text": "if ( foo == 0 ) if ( 0 == foo )"
},
{
"answer_id": 359784,
"author": "Liggy",
"author_id": 32142,
"author_profile": "https://Stackoverflow.com/users/32142",
"pm_score": 3,
"selected": false,
"text": "if (foo)\n snafu();\n bar();\n if (foo) snafu();\n"
},
{
"answer_id": 359787,
"author": "Adam Jaskiewicz",
"author_id": 35322,
"author_profile": "https://Stackoverflow.com/users/35322",
"pm_score": 6,
"selected": false,
"text": "if(foo()) bar();"
},
{
"answer_id": 359789,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 5,
"selected": false,
"text": "if (condition) action(); // ok by me\n\nif (condition) // normal/standard for me\n{\n action();\n}\n"
},
{
"answer_id": 359794,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 1,
"selected": false,
"text": "if ( any ) {\n DoSomething();\n}\n if ( any ) { DoSomething(); }\n if ( any ) {\n DoSomething(); }\nif ( any )\n { DoSomething(); }\n"
},
{
"answer_id": 359805,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 1,
"selected": false,
"text": "if (foo)\n bar();\n if (foo)\n bar()\nelse\n snafu();\n if (foo)\n bar();\n snafu();\n if (foo)\n if (bar)\n snafu()\n if (foo) {\n if (bar)\n snafu()\n}\n"
},
{
"answer_id": 359839,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": -1,
"selected": false,
"text": "if(DoSomething)\n MyClass myClass = new MyClass();\n\nmyClass.DoAnythingElse();\n if(doSomething)\n{\n MyClass myClass = new MyClass();\n}\n\nmyClass.DoAnythingElse();\n"
},
{
"answer_id": 359862,
"author": "Maghis",
"author_id": 45355,
"author_profile": "https://Stackoverflow.com/users/45355",
"pm_score": 5,
"selected": false,
"text": "if (something)\n just one statement; // i find this ugly\nelse\n{\n // many\n // lines\n // of code\n}\n if (something)\n{\n just one statement; // looks better:)\n}\nelse\n{\n // many\n // lines\n // of code\n}\n"
},
{
"answer_id": 359886,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 4,
"selected": false,
"text": "#define BADLY_MADE_MACRO(x) function1(x); function2(x);\n\nif (myCondition) BADLY_MADE_MACRO(myValue)\n"
},
{
"answer_id": 359902,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 2,
"selected": false,
"text": "if( some_condition ) { do_some_operation; }\n if( some_condition )\n{\n do_some_operation;\n}\n"
},
{
"answer_id": 359930,
"author": "Ironsides",
"author_id": 44785,
"author_profile": "https://Stackoverflow.com/users/44785",
"pm_score": 0,
"selected": false,
"text": "if(this == yes)\n DoSomething();\n if(this == yes)\n{\n DoSomething();\n}\n"
},
{
"answer_id": 359948,
"author": "FredV",
"author_id": 30829,
"author_profile": "https://Stackoverflow.com/users/30829",
"pm_score": 6,
"selected": false,
"text": "if(a)\n if(b)\n c();\nelse\n d();\n"
},
{
"answer_id": 360002,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": -1,
"selected": false,
"text": "(!a) ? Foo() : Bar();\n"
},
{
"answer_id": 360011,
"author": "Chris McAtackney",
"author_id": 5827,
"author_profile": "https://Stackoverflow.com/users/5827",
"pm_score": 3,
"selected": false,
"text": "if(x < y)\n x = y;\nelse\n y = x;\n if(x < y)\n{\n x = y;\n x++;\n}\nelse\n{\n y = x;\n y++;\n}\n"
},
{
"answer_id": 360012,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "if (foo)\n{\n // Lot of code\n}\nelse\n DoStuff();\n if (somethingBadHappened)\n return;\n"
},
{
"answer_id": 360963,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 4,
"selected": false,
"text": "if (condition) Foo(); // normal, everyday code\n\nif (condition) \n{\n // something non-trivial hapening; pay attention!\n Foo();\n Bar();\n}\n"
},
{
"answer_id": 361103,
"author": "Chris",
"author_id": 34942,
"author_profile": "https://Stackoverflow.com/users/34942",
"pm_score": 0,
"selected": false,
"text": "for (int i=0; i<10; i++) \n{\n for (int x=0; x<20; x++) \n {\n if (someBoolValue)\n DoThis(x,y);\n }\n}\n using (Stream x = File.Open(...)) \n{\n using (Stream y = File.Create(...)) \n {\n ...\n }\n}\n using (Stream x = File.Open(...))\nusing (Stream y = File.Create(...)) \n{\n ....\n}\n"
},
{
"answer_id": 361238,
"author": "RobH",
"author_id": 21255,
"author_profile": "https://Stackoverflow.com/users/21255",
"pm_score": 0,
"selected": false,
"text": "if (something)\n {\n for (i = 0; i < count; i++)\n {\n foo();\n }\n }\n if (something\n for (i = 0; i < count; i++)\n foo();\n if (something)\n{ for (i = 0; i < count; i++)\n { foo();\n }\n}\n"
},
{
"answer_id": 361280,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "if(addCurleyBraces()) bugFreeSofware.hooray();\n if(addCurleyBraces())\n bugFreeSofware.hooray();\n if(addCurleyBraces()) {\n bugFreeSofware.hooray();\n}\n"
},
{
"answer_id": 361327,
"author": "CrashCodes",
"author_id": 16260,
"author_profile": "https://Stackoverflow.com/users/16260",
"pm_score": 7,
"selected": false,
"text": "if (condition)\n{\n DoSomething();\n}\n\nDoSomethingElse();\n if (condition) DoSomething();\n\nDoSomethingElse();\n if (condition) DoSomething();\nDoSomethingElse();\n if (condition) \n DoSomething();\nDoSomethingElse();\n if (condition)\n{\n DoSomething();\n DoSomethingElse();\n}\n if (condition) \n DoSomething();\n DoSomethingElse();\n"
},
{
"answer_id": 361368,
"author": "Aistina",
"author_id": 37472,
"author_profile": "https://Stackoverflow.com/users/37472",
"pm_score": 1,
"selected": false,
"text": "if (condition1)\nif (condition2)\ndoSomething();\nelse\ndoSomethingElse();\n"
},
{
"answer_id": 361472,
"author": "Steve Melnikoff",
"author_id": 45552,
"author_profile": "https://Stackoverflow.com/users/45552",
"pm_score": 2,
"selected": false,
"text": "if(foo)\n {DoSomething();}\n"
},
{
"answer_id": 363308,
"author": "user45425",
"author_id": 45425,
"author_profile": "https://Stackoverflow.com/users/45425",
"pm_score": -1,
"selected": false,
"text": "if( foo )\n bar();\n"
},
{
"answer_id": 365723,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "if (foo)\n bar();\n if (foo)\n bar();\n baz();\n if (foo) {\n bar();\n baz();\n}\n if (foo) {\n bar();\n baz();\n} else {\n qux();\n}\n"
},
{
"answer_id": 588831,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 4,
"selected": false,
"text": " if( debugEnabled ) \n println( \"About to save 1 day of work to some very important place.\");\n saveDayData();\n if( debugEnabled ) \n // println( \"About to save 1 day of work to some very important place.\");\n saveDayData();\n if( object != null ) try { \n object.close();\n} catch( .....\n"
},
{
"answer_id": 1015869,
"author": "stone",
"author_id": 37168,
"author_profile": "https://Stackoverflow.com/users/37168",
"pm_score": 3,
"selected": false,
"text": "if (foo) bar();\n if (foo)\n{\n bar(); //It is easy to put a breakpoint here, and that is useful.\n}\n"
},
{
"answer_id": 1020035,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 0,
"selected": false,
"text": "if (mybool)\n{\n doMyStuff();\n}\nelse\n{\n doMyOtherStuff();\n checkStuff();\n}\n if (mybool) {\n doMyStuff();\n}\nelse {\n doMyOtherStuff();\n checkStuff();\n}\n if (mybool)\n doMyStuff(); \n else \n { \n doMyOtherStuff();\n checkStuff(); \n }\n"
},
{
"answer_id": 5739489,
"author": "Ozzah",
"author_id": 597755,
"author_profile": "https://Stackoverflow.com/users/597755",
"pm_score": 4,
"selected": false,
"text": "foreach (Foo f in foos)\n foreach (Bar b in bars)\n if (f.Equals(b))\n return true;\n\nreturn false;\n foreach (Foo f in foos)\n{\n foreach (Bar b in bars)\n {\n if (f.Equals(b))\n {\n return true;\n }\n }\n}\n\nreturn false;\n if (condition1)\n if (condition2)\n doSomething();\n else (condition2)\n doSomethingElse();\n if (condition1)\n if (condition2)\n doSomething();\nelse (condition2)\n doSomethingElse();\n if (condition1)\n{\n if (condition2)\n doSomething();\n else (condition2)\n doSomethingElse();\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45/"
] |
359,733 | <p>I recently learnt that oracle has a feature which was pretty useful to me - as the designer/implementator didn't care much about data history - I can query the historical state of a record if it's available yet in the oracle cache, like this:</p>
<pre><code>select *
from ( select *
from sometable where some_condition )
as of timestamp sysdate-1
</code></pre>
<p>But now I need to check the historical data within a range. Is it possible anyhow, using the cache?</p>
| [
{
"answer_id": 359810,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 0,
"selected": false,
"text": "SELECT *\n FROM sometable\n VERSIONS BETWEEN TIMESTAMP systimestamp - 1 AND systimestamp\n"
},
{
"answer_id": 359815,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": true,
"text": "SQL> select sal from emp where empno=7369;\n\n SAL\n----------\n 5800\n\nSQL> update emp set sal = sal+100 where empno=7369;\n\n1 row updated.\n\nSQL> commit;\n\nCommit complete.\n\nSQL> update emp set sal = sal-100 where empno=7369;\n\n1 row updated. \n\nSQL> commit;\n\nCommit complete.\n\nSQL> select empno, sal, versions_starttime,versions_xid\n 2 from emp\n 3 versions between timestamp sysdate-1 and sysdate\n 4 where empno=7369;\n\n EMPNO SAL VERSIONS_STARTTIME VERSIONS_XID\n---------- ---------- --------------------------------------------------------------------------- --\n 7369 5900 11-DEC-08 16.05.32 0014001300002A74\n 7369 5800 11-DEC-08 16.03.32 000D002200012EB1\n 7369 5800\n"
},
{
"answer_id": 360104,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 2,
"selected": false,
"text": "UNDO_RETENTION"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11621/"
] |
359,742 | <p>I have a windows application that I want to run as a windows service - how can I do this ?</p>
| [
{
"answer_id": 359818,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": "static class Program\n{\n static void Main()\n {\n ServiceBase[] ServicesToRun;\n ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};\n ServiceBase.Run(ServicesToRun); \n }\n}\n protected override void OnStart(string[] args)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26809/"
] |
359,745 | <p>I have a microcontroller that must download a large file from a PC serial port (115200 baud) and write it to serial flash memory over SPI (~2 MHz). The flash writes must be in 256 byte blocks preceded by a write command and page address. The total RAM available on the system is 1 kB with an 80 byte stack size.</p>
<p>This is currently working by filling a 256 byte buffer from the UART and then ping-ponging to a another 256 byte buffer being filled by an interrupt on the RX buffer ready signal while the flash is written to with busy writes. The buffer swapping is repeated until the operation is complete.</p>
<p>I would prefer to setup TX/RX interrupt handlers for both the SPI and UART ports that operate on seperate circular buffers. So, instead of polling for new bytes and waiting for operations to complete I can simply fill the TX buffers and enable the interrupt or check the buffers for incoming data. This would give a lot more clock cycles for real work instead of waiting on peripherals.</p>
<p>After implementing the IRQ's with 128 byte circular buffers, I poll the UART RX buffer for data and immediately place it in the SPI TX buffer to do the file transfer. The problem I am having with this approach is that I don't have sufficient RAM for the buffers and the PC receive buffer is filling up faster than I get the data over to the flash transmit buffer. Obviously, transmission speed is not the problem (115.2 kHz in and 2 MHz out), but there is a write cycle wait after each 256-byte page is transmitted.</p>
<hr>
<p>It appears the frequent SPI interrupts were blocking some of the UART interrupts and causing bytes to be missed. The solution I chose was to use a ring buffer for the UART receive interrupt and feed the data into a 256 byte page buffer that is sent to the serial flash by polling for byte transfers and write completion. A 128 ring buffer is big enough to prevent overflows during the SPI write.</p>
| [
{
"answer_id": 359955,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 3,
"selected": true,
"text": "typedef struct data_buffer {\n char flags;\n char[128] data;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491/"
] |
359,758 | <p>How do I set tab ordering in WPF? I have an ItemsControl with some items expanded and some collapsed and would like to skip the collapsed ones when I'm tabbing.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 360585,
"author": "Jab",
"author_id": 29676,
"author_profile": "https://Stackoverflow.com/users/29676",
"pm_score": 7,
"selected": true,
"text": "KeyboardNavigation.IsTabStop=\"False\"\n"
},
{
"answer_id": 591668,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 7,
"selected": false,
"text": "<Control KeyboardNavigation.TabIndex=\"0\" ... />\n TabIndex=\"0\""
},
{
"answer_id": 2901763,
"author": "Pankaj",
"author_id": 349522,
"author_profile": "https://Stackoverflow.com/users/349522",
"pm_score": 5,
"selected": false,
"text": "<Control KeyboardNavigation.TabIndex=\"0\" ... /> <ComboBox Height=\"23\" \n Margin=\"148,24,78,0\" \n Name=\"comboBoxDataSet\"\n VerticalAlignment=\"Top\"\n SelectionChanged=\"comboBoxDestMarketDataSet_SelectionChanged\"\n DropDownOpened=\"comboBoxDestMarketDataSet_DropDownOpened\"\n KeyboardNavigation.TabIndex=\"0\" />\n<ComboBox Height=\"23\" \n Margin=\"148,56,78,0\" \n Name=\"comboBoxCategory\" \n VerticalAlignment=\"Top\" \n SelectionChanged=\"comboBoxDestCategory_SelectionChanged\"\n DropDownOpened=\"comboBoxDestCategory_DropDownOpened\"\n KeyboardNavigation.TabIndex=\"1\" />\n"
},
{
"answer_id": 8326969,
"author": "AltF4_",
"author_id": 1073481,
"author_profile": "https://Stackoverflow.com/users/1073481",
"pm_score": 4,
"selected": false,
"text": "KeyboardNavigation.TabNavigation=\"Cycle\"\n"
},
{
"answer_id": 24087119,
"author": "Gustavo Mori",
"author_id": 556595,
"author_profile": "https://Stackoverflow.com/users/556595",
"pm_score": 3,
"selected": false,
"text": "TabIndex"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41304/"
] |
359,763 | <h2>Short version</h2>
<p>How do i use an API call when i cannot guarantee that the window
handle will remain valid? </p>
<p>i can guarantee that i'm holding a reference to my form (so the form is not being disposed). That doesn't guarantee that the form's <strong>handle</strong> will stay valid all that time. </p>
<p><em>How can a form's window handle become invalid even though the form is not diposed</em>? </p>
<p>Because the form's underlying Windows window was destroyed and recreated. </p>
<h2>Long Version</h2>
<p>i want to P/Invoke an API that requires a hwnd (a handle to a window). Some examples of API calls that requie an hWnd are:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms787175(VS.85).aspx" rel="nofollow noreferrer">IVMRWindowlessControl::SetVideoClippingWindow</a></p>
<pre><code> HRESULT SetVideoClippingWindow(
HWND hwnd
);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ms644950.aspx" rel="nofollow noreferrer">SendMessage</a></p>
<pre><code>SendMessage(
HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam
);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ms649052.aspx" rel="nofollow noreferrer">SetClipboardViewer</a></p>
<pre><code>HWND SetClipboardViewer(
HWND hWndNewViewer
);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ms644906.aspx" rel="nofollow noreferrer">SetTimer</a></p>
<pre><code>UINT_PTR SetTimer(
HWND hWnd,
UINT_PTR nIDEvent,
UINT uElapse,
TIMERPROC lpTimerFunc
);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/bb775262(VS.85).aspx" rel="nofollow noreferrer">IProgressDialog::StartProgressDialog</a></p>
<pre><code>HRESULT StartProgressDialog(
HWND hwndParent,
IUnknown *punkEnableModless,
DWORD dwFlags,
LPCVOID pvReserved
);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/bb762159(VS.85).aspx" rel="nofollow noreferrer">Shell_NotifyIcon</a></p>
<pre><code>BOOL Shell_NotifyIcon(
DWORD dwMessage,
PNOTIFYICONDATA lpdata //<--hWnd in there
);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ms632669.aspx" rel="nofollow noreferrer">AnimateWindow</a></p>
<pre><code>BOOL AnimateWindow(
HWND hwnd,
DWORD dwTime,
DWORD dwFlags
);
</code></pre>
<p><strong>Note:</strong> Some of these API calls have managed equivalents, some do not - but that fact is irrelavent for my question.</p>
<h2>Explanation</h2>
<p>i can call one of these API functions, which requires long term window handle, e.g.:</p>
<pre><code>private void TellTheGuyToDoTheThing()
{
SendMessage(this.Handle,
WM_MyCustomMessage,
paramOneForTheThing,
paramTwoForTheThing);
}
</code></pre>
<p>It has been suggested that the above call to SendMessage is dangerous because of the unmanaged use of a window handle. They suggest that you wrap the hwnd in a HandleRef object:</p>
<pre><code>private void TellTheGuyToDoTheThing()
{
SendMessage(new HandleRef(this, this.Handle),
WM_MyCustomMessage,
paramOneForTheThing, paramTwoForTheThing);
</code></pre>
<p>This way: the window handle is guaranteed to stay valid during the call to SendMessage. But it doesn't always work out that way. The following API call requires long-term access to a window handle:</p>
<pre><code>private void RegisterWithTheThing()
{
this.nextClipboardViewerInChain = SetClipboardViewer(
new HandleRef(this, this.Handle));
}
</code></pre>
<p>Even though i wrapped the handle in a HandleRef, it is still possible (in the subsequest seconds, minutes, hours, days, weeks, months, or years) for the form's window handle to become invalid. This happens when the form's underlying Windows window is destroyed and a new one created. This, despite the fact that i protected the form's handle in a HandleRef.</p>
<p>i can name <em>one</em> way in which a form's handle becomes invalid:</p>
<pre><code>this.RightToLeft = RightToLeft.Yes;
</code></pre>
<p>The form's window is re-created and old hwnd is now invalid.</p>
<p>So the question is: How to use an API call that requires a window handle?</p>
<h2>Cannot be done?</h2>
<p>i anticipate the answer: <em>you cannot do this. There is nothing that can be done to protect the form's handle to ensure it is valid as long as you need to keep the handle.</em></p>
<p>This then means that i need to know when the handle is being destroyed, so i can tell Windows to let it go, e.g.:</p>
<pre><code>protected override void TheHandleIsAboutToBeDestroyed()
{
ChangeClipboardChain(this.Handle, this.nextClipboardViewerInChain);
}
</code></pre>
<p>and then be told when the new handle is created:</p>
<pre><code>protected override void TheHandleWasJustCreated()
{
RegisterTheThing();
}
</code></pre>
<p>Except no such ancestor methods exist.</p>
<p><strong>Alternate question:</strong> Are there methods i can override so i know when a window's handle is about to be destroyed, and when it has just been creatd?</p>
<p>Having to break the .NET WinForms encapsulation of re-creating handles is ugly, but is it the only way?</p>
<hr>
<h2>Update One</h2>
<p>Handling the <strong>Close</strong>/<strong>OnClose</strong> event of a form is insufficient, the same goes for</p>
<ul>
<li>handling IDisposable</li>
<li>GC pinning the form</li>
</ul>
<p>since i can make the form's underlying window handle invalid without closing or disposing form. e.g:</p>
<pre><code>private void InvalidThisFormsWindowHandleForFun()
{
this.RightToLeft = RightToLeft.Yes;
}
</code></pre>
<p><strong>Note:</strong> You <em>destroy</em> a Windows window handle, you don't dispose of it. Objects in .NET are the things that get disposed of; which, if it's a Form object, will most likely involve <em>destroying</em> the Windows window handle.</p>
<p>Windows is a product by Microsoft.</p>
<p>A window is a thing with a message loop and can sometimes show stuff on screen.</p>
<hr>
<h2>Update Two</h2>
<p><a href="https://stackoverflow.com/questions/359763/net-winforms-how-to-use-an-api-call-that-requires-a-window-handle#360023">me.yahoo.com/a/BrYwg</a> had a good suggestion for the use of a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.nativewindow.aspx" rel="nofollow noreferrer">NativeWindow</a> object to act as a listener for items that require an hWnd which are used to listen for messages. This can be used to solve some issues, like:</p>
<ul>
<li>SetClipboardViewer</li>
<li>SetTimer</li>
<li>IProgressDialgo::StartProgressDialog</li>
<li>Shell_NotifyIcon</li>
</ul>
<p>but doesn't work for</p>
<ul>
<li>AnimateWindow</li>
<li>SendMessage</li>
<li>IVMRWindowlessControl::SetVideoClippingWindow</li>
</ul>
| [
{
"answer_id": 1980367,
"author": "Serghei Gorodetki",
"author_id": 240925,
"author_profile": "https://Stackoverflow.com/users/240925",
"pm_score": 0,
"selected": false,
"text": "this.RightToLeft = RightToLeft.Yes;\n this.ShowInTaskbar = false;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
359,775 | <p>If I want to display an underlined value in a TextBlock, I have to use a Run element. (If there's a better/easier way, I'd love to hear about it.)</p>
<pre><code><TextBlock>
<Run TextDecorations="Underline" Text="MyText" />
</TextBlock>
</code></pre>
<p>Ideally, to implement this within a DataTemplate, it would look something like this:</p>
<pre><code><DataTemplate x:Key="underlineTemplate">
<TextBlock>
<Run TextDecorations="Underline" Text="{Binding Value}" />
</TextBlock>
</DataTemplate>
</code></pre>
<p>This won't work, however, because the Run's Text property isn't a DependencyProperty, so you can't databind to it. Does anyone know how I can accomplish this?</p>
| [
{
"answer_id": 359833,
"author": "Sacha Bruttin",
"author_id": 20761,
"author_profile": "https://Stackoverflow.com/users/20761",
"pm_score": 0,
"selected": false,
"text": "<TextBlock Text=\"MyText\" TextDecorations=\"Underline\" />\n"
},
{
"answer_id": 359854,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 3,
"selected": true,
"text": "<TextBlock TextDecorations=\"Underline\" Text=\"{Binding Value}\" />\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30095/"
] |
359,782 | <p>I have a mysql table that relies on the unix epoch time stamp equivalent of the date of the entry to sort and filter in various parts of the website. I'm trying to implement a date picker that will enter the date into the form field in the mm/dd/yyyy format. I've been struggling with converting that date into the unix epoch format to add that entry in the row field. All the attempts I've made have resulted in generating the current day epoch time stamp. Does anyone have any idea how I can take that date format and convert in the it's equivalent epoch time stamp?</p>
<p>Thanks in advance.</p>
<p><strong>Additional information:</strong></p>
<p>I have been trying mktime, and all I get is todays epoch. Apologies, I should have added some code earlier to better explain:</p>
<p>The form id is "date" The database field is "epoch"</p>
<p>Here's what I'm trying (unsuccessfully) when I post the for date:</p>
<pre><code>$epochhold = ($_POST['date']);
$epoch = mktime(0,0,0,$epochhold);
</code></pre>
<p>I understand from a previous post that this would still submit the value as mm/dd/yyyy and not mm, dd, yyyy as mktime expects, however the post didn't offer and resolution on how to do that. I tried a str_replace to change the "/" to "," and that yeilded the same result - getting today's epoch date regardless of the date entered.</p>
<p>Here's that code example - again this didn't work, but I add it to help illustrate what I've tried</p>
<pre><code>$epochhold = ($_POST['date']);
$epochold2 = str_replace('/', ', ', $epochhold)
$epoch = mktime(0,0,0,$epochhold2);
</code></pre>
<p>Thanks for the previous response as well, I didn't want the quick reply to go unnoticed!</p>
<p><strong>Thanks everyone!</strong></p>
<p>Thanks to everyone for the replies - strtotime seems to be working best on the initial tests and may be the way to go as this format is consistent throughout the site. But all the suggestions helped with this a few other things all well so thank you all again!</p>
| [
{
"answer_id": 359914,
"author": "Matt",
"author_id": 42135,
"author_profile": "https://Stackoverflow.com/users/42135",
"pm_score": 5,
"selected": true,
"text": "strtotime($_POST['app_date']);\n"
},
{
"answer_id": 359943,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "if ( ! preg_match('#\\d{2}/\\d{2}/\\d{4}#', $_POST['date']) ) {\n // complain about invalid input\n}\n\nlist($m, $d, $y) = explode('/', $_POST['date']);\n$timestamp = mktime(0, 0, 0, $m, $d, $y);\n"
},
{
"answer_id": 360110,
"author": "Wickethewok",
"author_id": 30133,
"author_profile": "https://Stackoverflow.com/users/30133",
"pm_score": 0,
"selected": false,
"text": "$unix_time = strtotime($_POST['date']);\nif($unix_time < 0) {\n //error case\n}\nelse {\n //value OK!\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45389/"
] |
359,788 | <p>I have the name of a function in JavaScript as a string. How do I convert that into a function pointer so I can call it later?</p>
<p>Depending on the circumstances, I may need to pass various arguments into the method too.</p>
<p>Some of the functions may take the form of <code>namespace.namespace.function(args[...])</code>.</p>
| [
{
"answer_id": 359799,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 6,
"selected": false,
"text": "window[\"foo\"](arg1, arg2);\n eval(fname)(arg1, arg2);\n"
},
{
"answer_id": 359842,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 5,
"selected": false,
"text": "x.y.foo() x.y['foo']() x['y']['foo']() window['x']['y']['foo']()"
},
{
"answer_id": 359910,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 12,
"selected": true,
"text": "eval window[\"functionName\"](arguments);\n window[\"My.Namespace.functionName\"](arguments); // fail\n window[\"My\"][\"Namespace\"][\"functionName\"](arguments); // succeeds\n function executeFunctionByName(functionName, context /*, args */) {\n var args = Array.prototype.slice.call(arguments, 2);\n var namespaces = functionName.split(\".\");\n var func = namespaces.pop();\n for(var i = 0; i < namespaces.length; i++) {\n context = context[namespaces[i]];\n }\n return context[func].apply(context, args);\n}\n executeFunctionByName(\"My.Namespace.functionName\", window, arguments);\n executeFunctionByName(\"Namespace.functionName\", My, arguments);\n"
},
{
"answer_id": 4351575,
"author": "Alex Nazarov",
"author_id": 530089,
"author_profile": "https://Stackoverflow.com/users/530089",
"pm_score": 7,
"selected": false,
"text": "function executeFunctionByName(functionName, context /*, args */) {\n var args = Array.prototype.slice.call(arguments, 2);\n var namespaces = functionName.split(\".\");\n var func = namespaces.pop();\n for (var i = 0; i < namespaces.length; i++) {\n context = context[namespaces[i]];\n }\n return context[func].apply(context, args);\n}\n"
},
{
"answer_id": 8098261,
"author": "Amirali",
"author_id": 1042236,
"author_profile": "https://Stackoverflow.com/users/1042236",
"pm_score": 4,
"selected": false,
"text": "window[<method name>] var function_name = \"string\";\nfunction_name = window[function_name];\n"
},
{
"answer_id": 13521821,
"author": "merqlove",
"author_id": 754368,
"author_profile": "https://Stackoverflow.com/users/754368",
"pm_score": 1,
"selected": false,
"text": "var arrayMaker = { \n someProperty: 'some value here', \n make: function (arg1, arg2) { \n return [ this, arg1, arg2 ]; \n },\n execute: function_name\n};\n"
},
{
"answer_id": 14065120,
"author": "Bradley Shrader",
"author_id": 1933735,
"author_profile": "https://Stackoverflow.com/users/1933735",
"pm_score": 2,
"selected": false,
"text": "context = context == undefined? window:context; window"
},
{
"answer_id": 14522903,
"author": "Ahmet DAL",
"author_id": 1029816,
"author_profile": "https://Stackoverflow.com/users/1029816",
"pm_score": 4,
"selected": false,
"text": "window[\"functionName\"] var myObject=new Object();\nmyObject[\"functionName\"](arguments);\n var now=new Date();\nnow[\"getFullYear\"]()\n"
},
{
"answer_id": 18282021,
"author": "Coley",
"author_id": 1173314,
"author_profile": "https://Stackoverflow.com/users/1173314",
"pm_score": 6,
"selected": false,
"text": "var codeToExecute = \"My.Namespace.functionName()\";\nvar tmpFunc = new Function(codeToExecute);\ntmpFunc();\n"
},
{
"answer_id": 21560003,
"author": "Wolfgang Kuehn",
"author_id": 570118,
"author_profile": "https://Stackoverflow.com/users/570118",
"pm_score": 5,
"selected": false,
"text": "eval()"
},
{
"answer_id": 23221727,
"author": "DevAshish",
"author_id": 3471583,
"author_profile": "https://Stackoverflow.com/users/3471583",
"pm_score": 0,
"selected": false,
"text": "var command = \"Add\";\nvar tempFunction = new Function(\"Arg1\",\"Arg2\", \"window.\" + command + \"(Arg1,Arg2)\");\ntempFunction(x,y);\n"
},
{
"answer_id": 24478139,
"author": "Cilan",
"author_id": 2876565,
"author_profile": "https://Stackoverflow.com/users/2876565",
"pm_score": 2,
"selected": false,
"text": "this window this['fun'+'ctionName']();\n"
},
{
"answer_id": 26432746,
"author": "abhishekisnot",
"author_id": 2419112,
"author_profile": "https://Stackoverflow.com/users/2419112",
"pm_score": 3,
"selected": false,
"text": "var functionWithoutArguments = function(){\n console.log(\"Executing functionWithoutArguments\");\n}\nsetTimeout(\"functionWithoutArguments()\", 0);\n var functionWithArguments = function(arg1, arg2) {\n console.log(\"Executing functionWithArguments\", arg1, arg2);\n}\nsetTimeout(\"functionWithArguments(10, 20)\");\n var _very = {\n _deeply: {\n _defined: {\n _function: function(num1, num2) {\n console.log(\"Execution _very _deeply _defined _function : \", num1, num2);\n }\n }\n }\n}\nsetTimeout(\"_very._deeply._defined._function(40,50)\", 0);\n"
},
{
"answer_id": 29947151,
"author": "nomæd",
"author_id": 544618,
"author_profile": "https://Stackoverflow.com/users/544618",
"pm_score": 2,
"selected": false,
"text": "/**\n * Converts a string containing a function or object method name to a function pointer.\n * @param string func\n * @return function\n */\nfunction getFuncFromString(func) {\n // if already a function, return\n if (typeof func === 'function') return func;\n\n // if string, try to find function or method of object (of \"obj.func\" format)\n if (typeof func === 'string') {\n if (!func.length) return null;\n var target = window;\n var func = func.split('.');\n while (func.length) {\n var ns = func.shift();\n if (typeof target[ns] === 'undefined') return null;\n target = target[ns];\n }\n if (typeof target === 'function') return target;\n }\n\n // return null if could not parse\n return null;\n}\n"
},
{
"answer_id": 30385831,
"author": "pmrotule",
"author_id": 1895428,
"author_profile": "https://Stackoverflow.com/users/1895428",
"pm_score": 2,
"selected": false,
"text": "window['myfunction'](arguments)\n window['myobject.myfunction'](arguments); // won't work\nwindow['myobject']['myfunction'](arguments); // will work\n my = {\n code : {\n is : {\n nice : function(a, b){ alert(a + \",\" + b); }\n }\n }\n};\n\nguy = function(){ alert('awesome'); }\n\nfunction executeFunctionByName(str, args)\n{\n var arr = str.split('.');\n var fn = window[ arr[0] ];\n \n for (var i = 1; i < arr.length; i++)\n { fn = fn[ arr[i] ]; }\n fn.apply(window, args);\n}\n\nexecuteFunctionByName('my.code.is.nice', ['arg1', 'arg2']);\nexecuteFunctionByName('guy');"
},
{
"answer_id": 30602469,
"author": "Ruben Daddario",
"author_id": 4966334,
"author_profile": "https://Stackoverflow.com/users/4966334",
"pm_score": 6,
"selected": false,
"text": "var customObject = {\n customFunction: function(param){...}\n};\n customObject['customFunction'](param);\n const FunctionNames = Object.freeze({ \n FirstFunction: \"firstFunction\", \n SecondFunction: \"secondFunction\" \n});\n\n...\n\nvar customObject = {\n [FunctionNames.FirstFunction]: function(param){...},\n [FunctionNames.SecondFunction]: function(param){...}\n};\n\n...\n\ncustomObject[FunctionNames.FirstFunction](param);"
},
{
"answer_id": 31289846,
"author": "nils petersohn",
"author_id": 170881,
"author_profile": "https://Stackoverflow.com/users/170881",
"pm_score": 6,
"selected": false,
"text": "class X {\n method1(){\n console.log(\"1\");\n }\n method2(){\n this['method1']();\n console.log(\"2\");\n }\n}\nlet x = new X();\nx['method2']();\n 1\n2\n"
},
{
"answer_id": 33414649,
"author": "Magnus Smith",
"author_id": 11461,
"author_profile": "https://Stackoverflow.com/users/11461",
"pm_score": 1,
"selected": false,
"text": "var annoyingstring = 'call_my_func(123, true, \"blah\")'; onclick click <a href=\"#\" id=\"link_secret\"><!-- invisible --></a> $('#link_secret').attr('onclick', annoyingstring);\n$('#link_secret').click();\n <a>"
},
{
"answer_id": 35917055,
"author": "Ithar",
"author_id": 1512175,
"author_profile": "https://Stackoverflow.com/users/1512175",
"pm_score": -1,
"selected": false,
"text": "eval('function()') new Function(strName) <html>\n<body>\n<button onclick=\"test()\">Try it</button>\n</body>\n</html>\n<script type=\"text/javascript\">\n\n function test() {\n try { \n var fnName = \"myFunction()\";\n var fn = new Function(fnName);\n fn();\n } catch (err) {\n console.log(\"error:\"+err.message);\n }\n }\n\n function myFunction() {\n console.log('Executing myFunction()');\n }\n\n</script>\n"
},
{
"answer_id": 36737117,
"author": "crazycrv",
"author_id": 531897,
"author_profile": "https://Stackoverflow.com/users/531897",
"pm_score": 1,
"selected": false,
"text": "window.ClientSideValidations.forms.location_form\n window.ClientSideValidations.forms['location_form']\n"
},
{
"answer_id": 37617203,
"author": "KingRider",
"author_id": 2777092,
"author_profile": "https://Stackoverflow.com/users/2777092",
"pm_score": 0,
"selected": false,
"text": "var namefunction = 'jspure'; // String\n\nfunction jspure(msg1 = '', msg2 = '') { \n console.log(msg1+(msg2!=''?'/'+msg2:''));\n} // multiple argument\n\n// Results ur test\nwindow[namefunction]('hello','hello again'); // something...\neval[namefunction] = 'hello'; // use string or something, but its eval just one argument and not exist multiple\n"
},
{
"answer_id": 39978338,
"author": "Neo",
"author_id": 7001125,
"author_profile": "https://Stackoverflow.com/users/7001125",
"pm_score": 0,
"selected": false,
"text": "function executeFunctionByName(functionName, context, timeout /*, args */ ) {\n var args = Array.prototype.slice.call(arguments, 3);\n var namespaces = functionName.split(\".\");\n var func = namespaces.pop();\n for (var i = 0; i < namespaces.length; i++) {\n context = context[namespaces[i]];\n }\n var timeoutID = setTimeout(\n function(){ context[func].apply(context, args)},\n timeout\n );\n return timeoutID;\n}\n\nvar _very = {\n _deeply: {\n _defined: {\n _function: function(num1, num2) {\n console.log(\"Execution _very _deeply _defined _function : \", num1, num2);\n }\n }\n }\n}\n\nconsole.log('now wait')\nexecuteFunctionByName(\"_very._deeply._defined._function\", window, 2000, 40, 50 );"
},
{
"answer_id": 40607659,
"author": "PeterM",
"author_id": 5444623,
"author_profile": "https://Stackoverflow.com/users/5444623",
"pm_score": 0,
"selected": false,
"text": "executeByName app.widget['872LfCHc']['toggleFolders'] var executeByName = function(name, context) {\n var args, func, i, j, k, len, len1, n, normalizedName, ns;\n if (context == null) {\n context = window;\n }\n args = Array.prototype.slice.call(arguments, 2);\n normalizedName = name.replace(/[\\]'\"]/g, '').replace(/\\[/g, '.');\n ns = normalizedName.split(\".\");\n func = context;\n for (i = j = 0, len = ns.length; j < len; i = ++j) {\n n = ns[i];\n func = func[n];\n }\n ns.pop();\n for (i = k = 0, len1 = ns.length; k < len1; i = ++k) {\n n = ns[i];\n context = context[n];\n }\n if (typeof func !== 'function') {\n throw new TypeError('Cannot execute function ' + name);\n }\n return func.apply(context, args);\n}\n executeByName = (name, context = window) ->\n args = Array.prototype.slice.call(arguments, 2)\n normalizedName = name.replace(/[\\]'\"]/g, '').replace(/\\[/g, '.')\n ns = normalizedName.split \".\"\n func = context\n for n, i in ns\n func = func[n]\n\n ns.pop()\n for n, i in ns\n context = context[n];\n if typeof func != 'function'\n throw new TypeError 'Cannot execute function ' + name\n func.apply(context, args)\n"
},
{
"answer_id": 41677491,
"author": "Suat Atan PhD",
"author_id": 607230,
"author_profile": "https://Stackoverflow.com/users/607230",
"pm_score": 0,
"selected": false,
"text": "eval(\"functionname as string\") function testfunc(){\n return \"hello world\";\n}\n\n$( document ).ready(function() {\n\n $(\"div\").html(eval(\"testfunc\"));\n});\n"
},
{
"answer_id": 42171078,
"author": "Mac",
"author_id": 2158270,
"author_profile": "https://Stackoverflow.com/users/2158270",
"pm_score": 4,
"selected": false,
"text": "a = function( args ) {\n console.log( 'global func passed:' );\n for( var i = 0; i < arguments.length; i++ ) {\n console.log( '-> ' + arguments[ i ] );\n }\n};\nns = {};\nns.a = function( args ) {\n console.log( 'namespace func passed:' );\n for( var i = 0; i < arguments.length; i++ ) {\n console.log( '-> ' + arguments[ i ] ); \n }\n};\nname = 'nsa';\nn_s_a = [ 'Snowden' ];\nnoSuchAgency = function(){};\n function executeFunctionByName( functionName, context /*, args */ ) {\n var args, namespaces, func;\n\n if( typeof functionName === 'undefined' ) { throw 'function name not specified'; }\n\n if( typeof eval( functionName ) !== 'function' ) { throw functionName + ' is not a function'; }\n\n if( typeof context !== 'undefined' ) { \n if( typeof context === 'object' && context instanceof Array === false ) { \n if( typeof context[ functionName ] !== 'function' ) {\n throw context + '.' + functionName + ' is not a function';\n }\n args = Array.prototype.slice.call( arguments, 2 );\n\n } else {\n args = Array.prototype.slice.call( arguments, 1 );\n context = window;\n }\n\n } else {\n context = window;\n }\n\n namespaces = functionName.split( \".\" );\n func = namespaces.pop();\n\n for( var i = 0; i < namespaces.length; i++ ) {\n context = context[ namespaces[ i ] ];\n }\n\n return context[ func ].apply( context, args );\n}\n // calling a global function without parms\nexecuteFunctionByName( 'a' );\n /* OUTPUT:\n global func passed:\n */\n\n// calling a global function passing a number (with implicit window context)\nexecuteFunctionByName( 'a', 123 );\n /* OUTPUT:\n global func passed:\n -> 123\n */\n\n// calling a namespaced function without parms\nexecuteFunctionByName( 'ns.a' );\n /* OUTPUT:\n namespace func passed:\n */\n\n// calling a namespaced function passing a string literal\nexecuteFunctionByName( 'ns.a', 'No Such Agency!' );\n /* OUTPUT:\n namespace func passed:\n -> No Such Agency!\n */\n\n// calling a namespaced function, with explicit context as separate arg, passing a string literal and array \nexecuteFunctionByName( 'a', ns, 'No Such Agency!', [ 007, 'is the man' ] );\n /* OUTPUT:\n namespace func passed:\n -> No Such Agency!\n -> 7,is the man\n */\n\n// calling a global function passing a string variable (with implicit window context)\nexecuteFunctionByName( 'a', name );\n /* OUTPUT:\n global func passed:\n -> nsa\n */\n\n// calling a non-existing function via string literal\nexecuteFunctionByName( 'n_s_a' );\n /* OUTPUT:\n Uncaught n_s_a is not a function\n */\n\n// calling a non-existing function by string variable\nexecuteFunctionByName( n_s_a );\n /* OUTPUT:\n Uncaught Snowden is not a function\n */\n\n// calling an existing function with the wrong namespace reference\nexecuteFunctionByName( 'a', {} );\n /* OUTPUT:\n Uncaught [object Object].a is not a function\n */\n\n// calling no function\nexecuteFunctionByName();\n /* OUTPUT:\n Uncaught function name not specified\n */\n\n// calling by empty string\nexecuteFunctionByName( '' );\n /* OUTPUT:\n Uncaught is not a function\n */\n\n// calling an existing global function with a namespace reference\nexecuteFunctionByName( 'noSuchAgency', ns );\n /* OUTPUT:\n Uncaught [object Object].noSuchAgency is not a function\n */\n"
},
{
"answer_id": 44782118,
"author": "Leo Lanese",
"author_id": 4487657,
"author_profile": "https://Stackoverflow.com/users/4487657",
"pm_score": 2,
"selected": false,
"text": " let t0 = () => { alert('red0') }\n var t1 = () =>{ alert('red1') }\n var t2 = () =>{ alert('red2') }\n var t3 = () =>{ alert('red3') }\n var t4 = () =>{ alert('red4') }\n var t5 = () =>{ alert('red5') }\n var t6 = () =>{ alert('red6') }\n\n function getSelection(type) {\n var evalSelection = {\n 'title0': t0,\n 'title1': t1,\n 'title2': t2,\n 'title3': t3,\n 'title4': t4,\n 'title5': t5,\n 'title6': t6,\n 'default': function() {\n return 'Default';\n }\n };\n return (evalSelection[type] || evalSelection['default'])();\n }\n getSelection('title1');\n"
},
{
"answer_id": 46090820,
"author": "Hugo R",
"author_id": 7771019,
"author_profile": "https://Stackoverflow.com/users/7771019",
"pm_score": 0,
"selected": false,
"text": "window[\"f\"](); /* \nAuthor: Hugo Reyes\n@ www.teamsrunner.com\n\n*/\n\n (function ( W, D) { // enclose it as self invoking function to avoid name collisions.\n\n\n // to call function1 as string\n // initialize your FunctionHUB as your namespace - context\n // you can use W[\"functionX\"](), if you want to call a function at the window scope.\n var container = new FunctionHUB();\n\n\n // call a function1 by name with one parameter.\n\n container[\"function1\"](' Hugo ');\n\n\n // call a function2 by name.\n container[\"function2\"](' Hugo Leon');\n\n\n // OO style class\n function FunctionHUB() {\n\n this.function1 = function (name) {\n\n console.log('Hi ' + name + ' inside function 1')\n }\n\n this.function2 = function (name) {\n\n console.log('Hi' + name + ' inside function 2 ')\n }\n }\n\n})(window, document); // in case you need window context inside your namespace.\n my.name.space.for.functions.etc.etc.etc my.name.space.for.functions.etc.etc[\"function\"]();"
},
{
"answer_id": 50658670,
"author": "SJ00",
"author_id": 1449954,
"author_profile": "https://Stackoverflow.com/users/1449954",
"pm_score": 0,
"selected": false,
"text": "eval() new Function()"
},
{
"answer_id": 52857870,
"author": "pouyan",
"author_id": 2398444,
"author_profile": "https://Stackoverflow.com/users/2398444",
"pm_score": 4,
"selected": false,
"text": "function fnCall(fn, ...args)\n{\n let func = (typeof fn ==\"string\")?window[fn]:fn;\n if (typeof func == \"function\") func(...args);\n else throw new Error(`${fn} is Not a function!`);\n}\n\n\nfunction example1(arg1){console.log(arg1)}\nfunction example2(arg1, arg2){console.log(arg1 + \" and \" + arg2)}\nfunction example3(){console.log(\"No arguments!\")}\n\nfnCall(\"example1\", \"test_1\");\nfnCall(\"example2\", \"test_2\", \"test3\");\nfnCall(example3);\nfnCall(\"example4\"); // should raise an error in console"
},
{
"answer_id": 54875979,
"author": "Zibri",
"author_id": 236062,
"author_profile": "https://Stackoverflow.com/users/236062",
"pm_score": 5,
"selected": false,
"text": "this[\"funcname\"]();\nself[\"funcname\"]();\nwindow[\"funcname\"]();\ntop[\"funcname\"]();\nglobalThis[\"funcname\"]();\n global[\"funcname\"]()\n"
},
{
"answer_id": 59232792,
"author": "SimoAmi",
"author_id": 2117996,
"author_profile": "https://Stackoverflow.com/users/2117996",
"pm_score": 1,
"selected": false,
"text": "eval function runDynamicFn(fnName, ...args) {\n // can also be fed from a tightly controlled config\n const allowedFnNames = ['fn1', 'ns1.ns2.fn3', 'ns4.fn4'];\n\n return allowedFnNames.includes(fnName) ? eval(fnName)(...args) : undefined; \n}\n\n// test function:\nfunction fn1(a) { \n console.log('fn1 called with', a)\n}\n\nrunDynamicFn('alert(\"got you!\")')\nrunDynamicFn('fn1', 'foo')"
},
{
"answer_id": 61541647,
"author": "snnsnn",
"author_id": 7134134,
"author_profile": "https://Stackoverflow.com/users/7134134",
"pm_score": 3,
"selected": false,
"text": "function fun1(arg) {\n console.log(arg);\n}\n\nfunction fun2(arg) {\n console.log(arg);\n}\n\nconst operations = {\n fun1,\n fun2\n};\n\noperations[\"fun1\"](\"Hello World\");\noperations.fun2(\"Hello World\");\n\n// You can use intermediate variables, if you like\nlet temp = \"fun1\";\noperations[temp](\"Hello World\");\n // mode.js\nexport function fun1(arg) {\n console.log(arg);\n}\n\nexport function fun2(arg) {\n console.log(arg);\n}\n // index.js\nimport { fun1, fun2 } from \"./mod\";\n\nconst operations = {\n fun1,\n fun2\n};\n\noperations[\"fun1\"](\"Hello World\");\noperations[\"fun2\"](\"Hello World\");\n"
},
{
"answer_id": 66730148,
"author": "vivek agarwal",
"author_id": 9116488,
"author_profile": "https://Stackoverflow.com/users/9116488",
"pm_score": 2,
"selected": false,
"text": "let executor = new FunctionExecutor();\nexecutor.addFunction(two)\nexecutor.addFunction(three)\n\nexecutor.execute(\"one\");\nexecutor.execute(\"three\");\n function FunctionExecutor() {\n this.functions = {};\n\n this.addFunction = function (fn) {\n let fnName = fn.name;\n this.functions[fnName] = fn;\n }\n\n this.execute = function execute(fnName, ...args) {\n if (fnName in this.functions && typeof this.functions[fnName] === \"function\") {\n return this.functions[fnName](...args);\n }\n else {\n console.log(\"could not find \" + fnName + \" function\");\n }\n }\n\n this.logFunctions = function () {\n console.log(this.functions);\n }\n}\n\n function two() {\n console.log(\"two\"); \n}\n\nfunction three() {\n console.log(\"three\");\n}\n\nlet executor = new FunctionExecutor();\nexecutor.addFunction(two)\nexecutor.addFunction(three)\n\nexecutor.execute(\"one\");\nexecutor.execute(\"three\");\n"
},
{
"answer_id": 71917213,
"author": "SaidbakR",
"author_id": 1592845,
"author_profile": "https://Stackoverflow.com/users/1592845",
"pm_score": 0,
"selected": false,
"text": "function captchaTest(msg){\n let x = Math.floor(Math.random()*(21-1)) +1;\n let y = Math.floor(Math.random()*(11-1)) +1;\n let sum = function(){\n return x+y;\n }\n let sub = function(){\n if (y > x){\n let m = y;\n y = x;\n x = m;\n console.log(x,y,m,'--')\n }\n return x-y;\n }\n let mul = function(){\n return x*y;\n } \n let OParr = [sum(), sub(), mul()]; \n let OP = Math.floor(Math.random()*OParr.length); \n let s = OParr[OP]; //!!! HERE !!! is the call as array element\n switch(OP){\n case 0:\n opra = '+';\n break;\n case 1:\n opra = '━';\n break;\n default:\n opra = '✖';\n }\n let msg2 = 'Answer the following question to continue:'\n let p = prompt(msg+' '+msg2+'\\n'+'What is the result of '+x+opra+y+' ?','')\n console.log(s,p,OP)\n if (s == p){\n alert ('Wow, Correct Answer!')\n return true;\n }\n else{\n alert('Sorry, the answer is not correct!')\n return false;\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5791/"
] |
359,816 | <p>I am very new to grails.I am doing one sample project for image uploading and displaying.Right now my project uploads the images and stores into the images directory.Now i want to display all the images stored in the "image" directory.
I dont know how to write the gsp code for display all images.</p>
<p>For displaying the images I wrote the following code in list.gsp page.</p>
<p>My gsp code is: </p>
<pre><code><g:each in="${imageList}" var="image">
<img src="${createLinkTo(dir: 'images', file: '1.jpg')}" alt="Grails"/>
</g:each>
</code></pre>
<p>imageList has filenames of images in the image directory.</p>
<p>In the second line i want put filename instead of "1.jpg". </p>
<p>Can any one tell me how to display the images.</p>
<p>thanks</p>
| [
{
"answer_id": 359844,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 2,
"selected": false,
"text": "<g:each in=\"${imageList}\" var=\"image\">\n<img src=\"${createLinkTo(dir: 'images', file: image.filename)}\" alt=\"Grails\"/>\n</g:each>\n"
},
{
"answer_id": 359853,
"author": "Rob Hruska",
"author_id": 29995,
"author_profile": "https://Stackoverflow.com/users/29995",
"pm_score": 2,
"selected": false,
"text": "imageList ['1.jpg', '2.jpg', ...] createLinkTo ${createLinkTo(dir: 'images', file: image)}\n imageList"
},
{
"answer_id": 366080,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "**${createLinkTo(dir: 'images', file: image)}**\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40945/"
] |
359,821 | <p>I want to style the last TD in a table without using a CSS class on the particular TD.</p>
<pre><code><table>
<tbody>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
<td>Five</td>
</tr>
</tbody>
</table>
table td
{
border: 1px solid black;
}
</code></pre>
<p>I want the TD containing the text "Five" to not have a border but again, I do not want to use a class.</p>
| [
{
"answer_id": 359838,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 6,
"selected": true,
"text": "table td + td + td + td + td {\n border: none;\n}\n"
},
{
"answer_id": 359849,
"author": "yoavf",
"author_id": 1011,
"author_profile": "https://Stackoverflow.com/users/1011",
"pm_score": 7,
"selected": false,
"text": ":last-child"
},
{
"answer_id": 359857,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "$(\"table td:last\").css(\"border\", \"none\");\n"
},
{
"answer_id": 359865,
"author": "Neil Aitken",
"author_id": 13803,
"author_profile": "https://Stackoverflow.com/users/13803",
"pm_score": 5,
"selected": false,
"text": "table tr td:last-child {\n border: none;\n}\n"
},
{
"answer_id": 359871,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 4,
"selected": false,
"text": "$(\"td:last-child\").css({border:\"none\"})\n"
},
{
"answer_id": 359912,
"author": "Liggy",
"author_id": 32142,
"author_profile": "https://Stackoverflow.com/users/32142",
"pm_score": 1,
"selected": false,
"text": "<style type=\"text/css\">\ntable td { \n h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : '1px solid #000' ) );\n}\n</style>\n"
},
{
"answer_id": 361070,
"author": "Darko",
"author_id": 32943,
"author_profile": "https://Stackoverflow.com/users/32943",
"pm_score": 2,
"selected": false,
"text": "<table>\n <col />\n <col width=\"50\" />\n <col id=\"anId\" />\n <col class=\"whatever\" />\n <col style=\"border:1px solid #000;\" />\n <tbody>\n <tr>\n <td>One</td>\n <td>Two</td>\n <td>Three</td>\n <td>Four</td>\n <td>Five</td>\n </tr>\n </tbody>\n</table>\n"
},
{
"answer_id": 1351102,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<style type=\"text/css\">\n body { \n font-family:arial;font-size: 8pt; \n } \n table td{\n border-right: #666 1px solid\n } \n\n table td { \n h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : 'border-right: 0px solid' ) ); \n } \n</style>\n<table>\n <tr>\n <td>Home</td>\n <td>sunil</td>\n <td>Kumar</td>\n <td>Rayadurg</td>\n <td>Five</td>\n <td>Six</td>\n </tr>\n</table>\n"
},
{
"answer_id": 1373977,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "$(\"table tr td:not(:last-child)\").css({ \"border-right\":\"1px solid #aaaaaa\" });\n"
},
{
"answer_id": 1480618,
"author": "Mottie",
"author_id": 145346,
"author_profile": "https://Stackoverflow.com/users/145346",
"pm_score": 0,
"selected": false,
"text": "<th> <td> <style type=\"text/css\">\n table td { border: 1px solid black; }\n table th { border: 0px; }\n<style>\n<table>\n <tbody>\n <tr>\n <td>One</td>\n <td>Two</td>\n <td>Three</td>\n <td>Four</td>\n <th>Five</th>\n </tr>\n <tr>\n <td>One</td>\n <td>Two</td>\n <td>Three</td>\n <td>Four</td>\n <th>Five</th>\n </tr>\n </tbody>\n</table>\n"
},
{
"answer_id": 7919635,
"author": "rachel",
"author_id": 423306,
"author_profile": "https://Stackoverflow.com/users/423306",
"pm_score": 1,
"selected": false,
"text": "#table td:last-of-type { border: none; }\n"
},
{
"answer_id": 10518789,
"author": "Matthew Layton",
"author_id": 1033686,
"author_profile": "https://Stackoverflow.com/users/1033686",
"pm_score": 5,
"selected": false,
"text": ":last-of-type tr > td:last-of-type {\n /* styling here */\n}\n"
},
{
"answer_id": 35069944,
"author": "Kurt Poehler",
"author_id": 4036413,
"author_profile": "https://Stackoverflow.com/users/4036413",
"pm_score": 4,
"selected": false,
"text": "tr:last-child td:last-child{\n border:none;\n /*any other style*/\n}\n td:nth-child(5){\n border:none;\n}\n"
},
{
"answer_id": 62695305,
"author": "Habib_95",
"author_id": 9411303,
"author_profile": "https://Stackoverflow.com/users/9411303",
"pm_score": 2,
"selected": false,
"text": "<style>\n.table > tbody > tr > td:last-of-type {\n /* Give your style Here; */\n}\n</style>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,824 | <p>I have a chunk of <a href="http://en.wikipedia.org/wiki/MultiDimensional_eXpressions" rel="nofollow noreferrer">MDX</a> that I'd like to throw into an ASP.NET form. Hopefully just binding the results to a gridview. Are there any good links or snippets? I'm using VB.NET, but I am able to port from C# if no Visual Basic code is available.</p>
| [
{
"answer_id": 359838,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 6,
"selected": true,
"text": "table td + td + td + td + td {\n border: none;\n}\n"
},
{
"answer_id": 359849,
"author": "yoavf",
"author_id": 1011,
"author_profile": "https://Stackoverflow.com/users/1011",
"pm_score": 7,
"selected": false,
"text": ":last-child"
},
{
"answer_id": 359857,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "$(\"table td:last\").css(\"border\", \"none\");\n"
},
{
"answer_id": 359865,
"author": "Neil Aitken",
"author_id": 13803,
"author_profile": "https://Stackoverflow.com/users/13803",
"pm_score": 5,
"selected": false,
"text": "table tr td:last-child {\n border: none;\n}\n"
},
{
"answer_id": 359871,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 4,
"selected": false,
"text": "$(\"td:last-child\").css({border:\"none\"})\n"
},
{
"answer_id": 359912,
"author": "Liggy",
"author_id": 32142,
"author_profile": "https://Stackoverflow.com/users/32142",
"pm_score": 1,
"selected": false,
"text": "<style type=\"text/css\">\ntable td { \n h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : '1px solid #000' ) );\n}\n</style>\n"
},
{
"answer_id": 361070,
"author": "Darko",
"author_id": 32943,
"author_profile": "https://Stackoverflow.com/users/32943",
"pm_score": 2,
"selected": false,
"text": "<table>\n <col />\n <col width=\"50\" />\n <col id=\"anId\" />\n <col class=\"whatever\" />\n <col style=\"border:1px solid #000;\" />\n <tbody>\n <tr>\n <td>One</td>\n <td>Two</td>\n <td>Three</td>\n <td>Four</td>\n <td>Five</td>\n </tr>\n </tbody>\n</table>\n"
},
{
"answer_id": 1351102,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<style type=\"text/css\">\n body { \n font-family:arial;font-size: 8pt; \n } \n table td{\n border-right: #666 1px solid\n } \n\n table td { \n h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : 'border-right: 0px solid' ) ); \n } \n</style>\n<table>\n <tr>\n <td>Home</td>\n <td>sunil</td>\n <td>Kumar</td>\n <td>Rayadurg</td>\n <td>Five</td>\n <td>Six</td>\n </tr>\n</table>\n"
},
{
"answer_id": 1373977,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "$(\"table tr td:not(:last-child)\").css({ \"border-right\":\"1px solid #aaaaaa\" });\n"
},
{
"answer_id": 1480618,
"author": "Mottie",
"author_id": 145346,
"author_profile": "https://Stackoverflow.com/users/145346",
"pm_score": 0,
"selected": false,
"text": "<th> <td> <style type=\"text/css\">\n table td { border: 1px solid black; }\n table th { border: 0px; }\n<style>\n<table>\n <tbody>\n <tr>\n <td>One</td>\n <td>Two</td>\n <td>Three</td>\n <td>Four</td>\n <th>Five</th>\n </tr>\n <tr>\n <td>One</td>\n <td>Two</td>\n <td>Three</td>\n <td>Four</td>\n <th>Five</th>\n </tr>\n </tbody>\n</table>\n"
},
{
"answer_id": 7919635,
"author": "rachel",
"author_id": 423306,
"author_profile": "https://Stackoverflow.com/users/423306",
"pm_score": 1,
"selected": false,
"text": "#table td:last-of-type { border: none; }\n"
},
{
"answer_id": 10518789,
"author": "Matthew Layton",
"author_id": 1033686,
"author_profile": "https://Stackoverflow.com/users/1033686",
"pm_score": 5,
"selected": false,
"text": ":last-of-type tr > td:last-of-type {\n /* styling here */\n}\n"
},
{
"answer_id": 35069944,
"author": "Kurt Poehler",
"author_id": 4036413,
"author_profile": "https://Stackoverflow.com/users/4036413",
"pm_score": 4,
"selected": false,
"text": "tr:last-child td:last-child{\n border:none;\n /*any other style*/\n}\n td:nth-child(5){\n border:none;\n}\n"
},
{
"answer_id": 62695305,
"author": "Habib_95",
"author_id": 9411303,
"author_profile": "https://Stackoverflow.com/users/9411303",
"pm_score": 2,
"selected": false,
"text": "<style>\n.table > tbody > tr > td:last-of-type {\n /* Give your style Here; */\n}\n</style>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13954/"
] |
359,827 | <p>I need to compare 2 strings in C# and treat accented letters the same as non-accented letters. For example:</p>
<pre><code>string s1 = "hello";
string s2 = "héllo";
s1.Equals(s2, StringComparison.InvariantCultureIgnoreCase);
s1.Equals(s2, StringComparison.OrdinalIgnoreCase);
</code></pre>
<p>These 2 strings need to be the same (as far as my application is concerned), but both of these statements evaluate to false. Is there a way in C# to do this?</p>
| [
{
"answer_id": 359874,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "using System;\nusing System.Globalization;\n\nclass Sample {\n public static void Main() {\n String str1 = \"change\";\n String str2 = \"dollar\";\n String relation = null;\n\n relation = symbol( String.Compare(str1, str2, false, new CultureInfo(\"en-US\")) );\n Console.WriteLine(\"For en-US: {0} {1} {2}\", str1, relation, str2);\n\n relation = symbol( String.Compare(str1, str2, false, new CultureInfo(\"cs-CZ\")) );\n Console.WriteLine(\"For cs-CZ: {0} {1} {2}\", str1, relation, str2);\n }\n\n private static String symbol(int r) {\n String s = \"=\";\n if (r < 0) s = \"<\";\n else if (r > 0) s = \">\";\n return s;\n }\n}\n/*\nThis example produces the following results.\nFor en-US: change < dollar\nFor cs-CZ: change > dollar\n*/\n"
},
{
"answer_id": 360084,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 3,
"selected": false,
"text": "CompareIgnoreAccents(...) private static bool CompareIgnoreAccents(string s1, string s2)\n{\n return string.Compare(\n RemoveAccents(s1), RemoveAccents(s2), StringComparison.InvariantCultureIgnoreCase) == 0;\n}\n\nprivate static string RemoveAccents(string s)\n{\n Encoding destEncoding = Encoding.GetEncoding(\"iso-8859-8\");\n\n return destEncoding.GetString(\n Encoding.Convert(Encoding.UTF8, destEncoding, Encoding.UTF8.GetBytes(s)));\n}\n public static string RemoveAccents(this string s)\n{\n Encoding destEncoding = Encoding.GetEncoding(\"iso-8859-8\");\n\n return destEncoding.GetString(\n Encoding.Convert(Encoding.UTF8, destEncoding, Encoding.UTF8.GetBytes(s)));\n}\n if(string.Compare(s1.RemoveAccents(), s2.RemoveAccents(), true) == 0) {\n ...\n"
},
{
"answer_id": 368850,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 9,
"selected": true,
"text": "static string RemoveDiacritics(string text)\n{\n string formD = text.Normalize(NormalizationForm.FormD);\n StringBuilder sb = new StringBuilder();\n\n foreach (char ch in formD)\n {\n UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(ch);\n if (uc != UnicodeCategory.NonSpacingMark)\n {\n sb.Append(ch);\n }\n }\n\n return sb.ToString().Normalize(NormalizationForm.FormC);\n}\n Debug.Assert(\"hello\"==RemoveDiacritics(\"héllo\"));\n static string RemoveDiacritics(string text)\n{\n return string.Concat( \n text.Normalize(NormalizationForm.FormD)\n .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch)!=\n UnicodeCategory.NonSpacingMark)\n ).Normalize(NormalizationForm.FormC);\n}\n"
},
{
"answer_id": 7720903,
"author": "knightpfhor",
"author_id": 17089,
"author_profile": "https://Stackoverflow.com/users/17089",
"pm_score": 7,
"selected": false,
"text": "string s1 = \"hello\";\nstring s2 = \"héllo\";\n\nif (String.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) == 0)\n{\n // both strings are equal\n}\n string s1 = \"HEllO\";\nstring s2 = \"héLLo\";\n\nif (String.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) == 0)\n{\n // both strings are equal\n}\n"
},
{
"answer_id": 20686502,
"author": "Guish",
"author_id": 1456661,
"author_profile": "https://Stackoverflow.com/users/1456661",
"pm_score": 3,
"selected": false,
"text": " public static bool StartsWith(this string str, string value, CultureInfo culture, CompareOptions options)\n {\n if (str.Length >= value.Length)\n return string.Compare(str.Substring(0, value.Length), value, culture, options) == 0;\n else\n return false; \n }\n public static bool StartsWith(this string str, string value, CultureInfo culture, CompareOptions options)\n {\n return str.Length >= value.Length && string.Compare(str.Substring(0, value.Length), value, culture, options) == 0;\n }\n value.ToString().StartsWith(str, CultureInfo.InvariantCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)\n"
},
{
"answer_id": 25606556,
"author": "Newton Carlos Dantas",
"author_id": 1171268,
"author_profile": "https://Stackoverflow.com/users/1171268",
"pm_score": 1,
"selected": false,
"text": " Dim source As String = \"áéíóúç\"\n Dim result As String\n\n Dim bytes As Byte() = Encoding.GetEncoding(\"Cyrillic\").GetBytes(source)\n result = Encoding.ASCII.GetString(bytes)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343/"
] |
359,829 | <p>As our PHP5 OO application grew (in both size and traffic), we decided to revisit the __autoload() strategy.</p>
<p>We always name the file by the class definition it contains, so class Customer would be contained within Customer.php. We used to list the directories in which a file can potentially exist, until the right .php file was found.</p>
<p>This is quite inefficient, because you're potentially going through a number of directories which you don't need to, and doing so on every request (thus, making loads of stat() calls).</p>
<p>Solutions that come to my mind...</p>
<p>-use a naming convention that dictates the directory name (similar to PEAR). Disadvantages: doesn't scale too great, resulting in horrible class names.</p>
<p>-come up with some kind of pre-built array of the locations (propel does this for its __autoload). Disadvantage: requires a rebuild before any deploy of new code.</p>
<p>-build the array "on the fly" and cache it. This seems to be the best solution, as it allows for any class names and directory structure you want, and is fully flexible in that new files just get added to the list. The concerns are: where to store it and what about deleted/moved files. For storage we chose APC, as it doesn't have the disk I/O overhead. With regards to file deletes, it doesn't matter, as you probably don't wanna require them anywhere anyway. As to moves... that's unresolved (we ignore it as historically it didn't happen very often for us).</p>
<p>Any other solutions?</p>
| [
{
"answer_id": 359906,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\n load_class($class_name, $instansiate);\n \n load_class('Customer', TRUE);\n"
},
{
"answer_id": 359965,
"author": "Rob Hruska",
"author_id": 29995,
"author_profile": "https://Stackoverflow.com/users/29995",
"pm_score": -1,
"selected": false,
"text": "__autoload()"
},
{
"answer_id": 360054,
"author": "azkotoki",
"author_id": 28581,
"author_profile": "https://Stackoverflow.com/users/28581",
"pm_score": 2,
"selected": false,
"text": "import debug_backtrace() <?php\n\n loader::import('foo::bar::SomeClass');\n loader::import('foo::bar::OtherClass');\n\n $sc = new SomeClass();\n\n?>\n"
},
{
"answer_id": 362916,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": -1,
"selected": false,
"text": "function __autoload( $class )\n{\n $patterns = array( '%s.class.php', '%s.interface.php' );\n\n foreach( explode( ';', ini_get( 'include_path' ) ) as $dir )\n {\n foreach( $patterns as $pattern )\n {\n $file = sprintf( $pattern, $class );\n $command = sprintf( 'find -L %s -name \"%s\" -print', $dir, $file );\n $output = array();\n $result = -1;\n\n exec( $command, $output, $result );\n\n if ( count( $output ) == 1 )\n {\n require_once( $output[ 0 ] );\n return;\n }\n }\n }\n\n if ( is_integer( strpos( $class, 'Exception' ) ) )\n {\n eval( sprintf( 'class %s extends Exception {}', $class ) );\n return;\n }\n\n if ( ! class_exists( $class, false ) )\n {\n // no exceptions in autoload :(\n die( sprintf( 'Failure to autoload class: \"%s\"', $class ) );\n // or perhaps: die ( '<pre>'.var_export( debug_backtrace(), true ).'</pre>' ); \n }\n}\n"
},
{
"answer_id": 1424469,
"author": "SeanJA",
"author_id": 75924,
"author_profile": "https://Stackoverflow.com/users/75924",
"pm_score": 0,
"selected": false,
"text": "function __autoload($class){\n if($class matches pattern_1 and file_exists($class.pattern_1)){\n //include the file somehow\n } elseif($class matches pattern_2 and file_exists($class.pattern_2)){\n //include the file somehow\n } elseif(file_exists($class.pattern_3)){\n //include the file somehow\n } else {\n //throw an error because that class does not exist?\n }\n}\n"
},
{
"answer_id": 3053563,
"author": "Serty Oan",
"author_id": 332111,
"author_profile": "https://Stackoverflow.com/users/332111",
"pm_score": 0,
"selected": false,
"text": "__autoload() /path/to/root/www/index.php function __autoload($call) {\n require('../php/'.implode('/', explode('___', $call)).'.php');\n}\n"
},
{
"answer_id": 27472370,
"author": "Amir Hassan Azimi",
"author_id": 2891689,
"author_profile": "https://Stackoverflow.com/users/2891689",
"pm_score": 0,
"selected": false,
"text": "function __autoload($class_name) {\n $class_name = strtolower($class_name);\n $path = \"../includes/{$class_name}.php\";\n if (file_exists($path)) {\n require_once($path);\n } else {\n die(\"The file {$class_name}.php could not be found!\");\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8437/"
] |
359,831 | <p>I'm new to RhinoMock's just been doing state unit testing up till now.</p>
<p>How do you test void functions?</p>
<p>Getting the following complie error when setting up expectation,</p>
<p><em>Expression does not produce a value</em></p>
<p>Basically I want to test that a certain mock's method is called a certain amount of times.</p>
<p>Cheers</p>
| [
{
"answer_id": 555675,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 0,
"selected": false,
"text": "Expect.Call(() => someVoidFunction());\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31766/"
] |
359,836 | <p>I'm trying to determine if any changes were made to a particular entity object. Essentially, I want to know if SubmitChanges() will actually change anything. I would prefer to be able to determine this after SubmitChanges() has been called, but it doesn't really matter.</p>
<p>Anyone know how I would do this?</p>
| [
{
"answer_id": 361185,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 2,
"selected": true,
"text": "Public Function HasChanges(ByVal obj As Object) As Boolean\n Dim cs = GetChangeSet()\n If cs.Updates.Contains(obj) Or cs.Inserts.Contains(obj) Or cs.Deletes.Contains(obj) Then Return True\n Return False\nEnd Function\n"
},
{
"answer_id": 361726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "var entityType = typeof(myEntity);\nvar table = dataContext.GetTable<entityType>();\nvar modifiedMembers = table.GetModifiedMembers(myEntity);\n\nif (modifiedMembers.Any())\n{\n ... changes were made\n}\nelse\n{\n ... no changes were made\n}\n"
},
{
"answer_id": 32283484,
"author": "Arash Masir",
"author_id": 3787113,
"author_profile": "https://Stackoverflow.com/users/3787113",
"pm_score": 2,
"selected": false,
"text": " public static class DataContextExtensions\n{\n /// <summary>\n /// Discard all pending changes of current DataContext.\n /// All un-submitted changes, including insert/delete/modify will lost.\n /// </summary>\n /// <param name=\"context\"></param>\n public static void DiscardPendingChanges(this DataContext context)\n {\n context.RefreshPendingChanges(RefreshMode.OverwriteCurrentValues);\n ChangeSet changeSet = context.GetChangeSet();\n if (changeSet != null)\n {\n //Undo inserts\n foreach (object objToInsert in changeSet.Inserts)\n {\n context.GetTable(objToInsert.GetType()).DeleteOnSubmit(objToInsert);\n }\n\n //Undo deletes\n foreach (object objToDelete in changeSet.Deletes)\n {\n context.GetTable(objToDelete.GetType()).InsertOnSubmit(objToDelete);\n }\n\n //Undo updates\n foreach (object objToUpdate in changeSet.Updates)\n {\n context.Refresh(RefreshMode.OverwriteCurrentValues, objToUpdate);\n }\n }\n }\n\n /// <summary>\n /// Refreshes all pending Delete/Update entity objects of current DataContext according to the specified mode.\n /// Nothing will do on Pending Insert entity objects.\n /// </summary>\n /// <param name=\"context\"></param>\n /// <param name=\"refreshMode\">A value that specifies how optimistic concurrency conflicts are handled.</param>\n public static void RefreshPendingChanges(this DataContext context, RefreshMode refreshMode)\n {\n ChangeSet changeSet = context.GetChangeSet();\n if (changeSet != null)\n {\n context.Refresh(refreshMode, changeSet.Deletes);\n context.Refresh(refreshMode, changeSet.Updates);\n }\n }\n /// <summary>\n /// Get list of items of specific type that have been changed in a context.including their original and new values\n /// </summary>\n /// <typeparam name=\"TItem\"></typeparam>\n /// <param name=\"context\"></param>\n /// <returns></returns>\n public static List<ChangedItems<TItem>> GetChangedItems<TItem>(DataContext context)\n {\n // create a dictionary of type TItem for return to caller\n List<ChangedItems<TItem>> changedItems = new List<ChangedItems<TItem>>();\n\n // use reflection to get changed items from data context\n object services = context.GetType().BaseType.GetField(\"services\",\n BindingFlags.NonPublic |\n BindingFlags.Instance |\n BindingFlags.GetField).GetValue(context);\n\n object tracker = services.GetType().GetField(\"tracker\",\n BindingFlags.NonPublic |\n BindingFlags.Instance |\n BindingFlags.GetField).GetValue(services);\n System.Collections.IDictionary trackerItems =\n (System.Collections.IDictionary)tracker.GetType().GetField(\"items\",\n BindingFlags.NonPublic |\n BindingFlags.Instance |\n BindingFlags.GetField).GetValue(tracker);\n\n // iterate through each item in context, adding\n // only those that are of type TItem to the changedItems dictionary\n foreach (System.Collections.DictionaryEntry entry in trackerItems)\n {\n object original = entry.Value.GetType().GetField(\"original\",\n BindingFlags.NonPublic |\n BindingFlags.Instance |\n BindingFlags.GetField).GetValue(entry.Value);\n\n if (entry.Key is TItem && original is TItem)\n {\n changedItems.Add(\n new ChangedItems<TItem>((TItem)entry.Key, (TItem)original)\n );\n }\n }\n return changedItems;\n }\n\n /// <summary>\n /// Returns a list consist a pair if original-current values of each property for the given type.\n /// First KeyValue is current and second one is original.\n /// </summary>/// <typeparam name=\"T\"></typeparam>\n /// <param name=\"context\"></param>\n /// <returns></returns>\n public static List<Dictionary<string, object>> GetObjectDiff<T>(this DataContext context)\n {\n List<Dictionary<string, object>> diff = new List<Dictionary<string, object>>();\n\n try\n {\n Debuging.Info(\"Try to GetObjectDiff\");\n var changes = DataContextExtensions.GetChangedItems<T>(context);\n\n foreach (ChangedItems<T> changedItem in changes)\n {\n PropertyInfo[] props = typeof(T).GetProperties();\n\n var dictCurrent = new Dictionary<string, object>();\n\n foreach (PropertyInfo prp in props)\n {\n object value = prp.GetValue(changedItem.Current, new object[] { });\n dictCurrent.Add(prp.Name, value);\n }\n\n var dictOrigin = new Dictionary<string, object>();\n\n foreach (PropertyInfo prp in props)\n {\n object value = prp.GetValue(changedItem.Original, new object[] { });\n dictOrigin.Add(prp.Name, value);\n }\n\n foreach (var item in dictCurrent)\n {\n var paired = dictOrigin.SingleOrDefault(a => a.Key == item.Key);\n if (paired.Value != item.Value)\n {\n var first = new Dictionary<string, object>();\n first.Add(item.Key,item.Value);\n diff.Add(first);\n\n var second = new Dictionary<string, object>();\n second.Add(paired.Key, paired.Value);\n diff.Add(second);\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debuging.Error(ex, \"DataContextExtensions.GetObjectDiff\");\n }\n return diff;\n }\n\n /// <summary>\n /// Detect if there is any changed object in the context or not.\n /// </summary>\n public static bool HasChanges(this DataContext context)\n {\n ChangeSet changeSet = context.GetChangeSet();\n\n if (changeSet != null)\n {\n return changeSet.Inserts.Any() || changeSet.Deletes.Any() || changeSet.Updates.Any();\n }\n\n return false;\n }\n\n public class ChangedItems<T>\n {\n public ChangedItems(T current, T original)\n {\n this.Current = current;\n this.Original = original;\n }\n\n public T Current { get; set; }\n public T Original { get; set; }\n }\n\n\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] |
359,851 | <p>how can I debug a dll that is not loaded by the java application.</p>
<p>The scenario is this: my java app is loading the jni.dll that is using another dll and that dll is using another dll.</p>
<p>java<->jni.dll<->dll<->dll </p>
<p>I have the source code for all modules</p>
<p>I am using visual studio express when debugging the jni.dll but what should I do to be able to debug the other dlls?</p>
| [
{
"answer_id": 359950,
"author": "Martin Cowie",
"author_id": 42429,
"author_profile": "https://Stackoverflow.com/users/42429",
"pm_score": 0,
"selected": false,
"text": "_asm int 3;"
},
{
"answer_id": 2211768,
"author": "cx0der",
"author_id": 95768,
"author_profile": "https://Stackoverflow.com/users/95768",
"pm_score": 0,
"selected": false,
"text": "int x = 1;\nwhile(x); x 0"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,870 | <p>I am working in a .NET environment where the system occasionally generates log entries for a customer. Messages are then appended to a customer log which can be reviewed at a later time.</p>
<p>For example, if a customer is subscribing to a new service, or a customer has a failed payment attempt, these messages gets appended to the customer log.</p>
<p>At the moment, all messages are hardcoded into the code, e.g "Customer failed to finish payment of XX".</p>
<p>The problem is now that these messages need to be localized in a smart way, such that when a English user reviews the customer log, he gets the messages in English, and when a foreign user reviews the log, he gets them in his language.</p>
<p>What would be the best way to handle this scenario?</p>
| [
{
"answer_id": 360130,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 1,
"selected": false,
"text": "enum LogMessages\n{\n OutOfDiskSpace = 1;\n OutOfMemory = 2;\n OutOfCoffee = 3;\n}\n void LogToDatabase(LogMessages) // forgot to buy coffee again!\nLog(OutOfCoffee);\n string.Format() string.format(\"{0} forgot to buy coffee again. Lazy geek!\", \"I\");\n// yields: \"I forgot to buy coffee again. Lazy geek!\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42272/"
] |
359,880 | <p>I have been tasked with creating a new frontend for a legacy website.</p>
<p>It is written in php (pre-oo), and uses a MySQL database. The hosting provides a .Net package, but does not offer Ms Sql Server. </p>
<p>This is fine, as the database is working fine, but I really want to use Asp.net for the pages. However, most tutorials I've seen on connecting to MySQL from C# require installing an ODBC Driver specifically for MySQL. Not controlling the hosting env, I doubt I'll be able to do just that :)</p>
<p>Have you got any insight to share on this issue?</p>
| [
{
"answer_id": 359892,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": false,
"text": "string MyConString = \"SERVER=localhost;\" +\n \"DATABASE=mydatabase;\" +\n \"UID=testuser;\" +\n \"PASSWORD=testpassword;\";\nMySqlConnection connection = new MySqlConnection(MyConString);\nMySqlCommand command = connection.CreateCommand();\nMySqlDataReader Reader;\ncommand.CommandText = \"select * from mycustomers\";\nconnection.Open();\nReader = command.ExecuteReader();\nwhile (Reader.Read())\n{\n string thisrow = \"\";\n for (int i= 0;i<Reader.FieldCount;i++)\n thisrow+=Reader.GetValue(i).ToString() + \",\";\n listBox1.Items.Add(thisrow);\n}\nconnection.Close();\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21124/"
] |
359,881 | <p>What is the most efficient way of setting values in C# multi-dimensional arrays using a linear index? For example given an array...</p>
<pre><code>int[,,] arr2 = { {{0,1,2}, {3,4,5}, {6,7,8}}
, {{9,10,11}, {12,13,14}, {15,16,17}}
, {{18,19,20}, {21,22,23}, {24,25,26}}
};
</code></pre>
<p>How do I set all the elements to 30 using a linear index ...</p>
<pre><code>//This code does not work
for (int i = 0; i < arr.Length; i++)
{
arr.SetValue(30, i);
}
</code></pre>
<p>Apparently the SetValue() above does not work with multidimensional arrays.</p>
<p>Here is the best solution that I could come up with...</p>
<p>EDIT: Added some clarifications to the code...</p>
<pre><code>static class Program
{
static void Main(string[] args)
{
//Sample input.
int[,,] arr2 = { {{0,1,2}, {3,4,5}, {6,7,8}}
, {{9,10,11}, {12,13,14}, {15,16,17}}
, {{18,19,20}, {21,22,23}, {24,25,26}}
};
int[] arr1 = { 1, 2, 3, 4 };
setElementsTo30(arr2);
setElementsTo30(arr1);
}
//Must be able to process int arrays of arbitrary dimensions and content
private static void setElementsTo30(Array arr)
{
IList<int> cumulativeLength = getCumulativeLengths(arr);
for (int i = 0; i < arr.Length; i++)
{
SetValue(arr, i, 30, cumulativeLength);
}
}
public static void SetValue(this Array arr, int index, object value, IList<int> cumulativeLength)
{
int[] arrayIndex = new int[arr.Rank];
for (int dim = arr.Rank-1; dim >= 0; dim--)
{
arrayIndex[dim] = index / cumulativeLength[dim] % arr.GetLength(dim);
}
arr.SetValue(value, arrayIndex);
}
private static IList<int> getCumulativeLengths(Array arr)
{
List<int> lengths = new List<int>(arr.Rank);
for (int dim = 0; dim < arr.Rank; dim++)
{
int prod = 1;
for (int i = dim + 1; i < arr.Rank; i++)
{
prod *= arr.GetLength(i);
}
lengths.Add(prod);
}
return (IList<int>)lengths;
}
}
</code></pre>
<p>Is there a way to do the same more efficiently and possibly using something provided by the framework itself (i.e. something which can be used without much hassle.)</p>
<p>Thanks,<br>
SDX2000.</p>
| [
{
"answer_id": 359924,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 0,
"selected": false,
"text": "SetValue() {{30,30,30}, {30,30,30}, {30,30,30}}\n , {{30,30,30}, {30,30,30}, {30,30,30}}\n , {{30,30,30}, {30,30,30}, {30,30,30}\n\n}\n IList<int> getCumulativeLengths"
},
{
"answer_id": 360022,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 1,
"selected": false,
"text": "for i=0 to (a*b*c*d)\n\n Array[i % a, (i/a) % b, (i/(a*b) % c, i / (a*b*c)] = 30\n"
},
{
"answer_id": 360051,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": true,
"text": "static void SetValue2(this Array a, object value, int i) {\n int[] indices = new int[a.Rank];\n for (int d = a.Rank - 1; d >= 0; d--) {\n var l = a.GetLength(d);\n indices[d] = i % l;\n i /= l\n }\n a.SetValue(value, indices);\n}\n static void Main(string[] args) {\n int[, ,] arr2 = { \n {{0,1,2}, {3,4,5}, {6,7,8}}, \n {{9,10,11}, {12,13,14}, {15,16,17}}, \n {{18,19,20}, {21,22,23}, {24,25,26}}\n };\n for (int i = 0; i < arr2.Length; i++) {\n arr2.SetValue2(30, i);\n }\n}\n"
},
{
"answer_id": 44892626,
"author": "Makeman",
"author_id": 6627992,
"author_profile": "https://Stackoverflow.com/users/6627992",
"pm_score": 0,
"selected": false,
"text": " public static void CopyToMultidimensionalArray(this IList<object> source, Array target, IList<int> dimensions)\n {\n var indices = new int[dimensions.Count];\n for (var i = 0; i < source.Count; i++)\n {\n var t = i;\n for (var j = indices.Length - 1; j >= 0; j--)\n {\n indices[j] = t % dimensions[j];\n t /= dimensions[j];\n }\n\n target.SetValue(source[i], indices);\n }\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39648/"
] |
359,885 | <p>My application has just started exhibiting strange behaviour.</p>
<p>I can boot it through the Carbide Debugger (using TRK) and it works fine with no visible errors and is left installed on the device.</p>
<p>Any further attempts to launch the application fail, even after a restart. Uninstalling and downloading the .sisx file manually also doesn't work.</p>
<p>Has anyone had any experience like this? Could it be some resource file that is missing, or is there any other way I can find out what is happening?</p>
| [
{
"answer_id": 359924,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 0,
"selected": false,
"text": "SetValue() {{30,30,30}, {30,30,30}, {30,30,30}}\n , {{30,30,30}, {30,30,30}, {30,30,30}}\n , {{30,30,30}, {30,30,30}, {30,30,30}\n\n}\n IList<int> getCumulativeLengths"
},
{
"answer_id": 360022,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 1,
"selected": false,
"text": "for i=0 to (a*b*c*d)\n\n Array[i % a, (i/a) % b, (i/(a*b) % c, i / (a*b*c)] = 30\n"
},
{
"answer_id": 360051,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": true,
"text": "static void SetValue2(this Array a, object value, int i) {\n int[] indices = new int[a.Rank];\n for (int d = a.Rank - 1; d >= 0; d--) {\n var l = a.GetLength(d);\n indices[d] = i % l;\n i /= l\n }\n a.SetValue(value, indices);\n}\n static void Main(string[] args) {\n int[, ,] arr2 = { \n {{0,1,2}, {3,4,5}, {6,7,8}}, \n {{9,10,11}, {12,13,14}, {15,16,17}}, \n {{18,19,20}, {21,22,23}, {24,25,26}}\n };\n for (int i = 0; i < arr2.Length; i++) {\n arr2.SetValue2(30, i);\n }\n}\n"
},
{
"answer_id": 44892626,
"author": "Makeman",
"author_id": 6627992,
"author_profile": "https://Stackoverflow.com/users/6627992",
"pm_score": 0,
"selected": false,
"text": " public static void CopyToMultidimensionalArray(this IList<object> source, Array target, IList<int> dimensions)\n {\n var indices = new int[dimensions.Count];\n for (var i = 0; i < source.Count; i++)\n {\n var t = i;\n for (var j = indices.Length - 1; j >= 0; j--)\n {\n indices[j] = t % dimensions[j];\n t /= dimensions[j];\n }\n\n target.SetValue(source[i], indices);\n }\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
359,887 | <p>I am building a search box (input field) which should make a server call to filter a grid with the text being inserted on it but I need to make this in an smart way, I need to fire the server call only if the user has stopped.
Right now I'm trying to implement it, but if someone knows how to do it I'll be very pleased.
Anyway, if I do it first I'll post the answer here...
Best Regards,
Jaime.</p>
| [
{
"answer_id": 359908,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": true,
"text": "var searchTimeout;\ndocument.getElementById('searchBox').onkeypress = function () {\n if (searchTimeout != undefined) clearTimeout(searchTimeout);\n searchTimeout = setTimeout(callServerScript, 250);\n};\nfunction callServerScript() {\n // your code here\n}\n"
},
{
"answer_id": 359920,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 3,
"selected": false,
"text": "setTimeout setTimeout"
},
{
"answer_id": 360271,
"author": "Jaime Febres",
"author_id": 33205,
"author_profile": "https://Stackoverflow.com/users/33205",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n <script src=\"jquery.js\" type=\"text/javascript\"></script>\n\n<script type=\"text/javascript\">\n var interval = 500;\n var filterValue = \"\";\n $(document).ready(function() {\n $(\".txtSearch\").bind(\"keypress\", logKeyPress);\n });\n function logKeyPress() {\n var now = new Date().getTime();\n var lastTime = this._keyPressedAt || now;\n this._keyPressedAt = now;\n if (!this._monitoringSearch) {\n this._monitoringSearch = true;\n var input = this;\n window.setTimeout(\n function() {\n search(input);\n }, 0);\n }\n }\n function search(input) {\n var now = new Date().getTime();\n var lastTime = input._keyPressedAt;\n if ((now - lastTime) > interval) {\n /*console.log(now);\n console.log(lastTime);\n console.log(now - lastTime);*/\n if (input.value != filterValue) {\n filterValue = input.value;\n //console.log(\"search!\");\n alert(\"search!\");\n }\n input._monitoringSearch = false;\n }\n else {\n window.setTimeout(\n function() {\n search(input);\n }, 0);\n }\n }\n</script>\n"
},
{
"answer_id": 360418,
"author": "Paul",
"author_id": 42847,
"author_profile": "https://Stackoverflow.com/users/42847",
"pm_score": 2,
"selected": false,
"text": "<input type=\"text\" id=\"TxtSearch\" onchange=\"countDown=10;\" />\n\n<script type=\"text/javascript\">\n\nvar countDown = 0;\nfunction SearchTimerTick()\n{\n if(countDown == 1)\n {\n StopTypingCommand();\n countDown = 0;\n }\n\n if(countDown > 0)\n countDown--;\n}\n\nwindow.setInterval(SearchTimerTick,1000);\n\n</script>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33205/"
] |
359,891 | <p>I've hit upon a problem with WSADuplicateSocket, which I'm using to duplicate a socket for use by a different process. It works find when both processes are running under the same Windows user, but fails with error code 10022 (WSAEINVAL) when they are running under different users.</p>
<p>Specifically, the process calling WSADuplicateSocket is running under an admin user account and the target process is running under the System account.</p>
<p>Searching the web, I've found other references to the issue, but no solutions. Does anyone know of a way to resolve this?</p>
<p>Here's the current code:</p>
<pre><code>bool Duplicate(
SOCKET s,
WSAPROTOCOL_INFO* pSocketInfo,
int targetProcessID,
int& errorNum
)
{
memset(pSocketInfo, 0, sizeof(WSAPROTOCOL_INFO));
if (::WSADuplicateSocket(s, targetProcessID, pSocketInfo)
== SOCKET_ERROR)
{
errorNum = ::WSAGetLastError();
return false;
}
return true;
}
</code></pre>
| [
{
"answer_id": 359908,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": true,
"text": "var searchTimeout;\ndocument.getElementById('searchBox').onkeypress = function () {\n if (searchTimeout != undefined) clearTimeout(searchTimeout);\n searchTimeout = setTimeout(callServerScript, 250);\n};\nfunction callServerScript() {\n // your code here\n}\n"
},
{
"answer_id": 359920,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 3,
"selected": false,
"text": "setTimeout setTimeout"
},
{
"answer_id": 360271,
"author": "Jaime Febres",
"author_id": 33205,
"author_profile": "https://Stackoverflow.com/users/33205",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n <script src=\"jquery.js\" type=\"text/javascript\"></script>\n\n<script type=\"text/javascript\">\n var interval = 500;\n var filterValue = \"\";\n $(document).ready(function() {\n $(\".txtSearch\").bind(\"keypress\", logKeyPress);\n });\n function logKeyPress() {\n var now = new Date().getTime();\n var lastTime = this._keyPressedAt || now;\n this._keyPressedAt = now;\n if (!this._monitoringSearch) {\n this._monitoringSearch = true;\n var input = this;\n window.setTimeout(\n function() {\n search(input);\n }, 0);\n }\n }\n function search(input) {\n var now = new Date().getTime();\n var lastTime = input._keyPressedAt;\n if ((now - lastTime) > interval) {\n /*console.log(now);\n console.log(lastTime);\n console.log(now - lastTime);*/\n if (input.value != filterValue) {\n filterValue = input.value;\n //console.log(\"search!\");\n alert(\"search!\");\n }\n input._monitoringSearch = false;\n }\n else {\n window.setTimeout(\n function() {\n search(input);\n }, 0);\n }\n }\n</script>\n"
},
{
"answer_id": 360418,
"author": "Paul",
"author_id": 42847,
"author_profile": "https://Stackoverflow.com/users/42847",
"pm_score": 2,
"selected": false,
"text": "<input type=\"text\" id=\"TxtSearch\" onchange=\"countDown=10;\" />\n\n<script type=\"text/javascript\">\n\nvar countDown = 0;\nfunction SearchTimerTick()\n{\n if(countDown == 1)\n {\n StopTypingCommand();\n countDown = 0;\n }\n\n if(countDown > 0)\n countDown--;\n}\n\nwindow.setInterval(SearchTimerTick,1000);\n\n</script>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35090/"
] |
359,894 | <p>I'm using an image component that has a FromBinary method. Wondering how do I convert my input stream into a byte array</p>
<pre><code>HttpPostedFile file = context.Request.Files[0];
byte[] buffer = new byte[file.ContentLength];
file.InputStream.Read(buffer, 0, file.ContentLength);
ImageElement image = ImageElement.FromBinary(byteArray);
</code></pre>
| [
{
"answer_id": 359984,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 9,
"selected": true,
"text": "byte[] fileData = null;\nusing (var binaryReader = new BinaryReader(Request.Files[0].InputStream))\n{\n fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);\n}\n"
},
{
"answer_id": 360000,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 2,
"selected": false,
"text": "ImageElement image = ImageElement.FromBinary(buffer);\n"
},
{
"answer_id": 659230,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "BinaryReader b = new BinaryReader(file.InputStream);\nbyte[] binData = b.ReadBytes(file.InputStream.Length);\n byte[] binData = b.ReadBytes(file.ContentLength);\n"
},
{
"answer_id": 13805858,
"author": "tinamou",
"author_id": 1498401,
"author_profile": "https://Stackoverflow.com/users/1498401",
"pm_score": 4,
"selected": false,
"text": "Stream stream = file.InputStream;\nstream.Position = 0;\n"
},
{
"answer_id": 37208471,
"author": "Jodda",
"author_id": 1307740,
"author_profile": "https://Stackoverflow.com/users/1307740",
"pm_score": 2,
"selected": false,
"text": "var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);\nbyte[] imgByteArray = webImage.GetBytes();\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461880/"
] |
359,895 | <p>I'm seeing a lot of Javascript errors in IE8 on pages which worked fine in IE7 (and Firefox, Chrome, and Safari). I know that IE made some changes to things like Javascript security. Some of these don't give clear error messages - things like cross-domain violations can end up throwing very vague exceptions.</p>
<p>Let's make a checklist of top offenders when we're troubleshooting IE8 Javascript errors. Please list <strong>one</strong> change to the way IE8 Javascript that would cause a Javascript error.</p>
| [
{
"answer_id": 363092,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 5,
"selected": true,
"text": "1.) document.getElementById( id ); //now only returns the CORRECT matches!\n 3.) .getAttribute( name ); //returns the CORRECT value for the given attribute!\n4.) .setAttribute( name, value ); //actually SETS the name/value CORRECTLY (no more cAmElCaSe crud)!\n5.) CSS Expressions are NO LONGER allowed (deprecated)\n6.) Operation Aborted errors will still be thrown (in some cases) however the cases are fewer, and the error won't kill the entire page/DOM\n7.) The attributes[] array on elements should (from the RC build onwards) be correct in terms of contents, have a length, etc.\n8.) Button elements now submit the contents of the value attribute, NOT the HTML contents of the Button Tag\n window.open(); in IE8 Partner Release is sometimes failing \"claiming\" that the target url is not available (quirky, hard to reproduce)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
] |
359,903 | <p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p>
<p>E.g:</p>
<pre><code>a = ['foo', 'foo', 'boo'] #not valid
b = ['foo', 'foo', 'foo'] #valid
</code></pre>
<p>Whats the best way to go about doing that?</p>
<p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
| [
{
"answer_id": 359945,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 4,
"selected": true,
"text": "if a.count( \"foo\" ) != len(a)\n if a.count( a[0] ) != len(a)\n"
},
{
"answer_id": 359952,
"author": "Andrew Cox",
"author_id": 27907,
"author_profile": "https://Stackoverflow.com/users/27907",
"pm_score": 0,
"selected": false,
"text": "b == [b[0]] * len(b) #valid\na == [a[0]] * len(a) #not valid\n"
},
{
"answer_id": 359963,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 2,
"selected": false,
"text": "if len(set(my_list)) != 1:\n return False\n all_items_are_same = len(set(my_list)) == 1\n # Equality returns True or False\nall_items_are_same = (len(set(my_list)) == 1)\n"
},
{
"answer_id": 360069,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 3,
"selected": false,
"text": "all(a[0] == x for x in a)\n"
},
{
"answer_id": 360107,
"author": "rjmunro",
"author_id": 3408,
"author_profile": "https://Stackoverflow.com/users/3408",
"pm_score": 0,
"selected": false,
"text": ">>> a = ['foo', 'foo', 'boo'] #not valid\n>>> b = ['foo', 'foo', 'foo'] #valid\n>>> reduce(lambda x,y:x==y and x,a)\nFalse\n>>> reduce(lambda x,y:x==y and x,b)\n'foo'\n"
},
{
"answer_id": 360253,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "List Size 10\n0.00530 aList.count(aList[0] ) == len(aList)\n0.00699 for with return False if no match found.\n0.00892 aList == [aList[0]] * len(aList)\n0.00974 len(set(aList)) == 1\n0.02334 all(aList[0] == x for x in aList)\n0.02693 reduce(lambda x,y:x==y and x,aList)\n\nList Size 100\n0.01547 aList.count(aList[0] ) == len(aList)\n0.01623 aList == [aList[0]] * len(aList)\n0.03525 for with return False if no match found.\n0.05122 len(set(aList)) == 1\n0.08079 all(aList[0] == x for x in aList)\n0.22797 reduce(lambda x,y:x==y and x,aList)\n\nList Size 1000\n0.09198 aList == [aList[0]] * len(aList)\n0.11862 aList.count(aList[0] ) == len(aList)\n0.31874 for with return False if no match found.\n0.36145 len(set(aList)) == 1\n0.65861 all(aList[0] == x for x in aList)\n2.24386 reduce(lambda x,y:x==y and x,aList)\n def quickExit( aList ):\n \"\"\"for with return False if no match found.\"\"\"\n value= aList[0]\n for x in aList:\n if x != value: return False\n return True\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34395/"
] |
359,905 | <p>I have a UserControl Library solution which has the following </p>
<p>UserControl
---UserControl project</p>
<pre><code> ---UserControl Test Project
</code></pre>
<p>IN my test project, I am able to add my usercontrol to the tool box. When i drag it and drop it in my forms, it fails. I put in logging and found out that my usercontrol reads a config file. The config file is marked to copy always and exists in the obj\debug and the bin\debug directory/.</p>
<p>However when i drag the usercontrol to a form on my test project, it is trying to get a file from </p>
<p>C:\Documents and Settings\jondoe\Local Settings\Application Data\Microsoft\VisualStudio\8.0\ProjectAssemblies\vqjlihdl01</p>
<p>The above is a result of this</p>
<pre><code>string pluginAssemblyPath = Assembly.GetExecutingAssembly().Location;
DirectoryInfo dirInfo = new DirectoryInfo(pluginAssemblyPath);
pluginAssemblyPath = pluginAssemblyPath.Replace(dirInfo.Name.ToString(),"");
string configFilePath = pluginAssemblyPath + "FileConfig.xml";
</code></pre>
<p>I would have assumed that if i compile in debug mode, the file should be under obj\debug and that should be my assembly path. what gives or is there some setting that i need to do to get it to run correctly so that it can find my config file in the right location?</p>
| [
{
"answer_id": 359940,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 0,
"selected": false,
"text": "if (this.Site != null && this.Site.DesignMode)\n{\n ... design time behavior\n}\nelse\n{\n ... runtime behavior (read config file)\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38230/"
] |
359,921 | <p>I've got a test class in a module that extends another test class in one of its dependency modules. How can I import the dependency's test code into the test scope of the dependent module?</p>
<p>To illiterate, I've got two modules, "module-one" being a dependency of "module-two". <code>SubTestCase</code> is a subclass of <code>TestCase</code>.</p>
<pre>
module-one
\src\test\java\com\example\TestCase.java
module-two
\src\test\java\com\example\SubTestCase.java
</pre>
<p>But the build is failing because the test code of "module-one" is not being imported into "module-two", just the main code. </p>
| [
{
"answer_id": 1206760,
"author": "Rich Seller",
"author_id": 123582,
"author_profile": "https://Stackoverflow.com/users/123582",
"pm_score": 5,
"selected": false,
"text": " <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-jar-plugin</artifactId>\n <executions>\n <execution>\n <phase>package</phase>\n <goals>\n <goal>test-jar</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <dependency>\n <groupId>name.seller.rich</groupId>\n <artifactId>foo</artifactId>\n <version>1.0.0</version>\n <classifier>tests</classifier>\n <scope>test</scope>\n</dependency>\n"
},
{
"answer_id": 12299238,
"author": "Haim Raman",
"author_id": 1625740,
"author_profile": "https://Stackoverflow.com/users/1625740",
"pm_score": 3,
"selected": false,
"text": "<classifier>tests</classifier> <type>test-jar</type> <classifier>tests</classifier> <project>\n ...\n <dependencies>\n <dependency>\n <groupId>name.seller.rich</groupId>\n <artifactId>foo</artifactId>\n <version>1.0.0</version>\n <type>test-jar</type>\n <scope>test</scope>\n </dependency>\n </dependencies>\n ...\n</project>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
359,928 | <p>I want to use a signals/slots library in a project that doesn't use QT. I have pretty basic requirements: </p>
<ol>
<li>Connect two functions with any number of parameters.</li>
<li>Signals can be connected to multiple slots.</li>
<li>Manual disconnection of signal/slot connection.</li>
<li>Decent performance - the application is frame-based (i.e. not event-based) and I want to use the connections in each frame.</li>
</ol>
<p>I've read a <a href="https://web.archive.org/web/20130626010123/http://www.3sinc.com/opensource/boost.bind-vs-sigc2.html" rel="noreferrer">comparison between libsigc++ and Boost.Signals</a>. I've also read that Boost.Signals suffers from poor performance. However, I know there are other libraries and I'm still not sure which library should I choose.</p>
<p>Are there any recommendations for a signals/slots library?</p>
| [
{
"answer_id": 4561541,
"author": "Rodrigo Lopez",
"author_id": 36295,
"author_profile": "https://Stackoverflow.com/users/36295",
"pm_score": 2,
"selected": false,
"text": "COREEXTERN template class COREIMPEXP has_slots<SIGSLOT_DEFAULT_MT_POLICY>;\n"
},
{
"answer_id": 25554107,
"author": "fionbio",
"author_id": 1464716,
"author_profile": "https://Stackoverflow.com/users/1464716",
"pm_score": 3,
"selected": false,
"text": "connect typedef boost::signals2::signal_type<void()>::type signal_type; typedef boost::signals2::signal_type<void(), boost::signals2::keywords::mutex_type<boost::signals2::dummy_mutex> >::type signal_type;"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33982/"
] |
359,931 | <p>EDIT: I found out that I can get it to compile if I cast the IMetadataType object to the TMetadata type. Why do I need to do this?</p>
<p>EDIT #2: The "Values" property is a .NET dictionary of type <TMetadata, TData>.</p>
<p>I have this generic method:</p>
<pre><code>private void FillMetadata<TMetadata, TData>
(Metadata<TMetadata, TData> oMetadata) where TMetadata : IMetadataType
{
IMetadataType o;
oMetadata.Values.Add(o, (TData)(object)GetValue());
}
</code></pre>
<p>I have stripped the implementation to simplify it (I actually use a real object, not the IMetadataType declared here).</p>
<p>My question is, why doesn't this compile? The compile error is on the Add() method: "cannot convert from 'IMetadataType' to 'TMetadata'." Isn't that what the "where" clause on the method is for?</p>
<p>What am I missing?</p>
| [
{
"answer_id": 4561541,
"author": "Rodrigo Lopez",
"author_id": 36295,
"author_profile": "https://Stackoverflow.com/users/36295",
"pm_score": 2,
"selected": false,
"text": "COREEXTERN template class COREIMPEXP has_slots<SIGSLOT_DEFAULT_MT_POLICY>;\n"
},
{
"answer_id": 25554107,
"author": "fionbio",
"author_id": 1464716,
"author_profile": "https://Stackoverflow.com/users/1464716",
"pm_score": 3,
"selected": false,
"text": "connect typedef boost::signals2::signal_type<void()>::type signal_type; typedef boost::signals2::signal_type<void(), boost::signals2::keywords::mutex_type<boost::signals2::dummy_mutex> >::type signal_type;"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44626/"
] |
359,933 | <p>Since IronPython doesn't support attributes I am wondering if there is another way to decorate IronPython classes with attributes, perhaps with reflection?</p>
| [
{
"answer_id": 4561541,
"author": "Rodrigo Lopez",
"author_id": 36295,
"author_profile": "https://Stackoverflow.com/users/36295",
"pm_score": 2,
"selected": false,
"text": "COREEXTERN template class COREIMPEXP has_slots<SIGSLOT_DEFAULT_MT_POLICY>;\n"
},
{
"answer_id": 25554107,
"author": "fionbio",
"author_id": 1464716,
"author_profile": "https://Stackoverflow.com/users/1464716",
"pm_score": 3,
"selected": false,
"text": "connect typedef boost::signals2::signal_type<void()>::type signal_type; typedef boost::signals2::signal_type<void(), boost::signals2::keywords::mutex_type<boost::signals2::dummy_mutex> >::type signal_type;"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1740/"
] |
359,957 | <p>I'm trying to find out the last time a computer came out of standby/hibernate. I know I could get this by watching Win32_PowerManagementEvent, but that doesn't work in this instance as I need something I can poll - any ideas? It doesn't have to be WMI, I'm just assuming that's the place it would be.</p>
<p>Thanks!</p>
| [
{
"answer_id": 360157,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Register-WmiEvent -query \"Select * From Win32_PowerManagementEvent where EventType=7\" -messagedata \"Power Management Resume\" -sourceidentifier \"Resume\"\n"
},
{
"answer_id": 68609093,
"author": "shadowz1337",
"author_id": 1441275,
"author_profile": "https://Stackoverflow.com/users/1441275",
"pm_score": 0,
"selected": false,
"text": "Register-WMIEvent -query \"Select * From Win32_PowerManagementEvent where EventType=4\" `\n -sourceIdentifier \"Action Before Sleep\" `\n -action {\n write-host \"Sleeping time!\"\n nircmd.exe speak text \"Remember Keyboard cover\"\n }\n \n#Get-EventSubscriber\n#unregister-Event -subscriptionid 3\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,959 | <p>When parsing HTML for certain web pages (most notably, any windows live page) I encounter a lot of URL’s in the following format.</p>
<p>http\x3a\x2f\x2fjs.wlxrs.com\x2fjt6xQREgnzkhGufPqwcJjg\x2fempty.htm</p>
<p>These appear to be partially UTF8 escaped strings (\x2f = /, \x3a=:, etc …). Is there a .Net API that can be used to transform these strings into a System.Uri? Seems easy enough to parse but I’m trying to avoid building a new wheel today. </p>
| [
{
"answer_id": 1421687,
"author": "Timwi",
"author_id": 33225,
"author_profile": "https://Stackoverflow.com/users/33225",
"pm_score": 3,
"selected": true,
"text": "HttpUtility.UrlDecode() string input = @\"http\\x3a\\x2f\\x2fjs.wlxrs.com\\x2fjt6xQREgnzkhGufPqwcJjg\\x2fempty.htm\";\nstring output = Regex.Replace(input, @\"\\\\x([0-9a-f][0-9a-f])\",\n m => ((char) int.Parse(m.Groups[1].Value, NumberStyles.HexNumber)).ToString());\n Encoding.UTF8.GetString()"
},
{
"answer_id": 14286569,
"author": "Royi Namir",
"author_id": 859154,
"author_profile": "https://Stackoverflow.com/users/859154",
"pm_score": 0,
"selected": false,
"text": "string output = Regex.Replace(input, @\"\\\\x([0-9a-f][0-9a-f])\",\n m => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString());\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23283/"
] |
359,978 | <p>I have written a C# Windows Forms application to merge the files and folders from a remote folder on one machine ("source" folder is a mapped drive - "Z:\folder") with another remote folder on a different machine ("destination" folder is a UNC path to a shared folder - "\\computername\sharedfolder"). I have Full permissions to both folders. When I run the program on my local machine, it works fine, but when I try to run it from from within the source folder it fails with a security exception.</p>
<p>The failure occurs when calling the DirectoryInfo constructor for the destination folder (i.e., DirectoryInfo(@"\\computername\sharedfolder"). I assume the problem is because I am running the program from a mapped drive. Any workarounds?</p>
<hr>
<p>The specific exception is:
Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>okay, I got my application into Visual Studio 2008 (it was previously coded in 2005), targeted the .NET 3.5 framework, compiled and tried again.</p>
<p>I got the exact same error.</p>
<hr>
<p><strong>UPDATE - RESOLUTION</strong></p>
<p>I tried it with .NET 3.5, and it didn't work, then I noticed that you said 3.5 SP1. The service pack is definately needed.</p>
<p>Problem solved. Thank you.</p>
| [
{
"answer_id": 360025,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 3,
"selected": false,
"text": "@ECHO OFF\nSET CASPOL=%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\CasPol.exe\nCLS\n\n%CASPOL% -pp off\n%CASPOL% -m -ag 1.2 -url file://server/directory/* FullTrust\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45405/"
] |
359,986 | <p>I have a multilingual ASP.NET site; one of the languages is Arabic (ar-SA). To switch between cultures, I use this code: </p>
<pre><code>Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Name)
Thread.CurrentThread.CurrentUICulture = New CultureInfo(Name)
</code></pre>
<p>When displaying the date of an article, for example, I just do this, and the localization API takes care of everything:</p>
<pre><code><%#Eval("DatelineDate","{0:d MMMM yyyy}")%>
</code></pre>
<p>The problem is that this displays dates using the Hijiri (Islamic) calendar (e.g. the year 2008 is rendered as 1429). The client wants to display the dates using the Gregorian calendar (still rendering the month names and everything else in Arabic, of course). How can I do this?</p>
| [
{
"answer_id": 360170,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 5,
"selected": true,
"text": "ar-AE 11 ديسمبر 2008 \nar-BH 11 ديسمبر 2008 \nar-DZ 11 ديسمبر 2008 \nar-EG 11 ديسمبر 2008 \nar-IQ 11 كانون الأول 2008 \nar-JO 11 كانون الأول 2008 \nar-KW 11 ديسمبر 2008 \nar-LB 11 كانون الأول 2008 \nar-LY 11 ديسمبر 2008 \nar-MA 11 دجنبر 2008 \nar-OM 11 ديسمبر 2008 \nar-QA 11 ديسمبر 2008 \nar-SA 13 ذو الحجة 1429 \nar-SY 11 كانون الأول 2008 \nar-TN 11 ديسمبر 2008 \nar-YE 11 ديسمبر 2008 \n Response.Write(\"<table width=300px>\")\n For Each ci As CultureInfo In (From c As CultureInfo In CultureInfo.GetCultures(CultureTypes.AllCultures) Order By c.Name Where c.Name.StartsWith(\"ar-\"))\n Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(ci.Name)\n Thread.CurrentThread.CurrentUICulture = New CultureInfo(ci.Name)\n Response.Write(String.Format(\"<tr><td>{0}</td> <td style='direction:rtl;font-size:20px;'>{1:d MMMM yyyy}</td></tr>\", ci.Name, Today))\n\n Next\n Response.Write(\"</table>\")\n Response.End()\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
359,992 | <p>In my Symbian S60 application, my Options menu works as expected. But the Exit button does nothing.</p>
<p>I am developing with Carbide and have used the UI Designer to add items to the options menu.</p>
<p>Does anyone know how to enable the exit button, or why else it might not work?</p>
<p>Thanks!</p>
| [
{
"answer_id": 360032,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 3,
"selected": true,
"text": "appui::HandleCommandL EEikCmdExit EAknSoftkeyExit? if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit )\n {\n Exit();\n }\n"
},
{
"answer_id": 360044,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 1,
"selected": false,
"text": "HandleCommandL( TInt aCommand ) AppUi HandleCommandL() void MyAppUi::HandleCommandL( TInt aCommand )\n{\n TBool commandHandled = False;\n switch ( aCommand )\n {\n default:\n break;\n }\n\n if ( !commandHandled )\n {\n if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit )\n {\n Exit();\n }\n }\n}\n"
},
{
"answer_id": 360152,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 1,
"selected": false,
"text": "R_AVKON_OPTIONS_EXIT Exit() EEikCmdExit commandHandled EFalse"
},
{
"answer_id": 360166,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 1,
"selected": false,
"text": "void CMyContainerView::HandleCommandL( TInt aCommand )\n {\n\n TBool commandHandled = EFalse;\n switch ( aCommand )\n { \n // ...\n default:\n break;\n }\n\n\n if ( !commandHandled ) \n {\n AppUi()->HandleCommandL(aCommand);\n }\n\n\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
360,007 | <p>I'm trying to deploy <a href="http://code.google.com/p/elmah/" rel="nofollow noreferrer">elmah</a>. For inexplicable reasons, I'm getting an error: .axd files are explicitly forbidden. I've already fixed what I can control (my web.config) and solutions requiring collaboration from the system admin are <em>not</em> available (such as editing machine web.config or updating IIS mappings). I also verified that it works fine on several other machines with ordinary configurations.</p>
<p>Ashx is supposed to be like axd, so are there any differences between axd and ashx I should take into consideration when converting from one to the other?</p>
<p>UPDATE: I think I answered my own question. I change the web.config to read</p>
<pre><code> <add verb="POST,GET,HEAD" path="elmah.ashx" type="Elmah.ErrorLogPageFactory, Elmah" />
</code></pre>
<p>It seems to work. The source code for elmah doesn't even have the string axd in it.</p>
| [
{
"answer_id": 424939,
"author": "MatthewMartin",
"author_id": 33264,
"author_profile": "https://Stackoverflow.com/users/33264",
"pm_score": 3,
"selected": true,
"text": "<add verb=\"POST,GET,HEAD\" path=\"elmah.ashx\" type=\"Elmah.ErrorLogPageFactory, Elmah\" />\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33264/"
] |
360,013 | <p>I'm curious if it's possible to intercept the default methods of 'Edit' mode on a UITableView. Typically you get a free 'delete' button if you side swipe a UITableViewCell that has delegate methods associated with it. I'd like to change the delete to some other, arbitrary selector. Instead of deleting the cell, I'd just like to run a hello world alert dialogue. Is something to this extent possible? </p>
| [
{
"answer_id": 365099,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 2,
"selected": false,
"text": "editAction target"
},
{
"answer_id": 1249754,
"author": "Adam Prall",
"author_id": 1822483,
"author_profile": "https://Stackoverflow.com/users/1822483",
"pm_score": 4,
"selected": false,
"text": "[tableView setEditing: YES animated: YES];\n - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {\n if (editingStyle == UITableViewCellEditingStyleDelete) {\n UIAlertView *alert = [[UIAlertView alloc] \n initWithTitle: @\"Delete\" \n message: @\"Do you really want to delete “George W. Bush”?\" \n delegate: self\n cancelButtonTitle: @\"Cancel\"\n otherButtonTitles: @\"Of course!\", nil];\n }\n}\n [itemList removeObjectAtIndex:indexPath.row];\n[table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];\n"
},
{
"answer_id": 1995747,
"author": "James",
"author_id": 417788,
"author_profile": "https://Stackoverflow.com/users/417788",
"pm_score": 3,
"selected": false,
"text": "- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
360,016 | <p>Today our virtual W2003 server storing our SVN repository (too) became very-very busy. It turned out that it had only 88KB free space left on the C: drive. Not that good. Due to access problems, the only way we could reboot it by killing the busy processes from task manager (McAffee, SqlServer, services.exe) and then gracefully reboot. We freed up some space, the machine is happy again, but our SVN repository is not available anymore.</p>
<p>If I connect from the client, it gives the message "<em>No repository found in 'svn://[mymachine]/repos/[myapp]'</em> "
However, from the server I can see the content using "<em>svnlook tree [rootFolder]</em>" command.</p>
<p>If I navigate to the root folder using Windows Explorer, the following folders are empty (I have no clue if that is normal):</p>
<ul>
<li><em>[rootFolder]/trunk</em> </li>
<li><em>[rootFolder]/tags</em></li>
<li><em>[rootFolder]/branches</em></li>
</ul>
<p>However, the <em>[rootFolder]/db</em> contains many files with the corresponding revision name. The size of the head should be around 600MB but we have also a number of branches. The total size of the [rootFolder] is now ~600MB. Did we loose the branches? Tomorrow we will also know if our backup system worked well. Anyway, does anyone has any idea?</p>
<p><em>[Update after solution found]</em></p>
<p>Thanx for all who submitted answers, they were very useful in resolving the trouble.
During the crash, the SVN service got corrupted, while the data remained intact. Reinstallation of the service has solved the problem.</p>
| [
{
"answer_id": 365099,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 2,
"selected": false,
"text": "editAction target"
},
{
"answer_id": 1249754,
"author": "Adam Prall",
"author_id": 1822483,
"author_profile": "https://Stackoverflow.com/users/1822483",
"pm_score": 4,
"selected": false,
"text": "[tableView setEditing: YES animated: YES];\n - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {\n if (editingStyle == UITableViewCellEditingStyleDelete) {\n UIAlertView *alert = [[UIAlertView alloc] \n initWithTitle: @\"Delete\" \n message: @\"Do you really want to delete “George W. Bush”?\" \n delegate: self\n cancelButtonTitle: @\"Cancel\"\n otherButtonTitles: @\"Of course!\", nil];\n }\n}\n [itemList removeObjectAtIndex:indexPath.row];\n[table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];\n"
},
{
"answer_id": 1995747,
"author": "James",
"author_id": 417788,
"author_profile": "https://Stackoverflow.com/users/417788",
"pm_score": 3,
"selected": false,
"text": "- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24451/"
] |
360,024 | <p>I'd like to set a connection string programmatically, with absolutely no change to any config files / registry keys.</p>
<p>I have this piece of code, but unfortunately it throws an exception with "the configuration is read only".</p>
<pre><code>ConfigurationManager.ConnectionStrings.Clear();
string connectionString = "Server=myserver;Port=8080;Database=my_db;...";
ConnectionStringSettings connectionStringSettings =
new ConnectionStringSettings("MyConnectionStringKey", connectionString);
ConfigurationManager.ConnectionStrings.Add(connectionStringSettings);
</code></pre>
<p><strong>Edit:</strong>
The problem is that I have existing code that reads the connection string from the configuration. So setting the config string manually, or through a resource, don't seem like valid options. What I really need is a way to modify the configuration programmatically.</p>
| [
{
"answer_id": 360052,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 1,
"selected": false,
"text": "Resources.Default.ConnectionString = \"Server=myserver;\" // etc conn.ConnectionString = Resources.Default.ConnectionString"
},
{
"answer_id": 377573,
"author": "David Gardiner",
"author_id": 25702,
"author_profile": "https://Stackoverflow.com/users/25702",
"pm_score": 8,
"selected": true,
"text": "var settings = ConfigurationManager.ConnectionStrings[ 0 ];\n\nvar fi = typeof( ConfigurationElement ).GetField( \"_bReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic );\n\nfi.SetValue(settings, false);\n\nsettings.ConnectionString = \"Data Source=Something\";\n"
},
{
"answer_id": 1312739,
"author": "Rebecca",
"author_id": 119624,
"author_profile": "https://Stackoverflow.com/users/119624",
"pm_score": 3,
"selected": false,
"text": "Configuration config = WebConfigurationManager.OpenWebConfiguration(\"~\");\nConnectionStringsSection section = config.GetSection(\"connectionStrings\") as ConnectionStringsSection;\nif (section != null)\n{\n section.ConnectionStrings[\"MyConnectionString\"].ConnectionString = connectionString;\n config.Save();\n}\n"
},
{
"answer_id": 7484128,
"author": "Rupert Davis",
"author_id": 954585,
"author_profile": "https://Stackoverflow.com/users/954585",
"pm_score": 3,
"selected": false,
"text": "string NewConnection = \"\";\n// get the user to supply connection details\nfrmSetSQLConnection frm = new frmSetSQLConnection();\nfrm.ShowDialog();\nif (frm.DialogResult == DialogResult.OK)\n{\n // here we set the users connection string for the database\n // Get the application configuration file.\n System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n // Get the connection strings section.\n ConnectionStringsSection csSection = config.ConnectionStrings;\n foreach (ConnectionStringSettings connection3 in csSection.ConnectionStrings)\n {\n // Here we check for the preset string - this could be done by item no as well\n if (connection3.ConnectionString == \"Data Source=SQL204\\\\SQL2008;Initial Catalog=Transition;Integrated Security=True\")\n {\n // amend the details and save\n connection3.ConnectionString = frm.Connection;\n NewConnection = frm.Connection;\n break;\n }\n }\n config.Save(ConfigurationSaveMode.Modified);\n // reload the config file so the new values are available\n\n ConfigurationManager.RefreshSection(csSection.SectionInformation.Name);\n\n return clsDBMaintenance.UpdateDatabase(NewConnection))\n}\n"
},
{
"answer_id": 25063273,
"author": "NotNormal",
"author_id": 3896313,
"author_profile": "https://Stackoverflow.com/users/3896313",
"pm_score": 3,
"selected": false,
"text": "var settings = ConfigurationManager.ConnectionStrings;\nvar element = typeof(ConfigurationElement).GetField(\"_bReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\nvar collection = typeof(ConfigurationElementCollection).GetField(\"bReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\n\nelement.SetValue(settings, false);\ncollection.SetValue(settings, false);\n\nsettings.Add(new ConnectionStringSettings(\"ConnectionStringName\", connectionString));\n\n// Repeat above line as necessary\n\ncollection.SetValue(settings, true);\nelement.SetValue(settings, true);\n"
},
{
"answer_id": 55248932,
"author": "Andrew McClellan",
"author_id": 7108229,
"author_profile": "https://Stackoverflow.com/users/7108229",
"pm_score": 2,
"selected": false,
"text": "var fi = typeof( ConfigurationElement ).GetField( \"_bReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic );\n\nif(fi == null)\n{\n fi = typeof(System.Configuration.ConfigurationElementCollection).GetField(\"_readOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\n}\n\nfi.SetValue(settings, false);\n\nsettings.ConnectionString = \"Data Source=Something\";\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
360,028 | <p>Moments ago <a href="http://twitter.com/codinghorror/status/1051535711" rel="nofollow noreferrer">Jeff Atwood said the following on twitter</a>:</p>
<blockquote>
<p>Look, I love rapid new software releases, but the frequency of WordPress releases is just ridiculous.</p>
</blockquote>
<p>Which makes me think, <strong>how often should you release software updates?</strong></p>
<ul>
<li>Daily?</li>
<li>Weekly?</li>
<li>Monthly?</li>
<li>Yearly?</li>
</ul>
<p>Whats the best release strategy?</p>
| [
{
"answer_id": 360091,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 3,
"selected": false,
"text": "releaseDelta = updateTime/((1/365)*(60*60*8))\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
360,030 | <p>I have a Java method which returns an array of doubles. I would then like to store these values in individual variables in the calling function. Is there an elegant way of doing this in Java.</p>
<p>I could write it as this:</p>
<pre><code>double[] returnValues = calculateSomeDoubles();
double firstVar = returnValues[0];
double secondVar = returnValues[1];
</code></pre>
<p>I was just wondering if there was some way of compressing this down to a single line? Something like:</p>
<pre><code>(firstVar, secondVar) = calculateSomeDoubles();
</code></pre>
<p>This type of thing is quite easy when scripting, but the stronger typing of Java means it probably isn't possible.</p>
| [
{
"answer_id": 360060,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": " SomeUtility.fill( myObject , withDoublesFromMethod() );\n"
},
{
"answer_id": 360117,
"author": "Nick Holt",
"author_id": 41423,
"author_profile": "https://Stackoverflow.com/users/41423",
"pm_score": 4,
"selected": true,
"text": "MyObject myObject = calculateMyObject();\n"
},
{
"answer_id": 360207,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 1,
"selected": false,
"text": "void methode(double[] array)\n List methode()\n double[] methode()\n"
},
{
"answer_id": 360230,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 0,
"selected": false,
"text": "List<Double> myVars = Arrays.asList(calculateSomeDoubles());\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] |
360,036 | <p>Is there any way to split a long string of HTML after N words? Obviously I could use:</p>
<pre><code>' '.join(foo.split(' ')[:n])
</code></pre>
<p>to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.</p>
<p>I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal.</p>
<p>For example, say I have the text:</p>
<pre><code><p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit of linked text in it
</a>.
</p>
</code></pre>
<p>And I ask it to split after 5 words, it should return:</p>
<pre><code><p>This is some text with</p>
</code></pre>
<p>7 words:</p>
<pre><code><p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit
</a>
</p>
</code></pre>
| [
{
"answer_id": 360356,
"author": "JV.",
"author_id": 33612,
"author_profile": "https://Stackoverflow.com/users/33612",
"pm_score": 0,
"selected": false,
"text": "import re\nfrom BeautifulSoup import BeautifulSoup\nimport tidy\n\ndef remove_html_tags(data):\n p = re.compile(r'<.*?>')\n return p.sub('', data)\n\ninput_string='<p>This is some text with a <a href=\"http://www.example.com/\" '\\\n 'title=\"Example link\">bit of linked text in it</a></p>'\n\ns=remove_html_tags(input_string).split(' ')[:7]\n\n###required to ensure that only the last occurrence of the nth word is \n# taken into account for truncating. \n# coz if the nth word could be 'a'/'and'/'is'....etc \n# which may occur multiple times within n words \ntemp=input_string\nk=s.count(s[-1])\ni=1\nj=0\nwhile i<=k:\n j+=temp.find(s[-1])\n temp=temp[j+len(s[-1]):]\n i+=1\n#### \noutput_string=input_string[:j+len(s[-1])]\n\nprint \"\\nBeautifulSoup\\n\", BeautifulSoup(output_string)\nprint \"\\nTidy\\n\", tidy.parseString(output_string)\n BeautifulSoup\n<p>This is some text with a <a href=\"http://www.example.com/\" title=\"Example link\">bit</a></p>\n\nTidy\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n<html>\n<head>\n<meta name=\"generator\" content=\n\"HTML Tidy for Linux/x86 (vers 6 November 2007), see www.w3.org\">\n<title></title>\n</head>\n<body>\n<p>This is some text with a <a href=\"http://www.example.com/\"\ntitle=\"Example link\">bit</a></p>\n</body>\n</html>\n `p = re.compile(r'<[^<]*?>')`\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408/"
] |
360,040 | <p>When given a static set of objects (static in the sense that once loaded it seldom if ever changes) into which repeated concurrent lookups are needed with optimal performance, which is better, a <code>HashMap</code> or an array with a binary search using some custom comparator?</p>
<p>Is the answer a function of object or struct type? Hash and/or Equal function performance? Hash uniqueness? List size? <code>Hashset</code> size/set size?</p>
<p>The size of the set that I'm looking at can be anywhere from 500k to 10m - incase that information is useful.</p>
<p>While I'm looking for a C# answer, I think the true mathematical answer lies not in the language, so I'm not including that tag. However, if there are C# specific things to be aware of, that information is desired.</p>
| [
{
"answer_id": 360059,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 6,
"selected": false,
"text": "hashCode()\n{\n return 0;\n}\n Array class Program\n{\n private const long capacity = 10_000_000;\n\n private static void Main(string[] args)\n {\n testLongValues();\n Console.WriteLine();\n testStringValues();\n\n Console.ReadLine();\n }\n\n private static void testStringValues()\n {\n Dictionary<String, String> dict = new Dictionary<String, String>();\n String[] arr = new String[capacity];\n Stopwatch stopwatch = new Stopwatch();\n\n Console.WriteLine(\"\" + capacity + \" String values...\");\n\n stopwatch.Start();\n\n populateStringArray(arr);\n\n stopwatch.Stop();\n Console.WriteLine(\"Populate String Array: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n stopwatch.Start();\n\n populateStringDictionary(dict, arr);\n\n stopwatch.Stop();\n Console.WriteLine(\"Populate String Dictionary: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n stopwatch.Start();\n\n Array.Sort(arr);\n\n stopwatch.Stop();\n Console.WriteLine(\"Sort String Array: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n stopwatch.Start();\n\n searchStringDictionary(dict, arr);\n\n stopwatch.Stop();\n Console.WriteLine(\"Search String Dictionary: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n stopwatch.Start();\n\n searchStringArray(arr);\n\n stopwatch.Stop();\n Console.WriteLine(\"Search String Array: \" + stopwatch.ElapsedMilliseconds);\n\n }\n\n /* Populate an array with random values. */\n private static void populateStringArray(String[] arr)\n {\n for (long i = 0; i < capacity; i++)\n {\n arr[i] = generateRandomString(20) + i; // concatenate i to guarantee uniqueness\n }\n }\n\n /* Populate a dictionary with values from an array. */\n private static void populateStringDictionary(Dictionary<String, String> dict, String[] arr)\n {\n for (long i = 0; i < capacity; i++)\n {\n dict.Add(arr[i], arr[i]);\n }\n }\n\n /* Search a Dictionary for each value in an array. */\n private static void searchStringDictionary(Dictionary<String, String> dict, String[] arr)\n {\n for (long i = 0; i < capacity; i++)\n {\n String value = dict[arr[i]];\n }\n }\n\n /* Do a binary search for each value in an array. */\n private static void searchStringArray(String[] arr)\n {\n for (long i = 0; i < capacity; i++)\n {\n int index = Array.BinarySearch(arr, arr[i]);\n }\n }\n\n private static void testLongValues()\n {\n Dictionary<long, long> dict = new Dictionary<long, long>(Int16.MaxValue);\n long[] arr = new long[capacity];\n Stopwatch stopwatch = new Stopwatch();\n\n Console.WriteLine(\"\" + capacity + \" Long values...\");\n\n stopwatch.Start();\n\n populateLongDictionary(dict);\n\n stopwatch.Stop();\n Console.WriteLine(\"Populate Long Dictionary: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n stopwatch.Start();\n\n populateLongArray(arr);\n\n stopwatch.Stop();\n Console.WriteLine(\"Populate Long Array: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n stopwatch.Start();\n\n searchLongDictionary(dict);\n\n stopwatch.Stop();\n Console.WriteLine(\"Search Long Dictionary: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n stopwatch.Start();\n\n searchLongArray(arr);\n\n stopwatch.Stop();\n Console.WriteLine(\"Search Long Array: \" + stopwatch.ElapsedMilliseconds);\n }\n\n /* Populate an array with long values. */\n private static void populateLongArray(long[] arr)\n {\n for (long i = 0; i < capacity; i++)\n {\n arr[i] = i;\n }\n }\n\n /* Populate a dictionary with long key/value pairs. */\n private static void populateLongDictionary(Dictionary<long, long> dict)\n {\n for (long i = 0; i < capacity; i++)\n {\n dict.Add(i, i);\n }\n }\n\n /* Search a Dictionary for each value in a range. */\n private static void searchLongDictionary(Dictionary<long, long> dict)\n {\n for (long i = 0; i < capacity; i++)\n {\n long value = dict[i];\n }\n }\n\n /* Do a binary search for each value in an array. */\n private static void searchLongArray(long[] arr)\n {\n for (long i = 0; i < capacity; i++)\n {\n int index = Array.BinarySearch(arr, arr[i]);\n }\n }\n\n /**\n * Generate a random string of a given length.\n * Implementation from https://stackoverflow.com/a/1344258/1288\n */\n private static String generateRandomString(int length)\n {\n var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n var stringChars = new char[length];\n var random = new Random();\n\n for (int i = 0; i < stringChars.Length; i++)\n {\n stringChars[i] = chars[random.Next(chars.Length)];\n }\n\n return new String(stringChars);\n }\n}\n"
},
{
"answer_id": 360138,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 2,
"selected": false,
"text": " for (int i = 0; i < 1000 * 1000; i++) {\n c.GetHashCode();\n }\n for (int i = 0; i < 1000 * 1000; i++) {\n for (int j = 0; j < 20; j++)\n c.CompareTo(d);\n }\n"
},
{
"answer_id": 28566419,
"author": "ialiashkevich",
"author_id": 1411186,
"author_profile": "https://Stackoverflow.com/users/1411186",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace BinaryVsDictionary\n{\n internal class Program\n {\n private const long Capacity = 10000000;\n\n private static readonly Dictionary<long, long> Dict = new Dictionary<long, long>(Int16.MaxValue);\n private static readonly long[] Arr = new long[Capacity];\n\n private static void Main(string[] args)\n {\n Stopwatch stopwatch = new Stopwatch();\n\n stopwatch.Start();\n\n for (long i = 0; i < Capacity; i++)\n {\n Dict.Add(i, i);\n }\n\n stopwatch.Stop();\n\n Console.WriteLine(\"Populate Dictionary: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n\n stopwatch.Start();\n\n for (long i = 0; i < Capacity; i++)\n {\n Arr[i] = i;\n }\n\n stopwatch.Stop();\n\n Console.WriteLine(\"Populate Array: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n\n stopwatch.Start();\n\n for (long i = 0; i < Capacity; i++)\n {\n long value = Dict[i];\n// Console.WriteLine(value + \" : \" + RandomNumbers[i]);\n }\n\n stopwatch.Stop();\n\n Console.WriteLine(\"Search Dictionary: \" + stopwatch.ElapsedMilliseconds);\n\n stopwatch.Reset();\n\n stopwatch.Start();\n\n for (long i = 0; i < Capacity; i++)\n {\n long value = BinarySearch(Arr, 0, Capacity, i);\n// Console.WriteLine(value + \" : \" + RandomNumbers[i]);\n }\n\n stopwatch.Stop();\n\n Console.WriteLine(\"Search Array: \" + stopwatch.ElapsedMilliseconds);\n\n Console.ReadLine();\n }\n\n private static long BinarySearch(long[] arr, long low, long hi, long value)\n {\n while (low <= hi)\n {\n long median = low + ((hi - low) >> 1);\n\n if (arr[median] == value)\n {\n return median;\n }\n\n if (arr[median] < value)\n {\n low = median + 1;\n }\n else\n {\n hi = median - 1;\n }\n }\n\n return ~low;\n }\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18941/"
] |
360,063 | <p>I often run into code that has to perform lots of checks and ends up being indented at least five or six levels before really doing anything. I am wondering what alternatives exist.</p>
<p>Below I've posted an example of what I'm talking about (which isn't actual production code, just something I came up with off the top of my head).</p>
<pre><code>public String myFunc(SomeClass input)
{
Object output = null;
if(input != null)
{
SomeClass2 obj2 = input.getSomeClass2();
if(obj2 != null)
{
SomeClass3 obj3 = obj2.getSomeClass3();
if(obj3 != null && !BAD_OBJECT.equals(obj3.getSomeProperty()))
{
SomeClass4 = obj3.getSomeClass4();
if(obj4 != null)
{
int myVal = obj4.getSomeValue();
if(BAD_VALUE != myVal)
{
String message = this.getMessage(myVal);
if(MIN_VALUE <= message.length() &&
message.length() <= MAX_VALUE)
{
//now actually do stuff!
message = result_of_stuff_actually_done;
}
}
}
}
}
}
return output;
}
</code></pre>
| [
{
"answer_id": 360071,
"author": "ieure",
"author_id": 45224,
"author_profile": "https://Stackoverflow.com/users/45224",
"pm_score": 3,
"selected": false,
"text": "if (input == null) {\n return output;\n}\n"
},
{
"answer_id": 360072,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "public String myFunc(SomeClass input)\n{\n Object output = null;\n\n if(input == null) return \"\";\n\n SomeClass2 obj2 = input.getSomeClass2();\n if(obj2 == null) return \"\";\n\n SomeClass3 obj3 = obj2.getSomeClass3();\n if(obj3 == null || BAD_OBJECT.equals(obj3.getSomeProperty()))\n {\n return \"\";\n }\n\n SomeClass4 = obj3.getSomeClass4();\n if(obj4 == null) return \"\";\n\n int myVal = obj4.getSomeValue();\n if(BAD_VALUE == myVal) return \"\";\n\n String message = this.getMessage(myVal);\n if(MIN_VALUE <= message.length() &&\n message.length() <= MAX_VALUE)\n {\n //now actually do stuff!\n message = result_of_stuff_actually_done;\n }\n\n return output;\n}\n return \"\";"
},
{
"answer_id": 360082,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 2,
"selected": false,
"text": "public String myFunc(SomeClass input)\n{\n Object output = null;\n\n if (input == null)\n {\n return null;\n }\n\n SomeClass2 obj2 = input.getSomeClass2();\n if (obj2 == null)\n { \n return null;\n }\n\n SomeClass3 obj3 = obj2.getSomeClass3();\n if (obj3 == null || BAD_OBJECT.equals(obj3.getSomeProperty()))\n {\n return null;\n }\n\n SomeClass4 = obj3.getSomeClass4();\n if (obj4 == null)\n {\n return null;\n }\n int myVal = obj4.getSomeValue();\n if (BAD_VALUE == myVal)\n {\n return null;\n }\n String message = this.getMessage(myVal);\n if (MIN_VALUE <= message.length() &&\n message.length() <= MAX_VALUE)\n {\n //now actually do stuff!\n message = result_of_stuff_actually_done;\n }\n return output;\n}\n"
},
{
"answer_id": 360093,
"author": "Stephane Grenier",
"author_id": 39371,
"author_profile": "https://Stackoverflow.com/users/39371",
"pm_score": 1,
"selected": false,
"text": "if(input == null && input.getSomeClass2() == null && ...)\n return null;\n\n// Do what you want.\n if(input == null && input.getSomeClass2() == null)\n return null;\n\nSomeClass2 obj2 = input.getSomeClass2();\nif(obj2 == null)\n return null;\n\n...\n\n// Do what you want.\n"
},
{
"answer_id": 360127,
"author": "Jamal Hansen",
"author_id": 2035722,
"author_profile": "https://Stackoverflow.com/users/2035722",
"pm_score": 0,
"selected": false,
"text": "public String myFunc(SomeClass input)\n{\n Object output = null;\n\n if (inputIsValid(input))\n {\n //now actually do stuff!\n message = result_of_stuff_actually_done;\n } \n\n return output;\n}\n\n\nprivate bool inputIsValid(SomeClass input)\n{\n\n // *****************************************\n // convert these to guard style if you like \n // ***************************************** \n if(input != null)\n {\n SomeClass2 obj2 = input.getSomeClass2();\n if(obj2 != null)\n {\n SomeClass3 obj3 = obj2.getSomeClass3();\n if(obj3 != null && !BAD_OBJECT.equals(obj3.getSomeProperty()))\n {\n SomeClass4 = obj3.getSomeClass4();\n if(obj4 != null)\n {\n int myVal = obj4.getSomeValue();\n if(BAD_VALUE != myVal)\n {\n String message = this.getMessage(myVal);\n if(MIN_VALUE <= message.length() &&\n message.length() <= MAX_VALUE)\n {\n return true;\n }\n }\n }\n }\n }\n }\n return false;\n}\n"
},
{
"answer_id": 360251,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": "// validates the user has amount\nif( amount > other && that != var || startsAligned() != false ) {\n}\n if( isValidAmount() ) {\n}\n\nprivate boolean isValidAmount() {\n return ( amount > other && that != var || startsAligned() != false );\n}\n // these are business rules\n// then it should be clear that those rules are\n// and what they do.\n\n// internal state of the object.\nprivate SomeClass2 obj2;\nprivate SomeClass3 obj3;\nprivate SomeClass4 obj4;\n\n//public String myFunc( SomeClass input ) {\npublic String myComplicatedValidation( SomeClass input ) {\n this.input = input;\n if ( isValidInput() && \n isRuleTwoReady() &&\n isRuleTreeDifferentOf( BAD_OBJECT ) &&\n isRuleFourDifferentOf( BAD_VALUE ) && \n isMessageLengthInRenge( MIN_VALUE , MAX_VALUE ) ) { \n message = resultOfStuffActuallyDone();\n }\n}\n\n// These method names are self explaining what they do.\nprivate final boolean isValidInput() {\n return this.input != null;\n}\nprivate final boolean isRuleTwoReady() {\n obj2 = input.getSomeClass2();\n return obj2 != null ;\n}\nprivate final boolean isRuleTreeDifferentOf( Object badObject ) {\n obj3 = obj2.getSomeClass3();\n return obj3 != null && !badObject.equals( obj3.getSomeProperty() );\n}\nprivate final boolean isRuleFourDifferentOf( int badValue ) {\n obj4 = obj3.getSomeClass4();\n return obj4 != null && obj4.getSomeValue() != badValue;\n}\nprivate final boolean isMessageLengthInRenge( int min, int max ) {\n String message = getMessage( obj4.getSomeValue() );\n int length = message.length();\n return length >= min && length <= max;\n}\n if ( isValidInput() && \n isRuleTwoReady() &&\n isRuleTreeDifferentOf( BAD_OBJECT ) &&\n isRuleFourDifferentOf( BAD_VALUE ) && \n isMessageLengthInRenge( MIN_VALUE , MAX_VALUE ) ) { \n message = resultOfStuffActuallyDone();\n }\n if is valid input \nand rule two is ready \nand rule three is not BAD OBJECT \nand rule four is no BAD_VALUE \nand the message length is in range\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
360,088 | <p>I am planning a fresh installation of <strong>SQL Server 2005</strong> on a new machine, which I have to order. I know that <strong>tempdb tuning</strong> is very important to the overall <strong>performance</strong> of the SQL Server instance.</p>
<p>I've read that it's best practice to create as many tempdb files as you have CPU's (or cores?). Is that correct? Are there any other recommendations, e.g. for harddisk/RAID setup configuration I should pay attention to?</p>
<p><em>Thanks!</em></p>
| [
{
"answer_id": 362636,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": false,
"text": "ALTER DATABASE Envir. Size DB Size (MB) Log Size (MB)\n ----------- ------------ -------------\n Small 1024 256\n Medium 5120 1024\n Large 10024 2048\n sys.dm_db_file_space_usage sys.dm_db_session_space_usage sys.dm_db_task_space_usage"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6461/"
] |
360,111 | <p>I have an array of different type objects and I use a BinaryWriter to convert each item to its binary equivalent so I can send the structure over the network.</p>
<p>I currently do something like </p>
<pre><code>for ( i=0;i<tmpArrayList.Count;i++)
{
object x=tmpArrayList[i];
if (x.GetType() == typeof(byte))
{
wrt.Write((byte)x);
}
........
</code></pre>
<p>The problem is that if miss a type them my code might break in the future.</p>
<p>I would like to do something like.</p>
<pre><code>object x=tmpArrayList[i];
wrt.Write(x);
</code></pre>
<p>but it doesn't work unless I do each cast. </p>
<p>Edit:</p>
<p>After consulting the answers this is what I came up with for the function. For testing this function sends the array to syslog.</p>
<pre><code> private void TxMsg(ArrayList TxArray,IPAddress ipaddress)
{
Byte[] txbuf=new Byte[0];
int sz=0;
// caculate size of txbuf
foreach (Object o in TxArray)
{
if ( o is String )
{
sz+=((String)(o)).Length;
}
else if ( o is Byte[] )
{
sz+=((Byte[])(o)).Length;
}
else if ( o is Char[] )
{
sz+=((Char[])(o)).Length;
}
else // take care of non arrays
{
sz+=Marshal.SizeOf(o);
}
}
txbuf = new Byte[sz];
System.IO.MemoryStream stm_w = new System.IO.MemoryStream( txbuf, 0,txbuf.Length);
System.IO.BinaryWriter wrt = new System.IO.BinaryWriter( stm_w );
foreach (Object o in TxArray)
{
bool otypefound=false;
if (o is String) // strings need to be sent one byte per char
{
otypefound=true;
String st=(String)o;
for(int i=0;i<st.Length;i++)
{
wrt.Write((byte)st[i]);
}
}
else
{
foreach (MethodInfo mi in typeof(BinaryWriter).GetMethods())
{
if (mi.Name == "Write")
{
ParameterInfo[] pi = mi.GetParameters();
if ((pi.Length == 1)&&(pi[0].ParameterType==o.GetType()))
{
otypefound=true;
mi.Invoke(wrt, new Object[] { o });
}
}
}
}
if(otypefound==false)
{
throw new InvalidOperationException("Cannot write data of type " + o.GetType().FullName);
}
}
IPEndPoint endpoint = new IPEndPoint(ipaddress, 514); //syslog port
UdpClient udpClient_txmsg = new UdpClient();
udpClient_txmsg.Send(txbuf, txbuf.Length,endpoint); // send udp packet to syslog
}
</code></pre>
| [
{
"answer_id": 360121,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "if (x.GetType() == typeof(byte))\n if (x is byte)\n"
},
{
"answer_id": 360150,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "Dictionary"
},
{
"answer_id": 360193,
"author": "moffdub",
"author_id": 10759,
"author_profile": "https://Stackoverflow.com/users/10759",
"pm_score": 1,
"selected": false,
"text": "class Writer\n{\n void write(byte b)\n {\n // write bytes here\n }\n\n void write(Writable something)\n {\n something.writeOn(this);\n }\n}\n\ninterface Writeable\n{\n void writeOn(Writer writer);\n}\n\nclass SomeObject implements Writeable\n{\n private Object someData;\n private Object moreData;\n\n void writeOn(Writer writer)\n {\n writer.write(convertToByte(someData));\n writer.write(convertToByte(moreData));\n }\n}\n\nclass AnotherObject implements Writeable\n{\n private int x;\n private int y;\n private int z;\n\n void writeOn(Writer writer)\n {\n writer.write((byte)x);\n writer.write((byte)y);\n writer.write((byte)z);\n }\n}\n"
},
{
"answer_id": 360306,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": true,
"text": "using System.IO;\nusing System;\nusing System.Reflection;\nusing System.Collections.Generic;\nnamespace ConsoleApplication14\n{\n public class Program\n {\n public static void Main()\n {\n Dictionary<Type, MethodInfo> mapping = new Dictionary<Type, MethodInfo>();\n foreach (MethodInfo mi in typeof(BinaryWriter).GetMethods())\n {\n if (mi.Name == \"Write\")\n {\n ParameterInfo[] pi = mi.GetParameters();\n if (pi.Length == 1)\n mapping[pi[0].ParameterType] = mi;\n }\n }\n\n List<Object> someData = new List<Object>();\n someData.Add((Byte)10);\n someData.Add((Int32)10);\n someData.Add((Double)10);\n someData.Add((Char)10);\n someData.Add(\"Test\");\n\n using (FileStream file = new FileStream(@\"C:\\test.dat\", FileMode.Create, FileAccess.ReadWrite))\n using (BinaryWriter writer = new BinaryWriter(file))\n {\n foreach (Object o in someData)\n {\n MethodInfo mi;\n if (mapping.TryGetValue(o.GetType(), out mi))\n {\n mi.Invoke(writer, new Object[] { o });\n }\n else\n throw new InvalidOperationException(\"Cannot write data of type \" + o.GetType().FullName);\n }\n }\n }\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32958/"
] |
360,116 | <p><strong>Update 1:</strong><br>
Cannot reproduce this on a co-worker's computer (same setup as mine) so I assume this is a problem with my workstation and not a general one. </p>
<p>I'd appreciate it if someone would close this question as I don't have enough reputation to do it myself. </p>
<p>@MatthewMartin. Thanks for your comments :-)</p>
<hr>
<p><strong>Update 2:</strong><br>
Unlike my coworker, I have <strong>VS90sp1-KB945140-ENU.exe (SP1)</strong> and <strong>VS90SP1-KB957912-x86.exe</strong> (JS Intellisense hotfix) installed on my machine. That <em>appears</em> to be the only difference between our setups. I removed both of them, but that didn't solve my problem.</p>
<hr>
<p>In my asp.net (C#) page is a little bit of Javascript to resize an object when the user resizes the window.</p>
<p>When I access the page using IE6 on my DEV server (IIS), it <strong>works</strong>.<br>
When I access the page using IE6 via VS2008 using F5 or CTRL-F5 (both of which start the ASP.NET Development Server) it <strong>fails</strong>. It seems to enter an infinite loop of resizing where the <code>adjSpreadsheetSize</code> function fires the window.resize event, which invokes <code>adjSpreadsheetSize</code> ... Repeat ad infinitum</p>
<p>I see quite a few people out there complaining that IE6 can't properly handle onresize events, but nobody seems to be having this precise problem.</p>
<p><strong>Any idea why this code works on IIS but not on ASP.NET Development Server?</strong></p>
<p>Here's the relevant part of the code:</p>
<pre><code>[snip]
<head>
[snip]
<script language="javascript" type="text/javascript">
window.onresize = adjSpreadsheetSize;
window.onload = pageSetup;
//Change spreadsheet size to fill the window (viewport) below the entry form
function adjSpreadsheetSize() {
var objSS = document.getElementById("OWC_data");
var winWidth = document.documentElement.clientWidth;
var winHeight = document.documentElement.clientHeight;
winHeight -= document.getElementById('form_body').offsetHeight;
objSS.height = winHeight;
objSS.width = winWidth;
return false;
}
function pageSetup() {
adjSpreadsheetSize();
}
</script>
[snip]
</head>
<body>
<form id="form1" runat="server" action="rawdata.aspx" method="get">
<div id="form_body">
[snip]
</div>
</form>
<div id="OWC_container">
<object id="OWC_data" classid="clsid:0002E559-0000-0000-C000-000000000046">
</object>
</div>
</code></pre>
<p>
</p>
<p>My setup:</p>
<ul>
<li>WinXP Pro SP2</li>
<li>Microsoft Visual Studio 2008 Version 9.0.21022.8 RTM
<ul>
<li>Installed Edition: Professional</li>
<li>Microsoft Visual Basic 2008</li>
<li>Microsoft Visual C# 2008</li>
<li>Microsoft Visual C++ 2008</li>
<li>Microsoft Visual Studio 2008 Tools for Office</li>
<li>Microsoft Visual Web Developer 2008</li>
<li>Crystal Reports Basic for Visual Studio 2008</li>
</ul></li>
<li>Microsoft .NET Framework Version 3.5 SP1</li>
<li>The Website project lives on the DEV server (mapped as a local drive)</li>
</ul>
| [
{
"answer_id": 360121,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "if (x.GetType() == typeof(byte))\n if (x is byte)\n"
},
{
"answer_id": 360150,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "Dictionary"
},
{
"answer_id": 360193,
"author": "moffdub",
"author_id": 10759,
"author_profile": "https://Stackoverflow.com/users/10759",
"pm_score": 1,
"selected": false,
"text": "class Writer\n{\n void write(byte b)\n {\n // write bytes here\n }\n\n void write(Writable something)\n {\n something.writeOn(this);\n }\n}\n\ninterface Writeable\n{\n void writeOn(Writer writer);\n}\n\nclass SomeObject implements Writeable\n{\n private Object someData;\n private Object moreData;\n\n void writeOn(Writer writer)\n {\n writer.write(convertToByte(someData));\n writer.write(convertToByte(moreData));\n }\n}\n\nclass AnotherObject implements Writeable\n{\n private int x;\n private int y;\n private int z;\n\n void writeOn(Writer writer)\n {\n writer.write((byte)x);\n writer.write((byte)y);\n writer.write((byte)z);\n }\n}\n"
},
{
"answer_id": 360306,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": true,
"text": "using System.IO;\nusing System;\nusing System.Reflection;\nusing System.Collections.Generic;\nnamespace ConsoleApplication14\n{\n public class Program\n {\n public static void Main()\n {\n Dictionary<Type, MethodInfo> mapping = new Dictionary<Type, MethodInfo>();\n foreach (MethodInfo mi in typeof(BinaryWriter).GetMethods())\n {\n if (mi.Name == \"Write\")\n {\n ParameterInfo[] pi = mi.GetParameters();\n if (pi.Length == 1)\n mapping[pi[0].ParameterType] = mi;\n }\n }\n\n List<Object> someData = new List<Object>();\n someData.Add((Byte)10);\n someData.Add((Int32)10);\n someData.Add((Double)10);\n someData.Add((Char)10);\n someData.Add(\"Test\");\n\n using (FileStream file = new FileStream(@\"C:\\test.dat\", FileMode.Create, FileAccess.ReadWrite))\n using (BinaryWriter writer = new BinaryWriter(file))\n {\n foreach (Object o in someData)\n {\n MethodInfo mi;\n if (mapping.TryGetValue(o.GetType(), out mi))\n {\n mi.Invoke(writer, new Object[] { o });\n }\n else\n throw new InvalidOperationException(\"Cannot write data of type \" + o.GetType().FullName);\n }\n }\n }\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41089/"
] |
360,134 | <p>I am using master page on some pages. And that master page is loading the user control. So I want to disable or enable user control on some page load which has master page. </p>
<hr>
<p>Is there anyway can I disable User control on master page Page_load()</p>
<hr>
<pre><code><div class="ucTabCtrl" >
<uc1:TLTabControl ID="ctrlname" runat="server" Visible="False" />
</div>
Master Page_load()
{
// checking some condition if true
ctrlname.visible = true;
}
</code></pre>
<p>but the problem is I'm not able to get the instance of user ctrl, in short ctrlname is null all the time.</p>
| [
{
"answer_id": 360149,
"author": "Steven Behnke",
"author_id": 42588,
"author_profile": "https://Stackoverflow.com/users/42588",
"pm_score": 0,
"selected": false,
"text": "if (null != this.Master)\n{\n userControl.Enabled = false;\n}\n"
},
{
"answer_id": 360557,
"author": "Tom Jelen",
"author_id": 28399,
"author_profile": "https://Stackoverflow.com/users/28399",
"pm_score": 1,
"selected": false,
"text": "public partial class Site1 : System.Web.UI.MasterPage\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n if (Page is WebForm1 || Page is WebForm2)\n {\n webUserControl11.Visible = false;\n }\n }\n}\n public partial class Site1 : System.Web.UI.MasterPage\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n ISpecialPage specialPage = Page as ISpecialPage;\n\n if (specialPage != null && specialPage.ShouldDisableUserControl)\n webUserControl11.Visible = false;\n }\n}\n\npublic interface ISpecialPage\n{\n bool ShouldDisableUserControl { get; }\n}\n"
},
{
"answer_id": 430474,
"author": "Seth Reno",
"author_id": 50225,
"author_profile": "https://Stackoverflow.com/users/50225",
"pm_score": 0,
"selected": false,
"text": "Dim userControl As WebControl = ContentPlaceHolder1.FindControl(\"someControl\")\nIf userControl IsNot Nothing Then\n CType(userControl, WebControl).Enabled = False\nEnd If\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21918/"
] |
360,141 | <p>I just installed SQL Server 2008 Express on my Vista SP1 machine. I previously had 2005 on here and used it just fine with the old SQL Server Management Studio Express. I was able to connect with no problems to my PC-NAME\SQLEXPRESS instance (no, PC-NAME is not my computer name ;-).</p>
<p>I uninstalled 2005 and SQL Server Management Studio Express. I then installed SQL Server 2008 Express on my machine and elected to have it install SQL Server Management Studio Basic.</p>
<p>Now, when I try to connect to PC-NAME\SQLEXPRESS (with Windows Authentication, like I always did), I get the following message:</p>
<p><em>Cannot connect to PC-NAME\SQLEXPRESS.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1)
For help, click: <a href="http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1&LinkId=20476" rel="noreferrer">http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1&LinkId=20476</a></em></p>
<p>When I installed SQL Server 2008, I had it use SQLEXPRESS as the local instance name. As far as I can tell, through SQL Server Configuration Manager, SQL Server is configured to allow remote connections.</p>
<p>When I went to the help link it mentions, the help page suggests the following:</p>
<ul>
<li>Make sure that the SQL Server Browser service is started on the server.</li>
<li>Use the SQL Server Surface Area Configuration tool to enable SQL Server to accept remote connections. For more information about the SQL Server Surface Area Configuration Tool, see Surface Area Configuration for Services and Connections.</li>
</ul>
<p>Well, as far as I can tell, there is no SQL Server Browser service on my system (looked in MMC for one, couldn't find one).</p>
<p>And the SQL Server Surface Area Configuration tool doesn't exist in SQL Server 2008. So good job there with your help documentation, Microsoft ;-).</p>
<p>I'm at a loss for what to do right now. I had a lot of work I was hoping to get done today after upgrading to 2008 (the person I'm working with got it up and running with no problem and told me it would be easy - he's also far better with database stuff that I am). Does anyone have any idea what might be wrong? I'd really appreciate it. If I can't get this working in a few hours, I'm going back to SQL Server 2005 (if that will even work, gah...).</p>
<p>Edit: I have tried turning Windows Firewall off, and that did not help. Also, I noticed that I do not have a "Data" directory under my SQL Server 2008 install directory tree - could I have possibly set something up wrong when I installed it?</p>
| [
{
"answer_id": 3461900,
"author": "Govardhana Reddy",
"author_id": 417640,
"author_profile": "https://Stackoverflow.com/users/417640",
"pm_score": 8,
"selected": false,
"text": "\\SQLEXPRESS"
},
{
"answer_id": 5015707,
"author": "SQLSERV",
"author_id": 619515,
"author_profile": "https://Stackoverflow.com/users/619515",
"pm_score": 3,
"selected": false,
"text": "var.connectionstring = \"server=localhost; database=dbname; integrated security=yes\"\n var.connectionstring = \"server=localhost; database=dbname; login=yourlogin; pwd=yourpass\"\n"
},
{
"answer_id": 25180369,
"author": "WhatEvil",
"author_id": 3228818,
"author_profile": "https://Stackoverflow.com/users/3228818",
"pm_score": 4,
"selected": false,
"text": "PC_NAME\\SQLEXPRESS Error: 26 - Error Locating Server/Instance Specified SQL Server Browser SQL Server SQL Server (SQLEXPRESS) SQL Server(MSSQLSERVER) PC-NAME\\MSSQLSERVER SQL Network Interfaces, error: 25 - Connection string is not valid) (MicrosoftSQL Server, Error: 87) The parameter is incorrect PC-NAME\\MSSQLSERVER PC-NAME"
},
{
"answer_id": 26241647,
"author": "Artyom Pranovich",
"author_id": 3006185,
"author_profile": "https://Stackoverflow.com/users/3006185",
"pm_score": 2,
"selected": false,
"text": "net start mssqlserver"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18505/"
] |
360,148 | <p>I'm trying to create a Comments section in my wiki. There's one solution on the Web involving the creation of a "column," but that seemed to just create a second text block under the main article block. This is impractical, because subsequent edits don't create new comments - they seem to just edit the existing comment. There are a few others asking this question out there. Has anyone done anything like this before?</p>
| [
{
"answer_id": 3461900,
"author": "Govardhana Reddy",
"author_id": 417640,
"author_profile": "https://Stackoverflow.com/users/417640",
"pm_score": 8,
"selected": false,
"text": "\\SQLEXPRESS"
},
{
"answer_id": 5015707,
"author": "SQLSERV",
"author_id": 619515,
"author_profile": "https://Stackoverflow.com/users/619515",
"pm_score": 3,
"selected": false,
"text": "var.connectionstring = \"server=localhost; database=dbname; integrated security=yes\"\n var.connectionstring = \"server=localhost; database=dbname; login=yourlogin; pwd=yourpass\"\n"
},
{
"answer_id": 25180369,
"author": "WhatEvil",
"author_id": 3228818,
"author_profile": "https://Stackoverflow.com/users/3228818",
"pm_score": 4,
"selected": false,
"text": "PC_NAME\\SQLEXPRESS Error: 26 - Error Locating Server/Instance Specified SQL Server Browser SQL Server SQL Server (SQLEXPRESS) SQL Server(MSSQLSERVER) PC-NAME\\MSSQLSERVER SQL Network Interfaces, error: 25 - Connection string is not valid) (MicrosoftSQL Server, Error: 87) The parameter is incorrect PC-NAME\\MSSQLSERVER PC-NAME"
},
{
"answer_id": 26241647,
"author": "Artyom Pranovich",
"author_id": 3006185,
"author_profile": "https://Stackoverflow.com/users/3006185",
"pm_score": 2,
"selected": false,
"text": "net start mssqlserver"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44831/"
] |
360,158 | <p>I'm using VBA in Excel 2003 to apply validation to apply validation to a given range of cells from a named list. The user can then select from a dropdown list of values.</p>
<p>Edit: Here's how I'm setting the validation, given a named range called 'MyLookupList'</p>
<pre><code> With validatedRange.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=MyLookupList"
.ErrorMessage = "Invalid value. Select one from the dropdown list."
.InCellDropdown = True
End With
</code></pre>
<p>All that works fine, but the problem is that when validation is applied from a named list, it is case-insensitive. I.e. if a dropdown choice is "John Smith", then the user can type in "john smith" or "john SmiTh" into the validated cell and Excel will still treat it as a valid entry.</p>
<p>I know that manually creating a list via Tools-->Validation... will make the lookup validation case sensitive, but for my case this is just not feasible - I have to populate the named lists and assign validation programmatically.</p>
<p>Does anyone know of a way to ensure that Excel validation based on named lists is case-sensitive?</p>
<p>Thanks.</p>
| [
{
"answer_id": 360750,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 2,
"selected": false,
"text": "Dim sValidationList As String\nDim iRow As Integer\n\n 'build comma-delimited list based on validation range\n With oValidationRange\n For iRow = 1 To .Rows.Count\n sValidationList = sValidationList & .Cells(iRow, 1) & \",\"\n Next\n End With\n\n 'trim trailing comma \n sValidationList = Left(sValidationList, Len(sValidationList) - 1)\n\n 'apply validation to data input range\n With oDataRange.Validation\n .Delete\n .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _\n Operator:=xlBetween, Formula1:=sValidationList\n .ErrorMessage = \"Invalid value. Select one from the dropdown list.\"\n .InCellDropdown = True\n\n End With\n"
},
{
"answer_id": 360904,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": " Set c = Range(\"MyLookupList\").Find(Range(\"ValidateRange\"), _\n LookIn:=xlValues)\n If Not c Is Nothing Then\n If StrComp(c, Range(\"ValidateRange\"), vbBinaryCompare) = 0 Then\n 'Match '\n MsgBox \"OK\"\n Else\n MsgBox \"Problem\"\n End If\n End If\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354/"
] |
360,161 | <p>Im trying to get a completly data copy from a gridview, itryed clone(), tryed cast DataView from DataSouce, but always get nulls or cant get the data, please exists a way to copy data from gridview, modified it and then reload it? or modifyng directly some rows in the gridview?
thanks in advance!</p>
| [
{
"answer_id": 360317,
"author": "dragonjujo",
"author_id": 37344,
"author_profile": "https://Stackoverflow.com/users/37344",
"pm_score": 2,
"selected": true,
"text": "protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.Header)\n {\n //HeaderStuff\n }\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n ObjectTye objectType = (ObjectType)e.Row.DataItem;\n // and doing some stuff with the properties\n e.Row.Cells[0].Text = objectType.SomeProperty.ToString();\n LinkButton deleteLnk = (LinkButton)e.Row.FindControl(\"lnkDelete\");\n deleteLnk.Attributes.Add(\"onclick\", \"javascript:return \" + \n \"confirm('Are you sure you want to delete this')\");\n deleteLnk.CommandArgument = e.Row.RowIndex.ToString();\n }\n}\nprotected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n int rowIndex = int.Parse(e.CommandArgument.ToString());\n GridViewRow row = GridView1.Rows[rowIndex];\n\n ObjectType objectType = new ObjectType();\n objectType.StringProperty = row.Cells[0].Text;\n}\n"
},
{
"answer_id": 360349,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 0,
"selected": false,
"text": "DataGridView1.DataSource = yourList;\nDataGridView1.DataBind();\n...\nDataGridView2.DataSource = yourList; //or = DataGridView1.DataSource;\nDataGridView2.DataBind();\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388553/"
] |
360,167 | <p>I'd like to host custom items in a ToolBar in an ItemsControl. However, the buttons I add are rendered below the toolbar and as regular buttons rather than in the ToolBar with the ToolBar look and feel.</p>
<p>This can be reproduced with a few lines of Xaml (I've excluded the default content). The custom ItemsControl:</p>
<pre><code><ToolBar ItemsSource="{Binding Items}" />
</code></pre>
<p>The example window:</p>
<pre><code><StackPanel Orientation="Vertical">
<local:UserControl1>
<Button>control button</Button>
</local:UserControl1>
<Button>standard button</Button>
<ToolBar>
<Button>window toolbar button</Button>
</ToolBar>
</code></pre>
<p>I would expect that the "control button" would render similarly to the "window toolbar button", rather it renders like the "standard button" below an empty ToolBar.</p>
<p>Any guidance will be appreciated.</p>
| [
{
"answer_id": 360371,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 2,
"selected": false,
"text": "Style=\"{DynamicResource {x:Static ToolBar.ButtonStyleKey}}\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
] |
360,195 | <p>I'm trying to run a c++ 2d array (pretty simple file) and it works but an error (at least I think it's an error) appears on the end.</p>
<p>The code for the array is;</p>
<pre><code>int myArray[10][10];
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
myArray[i][t] = i+t; //This will give each element a value
}
}
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
cout << myArray[i][t] << "\n";
}
</code></pre>
<p>this prints the array properly but adds</p>
<p>"0x22fbb0"</p>
<p>on the end. What is this and why does it happen?</p>
| [
{
"answer_id": 360228,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "if(cout) { ... }"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33061/"
] |
360,201 | <p>I am looking for a way to clean up the mess when my top-level script exits.</p>
<p>Especially if I want to use <code>set -e</code>, I wish the background process would die when the script exits.</p>
| [
{
"answer_id": 360249,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": -1,
"selected": false,
"text": "killall"
},
{
"answer_id": 360275,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 9,
"selected": true,
"text": "trap trap \"echo hello\" SIGINT\n trap \"killall background\" EXIT\n help trap trap 'kill $(jobs -p)' EXIT\n ' $()"
},
{
"answer_id": 2173421,
"author": "tokland",
"author_id": 188031,
"author_profile": "https://Stackoverflow.com/users/188031",
"pm_score": 8,
"selected": false,
"text": "trap \"trap - SIGTERM && kill -- -$$\" SIGINT SIGTERM EXIT\n kill -- -$$ EXIT set -e"
},
{
"answer_id": 5586663,
"author": "raytraced",
"author_id": 435477,
"author_profile": "https://Stackoverflow.com/users/435477",
"pm_score": 4,
"selected": false,
"text": "trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT\n"
},
{
"answer_id": 13838914,
"author": "michaeljt",
"author_id": 213180,
"author_profile": "https://Stackoverflow.com/users/213180",
"pm_score": -1,
"selected": false,
"text": "trap 'while kill %% 2>/dev/null; do jobs > /dev/null; done' INT TERM EXIT [...]\n"
},
{
"answer_id": 17120020,
"author": "tdaitx",
"author_id": 1153136,
"author_profile": "https://Stackoverflow.com/users/1153136",
"pm_score": 3,
"selected": false,
"text": "cleanup() {\n local pids=$(jobs -pr)\n [ -n \"$pids\" ] && kill $pids\n}\ntrap \"cleanup\" INT QUIT TERM EXIT [...]\n trap '[ -n \"$(jobs -pr)\" ] && kill $(jobs -pr)' INT QUIT TERM EXIT [...]\n trap 'kill $(jobs -pr)' [...] kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]\n jobs -pr"
},
{
"answer_id": 22644006,
"author": "korkman",
"author_id": 302079,
"author_profile": "https://Stackoverflow.com/users/302079",
"pm_score": 7,
"selected": false,
"text": "trap \"exit\" INT TERM\ntrap \"kill 0\" EXIT\n INT TERM kill 0 kill 0 EXIT kill 0 kill 0"
},
{
"answer_id": 28333938,
"author": "skozin",
"author_id": 804678,
"author_profile": "https://Stackoverflow.com/users/804678",
"pm_score": 5,
"selected": false,
"text": "trap 'kill 0' SIGINT SIGTERM EXIT SIGINT SIGTERM EXIT kill 0 SIGTERM trap 'trap - SIGTERM && kill 0' SIGINT SIGTERM EXIT\n #!/usr/bin/env bash\n\ntrap_with_arg() { # from https://stackoverflow.com/a/2183063/804678\n local func=\"$1\"; shift\n for sig in \"$@\"; do\n trap \"$func $sig\" \"$sig\"\n done\n}\n\nstop() {\n trap - SIGINT EXIT\n printf '\\n%s\\n' \"received $1, killing child processes\"\n kill -s SIGINT 0\n}\n\ntrap_with_arg 'stop' EXIT SIGINT SIGTERM SIGHUP\n\n{ i=0; while (( ++i )); do sleep 0.5 && echo \"a: $i\"; done } &\n{ i=0; while (( ++i )); do sleep 0.6 && echo \"b: $i\"; done } &\n\nwhile true; do read; done\n stop"
},
{
"answer_id": 31150244,
"author": "nh2",
"author_id": 263061,
"author_profile": "https://Stackoverflow.com/users/263061",
"pm_score": 1,
"selected": false,
"text": "trap & #!/bin/bash\n\n# killable-shell.sh: Kills itself and all children (the whole process group) when killed.\n# Adapted from http://stackoverflow.com/a/2173421 and http://veithen.github.io/2014/11/16/sigterm-propagation.html\n# Note: Does not work (and cannot work) when the shell itself is killed with SIGKILL, for then the trap is not triggered.\ntrap \"trap - SIGTERM && echo 'Caught SIGTERM, sending SIGTERM to process group' && kill -- -$$\" SIGINT SIGTERM EXIT\n\necho $@\n\"$@\" &\nPID=$!\nwait $PID\ntrap - SIGINT SIGTERM EXIT\nwait $PID\n $ bash killable-shell.sh sleep 100\nsleep 100\n^Z\n[1] + 31568 suspended bash killable-shell.sh sleep 100\n\n$ ps aux | grep \"sleep\"\nniklas 31568 0.0 0.0 19640 1440 pts/18 T 01:30 0:00 bash killable-shell.sh sleep 100\nniklas 31569 0.0 0.0 14404 616 pts/18 T 01:30 0:00 sleep 100\nniklas 31605 0.0 0.0 18956 936 pts/18 S+ 01:30 0:00 grep --color=auto sleep\n\n$ bg\n[1] + 31568 continued bash killable-shell.sh sleep 100\n\n$ kill 31568\nCaught SIGTERM, sending SIGTERM to process group\n[1] + 31568 terminated bash killable-shell.sh sleep 100\n\n$ ps aux | grep \"sleep\"\nniklas 31717 0.0 0.0 18956 936 pts/18 S+ 01:31 0:00 grep --color=auto sleep\n"
},
{
"answer_id": 32573879,
"author": "Orsiris de Jong",
"author_id": 2635443,
"author_profile": "https://Stackoverflow.com/users/2635443",
"pm_score": 2,
"selected": false,
"text": "KillJobs() {\n for job in $(jobs -p); do\n kill -s SIGTERM $job > /dev/null 2>&1 || (sleep 10 && kill -9 $job > /dev/null 2>&1 &)\n\n done\n}\n\nTrapQuit() {\n # Whatever you need to clean here\n KillJobs\n}\n\ntrap TrapQuit EXIT\n"
},
{
"answer_id": 53714583,
"author": "Delaware",
"author_id": 10082476,
"author_profile": "https://Stackoverflow.com/users/10082476",
"pm_score": 2,
"selected": false,
"text": "function cleanup_func {\n sleep 0.5\n echo cleanup\n}\n\ntrap \"exit \\$exit_code\" INT TERM\ntrap \"exit_code=\\$?; cleanup_func; kill 0\" EXIT\n\n# exit 1\n# exit 0\n"
},
{
"answer_id": 54593493,
"author": "noonex",
"author_id": 102484,
"author_profile": "https://Stackoverflow.com/users/102484",
"pm_score": -1,
"selected": false,
"text": "trap 'test -z \"$intrap\" && export intrap=1 && kill -- -$$' SIGINT SIGTERM EXIT\n"
},
{
"answer_id": 73427461,
"author": "Dino Dini",
"author_id": 4089000,
"author_profile": "https://Stackoverflow.com/users/4089000",
"pm_score": 0,
"selected": false,
"text": "while ! ffmpeg ....\ndo\n sleep 1\ndone\n cleanup() {\n # kill all processes whose parent is this process\n kill $(pidtree $$ | tac)\n}\n\npidtree() (\n [ -n \"$ZSH_VERSION\" ] && setopt shwordsplit\n declare -A CHILDS\n while read P PP;do\n CHILDS[$PP]+=\" $P\"\n done < <(ps -e -o pid= -o ppid=)\n walk() {\n echo $1\n for i in ${CHILDS[$1]};do\n walk $i\n done\n }\n\n for i in \"$@\";do\n walk $i\n done\n)\n\ntrap cleanup EXIT\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277510/"
] |
360,216 | <p>I would like to display certain meta data fields in the edit form based on the value of a fields. </p>
<p>Example: Users upload a document to the Doclib to be approved by there manager. They are allowed to change the meta data Name,Case No, Location until the item is approved by the manager. Once the item is approved I would like to set Name and Case Number to read only.</p>
<p>What is the best way to meet this requirement?</p>
<p>If approved = yes
set Name and Case No = Read only
Else
do nothing.</p>
<hr>
<p>I have tried this method for about 5 hours. I believed this may be different for ModerationStatus. Might require something special</p>
<pre><code>print("<xsl:choose>
<xsl:when test="@_ModerationStatus != '0;#approved'">
<SharePoint:FormField runat="server" id="ff12{$Pos}" ControlMode="Edit" FieldName="Test_x0020_Session" __designer:bind="{ddwrt:DataBind('u',concat('ff12',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Test_x0020_Session')}"/>
<SharePoint:FieldDescription runat="server" id="ff12description{$Pos}" FieldName="Test_x0020_Session" ControlMode="Edit"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="@Test_x0020_Session"></xsl:value-of>
</xsl:otherwise>
</code></pre>
<p>");</p>
<p>I can get it to work with the other fields but not ModerationStatus. I have also tried changing it to !='0' and !='Approved' and '0;#Approved'. Is there something I am doing wrong?</p>
<p>Seems like its stuck on 0;#Approved</p>
| [
{
"answer_id": 366929,
"author": "Toni Frankola",
"author_id": 15626,
"author_profile": "https://Stackoverflow.com/users/15626",
"pm_score": 2,
"selected": true,
"text": "<xsl:choose>\n <xsl:when test=\"@Status != 'Closed'\">\n <SharePoint:FormField runat=\"server\" id=\"ff1{$Pos}\" ControlMode=\"Edit\" FieldName=\"Title\" __designer:bind=\"{ddwrt:DataBind('u',concat('ff1',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Title')}\"/>\n <SharePoint:FieldDescription runat=\"server\" id=\"ff1description{$Pos}\" FieldName=\"Title\" ControlMode=\"Edit\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"@Title\"></xsl:value-of>\n </xsl:otherwise>\n</xsl:choose>\n"
},
{
"answer_id": 377771,
"author": "Bulat",
"author_id": 47383,
"author_profile": "https://Stackoverflow.com/users/47383",
"pm_score": 0,
"selected": false,
"text": "<xsl:when test=\"not(starts-with(@_ModerationStatus,'0'))\">\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282/"
] |
360,219 | <p>I want to skip to the first line that contains "include".</p>
<pre><code><> until /include/;
</code></pre>
<p>Why does this not work?</p>
| [
{
"answer_id": 360243,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "$_ <> $_ $_ perldoc perlop"
},
{
"answer_id": 360261,
"author": "Hudson",
"author_id": 14105,
"author_profile": "https://Stackoverflow.com/users/14105",
"pm_score": 2,
"selected": false,
"text": "<> while(<>) $_ /include/ -w Use of uninitialized value in pattern match (m//) at ....\n $_ = <> until /include/;\n while(<>)\n{\n last if /include/;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44511/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.