qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
222,827 |
<p>First, I know about this: <a href="https://stackoverflow.com/questions/51217/how-would-you-organize-a-subversion-repository-for-in-house-software-projects">How would you organize a Subversion repository for in house software projects?</a>
Next, the actual question:
My team is restructuring our repository and I'm looking for hints on how to organize it. (SVN in this case).
Here's what we came up with. We have one repository, multiple projects and multiple svn:externals cross-references</p>
<pre><code>\commonTools /*tools used in all projects. Referenced in each project with svn:externals*/
\NUnit.v2.4.8
\NCover.v.1.5.8
\<other similar tools>
\commonFiles /*settings strong name keys etc.*/
\ReSharper.settings
\VisualStudio.settings
\trash /*each member of the team has trash for samples, experiments etc*/
\user1
\user2
\projects
\Solution1 /*Single actual project (Visual Studio Solution)*/
\trunk
\src
\Project1 /*Each sub-project resulting in single .dll or .exe*/
\Project2
\lib
\tools
\tests
\Solution1.sln
\tags
\branches
\Solution2
\trunk
\src
\Project3 /*Each sub-project resulting in single .dll or .exe*/
\Project1 /*Project1 from Solution1 references with svn:externals*/
\lib
\tools
\tests
\Solution2.sln
\tags
\branches
</code></pre>
<p>To clear the vocabulary: Solution means single product, Project is a Visual Studio Project (that results in a single .dll or single .exe)</p>
<p>That's how we plan to lay out the repository. The main issue is, that we have multiple Solutions, but we want to share Projects among Solutions.
We thought that there is no point really in moving those shared Projects to their own Solutions, and instead we decided to use svn:externals to share Projects among Solutions. We also want to keep common set of tools and 3rd party libraries in one place in the repository, and them reference them in each Solution with svn:externals.</p>
<p>What do you think about this layout? Especially about the use of svn:externals. It's not an ideal solution, but considering all pros and cons, it's the best we could think of. How would YOU do it?</p>
|
[
{
"answer_id": 222906,
"author": "Fabio Gomes",
"author_id": 727,
"author_profile": "https://Stackoverflow.com/users/727",
"pm_score": 2,
"selected": false,
"text": "<p>I believe that <a href=\"http://www.pragprog.com/titles/svn/pragmatic-version-control-using-subversion\" rel=\"nofollow noreferrer\">Pragmatic Version Control using Subversion</a> has everything you need to organize your repository.</p>\n"
},
{
"answer_id": 222952,
"author": "SqlRyan",
"author_id": 8114,
"author_profile": "https://Stackoverflow.com/users/8114",
"pm_score": 2,
"selected": false,
"text": "<p>We've set ours up to almost exactly match what you've posted. We use the general form:</p>\n\n<pre><code>\\Project1\n \\Development (for active dev - what you've called \"Trunk\", containing everything about a project)\n \\Branches (For older, still-evolving supported branches of the code)\n \\Version1\n \\Version1.1\n \\Version2\n \\Documentation (For any accompanying documents that aren't version-specific\n</code></pre>\n\n<p>While I suppose not as complete as your example, it's worked well for us and lets us keep things separate. I like the idea of each user having a \"Thrash\" folder as well - currently, those types of projects don't end up in Source control, and I've always felt that they should.</p>\n"
},
{
"answer_id": 222955,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have a similar layout, but my trunk, branches, tags all the way at the top. So: /trunk/main, /trunk/utils, /branches/release/, etc.</p>\n\n<p>This ended up being really handy when we wanted to try out other version control systems because many of the translation tools worked best with the basic textbook SVN layout.</p>\n"
},
{
"answer_id": 223039,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 0,
"selected": false,
"text": "<p>I think the main disadvantage of the proposed structure is that the shared projects will only be versioned with the first solution they were added to (unless svn:externals is fancier than I am imagining). For example, when you create a branch for the first release of Solution2, Project1 won't be branched since it lives in Solution1. If you need to build from that branch at a later time (QFE release), it will use the latest version of Project1 rather than version of Project1 at the time of the branch.</p>\n\n<p>For this reason, it may be advantageous to put the shared projects in one or more shared solutions (and thus top-level directories in your structure) and then branch them with each release of <em>any</em> solution.</p>\n"
},
{
"answer_id": 223049,
"author": "Rene Saarsoo",
"author_id": 15982,
"author_profile": "https://Stackoverflow.com/users/15982",
"pm_score": 1,
"selected": false,
"text": "<p>Why have it all in one repository? Why not just have a separate repository for each project (I mean \"Solution\")?</p>\n\n<p>Well, at least I've used to the one-project-per-repository-approach. Your repository structure seems overcomplicated to me.</p>\n\n<p>And how many project do you plan to put into this one big repository? 2? 3? 10? 100?</p>\n\n<p>And what do you do when you cancel the development of one project? Just delete it from repository tree so that it will become hard to find in the future. Or leave it lying around forever? Or when you want to move one project to another server altogether?</p>\n\n<p>And what about the mess of all those version numbers? The version numbers of one project going like 2, 10, 11, while the other goes like 1, 3, 4, 5, 6, 7, 8, 9, 12...</p>\n\n<p>Maybe I'm foolish, but I like one project per repository.</p>\n"
},
{
"answer_id": 223053,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<p>To add to the relative path issue:</p>\n\n<p>I am not sure it is a problem:<br>\nJust checkout Solution1/trunk under the directory named \"Solution1\", ditto for Solution2: the goal of 'directories' actually representing branches is to <em>not be visible</em> once imported into a workspace. Hence relative paths are possible between 'Solution1' (actually 'Solution1/trunk') and 'Solution2' (Solution2/trunk).</p>\n"
},
{
"answer_id": 223098,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 0,
"selected": false,
"text": "<p>RE: the relative path and shared file issue -</p>\n\n<p>It seems that this is svn specific, but that is not a problem. One other person already mentioned separate repositories and that is probably the best solution I can think of in the case where you have different projects referring to arbitrary other projects. In the case where you have no shared files then the OP solution (As well as many others) will work fine. </p>\n\n<p>We're still working this out and I have 3 different efforts (different clients) that I have to resolve right now since I took over setting up either non-existent or poor version control. </p>\n"
},
{
"answer_id": 304036,
"author": "Rob Williams",
"author_id": 26682,
"author_profile": "https://Stackoverflow.com/users/26682",
"pm_score": 8,
"selected": true,
"text": "<p>If you follow my recommendations below (I have for years), you will be able to:</p>\n\n<p>-- put each project anywhere in source control, as long as you preserve the structure from the project root directory on down</p>\n\n<p>-- build each project anywhere on any machine, with minimum risk and minimum preparation</p>\n\n<p>-- build each project completely stand-alone, as long as you have access to its binary dependencies (local \"library\" and \"output\" directories)</p>\n\n<p>-- build and work with any combination of projects, since they are independent</p>\n\n<p>-- build and work with multiple copies/versions of a single project, since they are independent</p>\n\n<p>-- avoid cluttering your source control repository with generated files or libraries</p>\n\n<p>I recommend (here's the beef):</p>\n\n<ol>\n<li><p>Define each project to produce a single primary deliverable, such as an .DLL, .EXE, or .JAR (default with Visual Studio).</p></li>\n<li><p>Structure each project as a directory tree with a single root.</p></li>\n<li><p>Create an automated build script for each project in its root directory that will build it from scratch, with NO dependencies on an IDE (but don't prevent it from being built in the IDE, if feasible).</p></li>\n<li><p>Consider nAnt for .NET projects on Windows, or something similar based on your OS, target platform, etc.</p></li>\n<li><p>Make every project build script reference its external (3rd-party) dependencies from a single local shared \"library\" directory, with every such binary FULLY identified by version: <code>%DirLibraryRoot%\\ComponentA-1.2.3.4.dll</code>, <code>%DirLibraryRoot%\\ComponentB-5.6.7.8.dll</code>.</p></li>\n<li><p>Make every project build script publish the primary deliverable to a single local shared \"output\" directory: <code>%DirOutputRoot%\\ProjectA-9.10.11.12.dll</code>, <code>%DirOutputRoot%\\ProjectB-13.14.15.16.exe</code>.</p></li>\n<li><p>Make every project build script reference its dependencies via configurable and fully-versioned absolute paths (see above) in the \"library\" and \"output\" directories, AND NO WHERE ELSE.</p></li>\n<li><p>NEVER let a project directly reference another project or any of its contents--only allow references to the primary deliverables in the \"output\" directory (see above).</p></li>\n<li><p>Make every project build script reference its required build tools by a configurable and fully-versioned absolute path: <code>%DirToolRoot%\\ToolA\\1.2.3.4</code>, <code>%DirToolRoot%\\ToolB\\5.6.7.8</code>.</p></li>\n<li><p>Make every project build script reference source content by an absolute path relative to the project root directory: <code>${project.base.dir}/src</code>, <code>${project.base.dir}/tst</code> (syntax varies by build tool).</p></li>\n<li><p>ALWAYS require a project build script to reference EVERY file or directory via an absolute, configurable path (rooted at a directory specified by a configurable variable): <code>${project.base.dir}/some/dirs</code> or <code>${env.Variable}/other/dir</code>.</p></li>\n<li><p>NEVER allow a project build script to reference ANYTHING with a relative path like <code>.\\some\\dirs\\here</code> or <code>..\\some\\more\\dirs</code>, ALWAYS use absolute paths.</p></li>\n<li><p>NEVER allow a project build script to reference ANYTHING using an absolute path that does not have a configurable root directory, like <code>C:\\some\\dirs\\here</code> or <code>\\\\server\\share\\more\\stuff\\there</code>.</p></li>\n<li><p>For each configurable root directory referenced by a project build script, define an environment variable that will be used for those references.</p></li>\n<li><p>Attempt to minimize the number of environment variables you must create to configure each machine.</p></li>\n<li><p>On each machine, create a shell script that defines the necessary environment variables, which is specific to THAT machine (and possibly specific to that user, if relevant).</p></li>\n<li><p>Do NOT put the machine-specific configuration shell script into source control; instead, for each project, commit a copy of the script in the project root directory as a template.</p></li>\n<li><p>REQUIRE each project build script to check each of its environment variables, and abort with a meaningful message if they are not defined.</p></li>\n<li><p>REQUIRE each project build script to check each of its dependent build tool executables, external library files, and dependent project deliverable files, and abort with a meaningful message if those files do not exist.</p></li>\n<li><p>RESIST the temptation to commit ANY generated files into source control--no project deliverables, no generated source, no generated docs, etc.</p></li>\n<li><p>If you use an IDE, generate whatever project control files you can, and don't commit them to source control (this includes Visual Studio project files).</p></li>\n<li><p>Establish a server with an official copy of all external libraries and tools, to be copied/installed on developer workstations and build machines. Back it up, along with your source control repository.</p></li>\n<li><p>Establish a continuous integration server (build machine) with NO development tools whatsoever.</p></li>\n<li><p>Consider a tool for managing your external libraries and deliverables, such as Ivy (used with Ant).</p></li>\n<li><p>Do NOT use Maven--it will initially make you happy, and eventually make you cry.</p></li>\n</ol>\n\n<p>Note that none of this is specific to Subversion, and most of it is generic to projects targeted to any OS, hardware, platform, language, etc. I did use a bit of OS- and tool-specific syntax, but only for illustration--I trust that you will translate to your OS or tool of choice.</p>\n\n<p>Additional note regarding Visual Studio solutions: don't put them in source control! With this approach, you don't need them at all or you can generate them (just like the Visual Studio project files). However, I find it best to leave the solution files to individual developers to create/use as they see fit (but not checked in to source control). I keep a <code>Rob.sln</code> file on my workstation from which I reference my current project(s). Since my projects all stand-alone, I can add/remove projects at will (that means no project-based dependency references).</p>\n\n<p>Please don't use Subversion externals (or similar in other tools), they are an anti-pattern and, therefore, unnecessary.</p>\n\n<p>When you implement continuous integration, or even when you just want to automate the release process, create a script for it. Make a single shell script that: takes parameters of the project name (as listed in the repository) and tag name, creates a temporary directory within a configurable root directory, checks out the source for the given project name and tag name (by constructing the appropriate URL in the case of Subversion) to that temporary directory, performs a clean build that runs tests and packages the deliverable. This shell script should work on any project and should be checked into source control as part of your \"build tools\" project. Your continuous integration server can use this script as its foundation for building projects, or it might even provide it (but you still might want your own).</p>\n\n<p>@VonC: You do NOT want to work at all times with \"ant.jar\" rather than \"ant-a.b.c.d.jar\" after you get burned when your build script breaks because you unknowingly ran it with an incompatible version of Ant. This is particularly common between Ant 1.6.5 and 1.7.0. Generalizing, you ALWAYS want to know what specific version of EVERY component is being used, including your platform (Java A.B.C.D) and your build tool (Ant E.F.G.H). Otherwise, you will eventually encounter a bug and your first BIG problem will be tracking down what versions of your various components are involved. It is simply better to solve that problem up front.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13163/"
] |
First, I know about this: [How would you organize a Subversion repository for in house software projects?](https://stackoverflow.com/questions/51217/how-would-you-organize-a-subversion-repository-for-in-house-software-projects)
Next, the actual question:
My team is restructuring our repository and I'm looking for hints on how to organize it. (SVN in this case).
Here's what we came up with. We have one repository, multiple projects and multiple svn:externals cross-references
```
\commonTools /*tools used in all projects. Referenced in each project with svn:externals*/
\NUnit.v2.4.8
\NCover.v.1.5.8
\<other similar tools>
\commonFiles /*settings strong name keys etc.*/
\ReSharper.settings
\VisualStudio.settings
\trash /*each member of the team has trash for samples, experiments etc*/
\user1
\user2
\projects
\Solution1 /*Single actual project (Visual Studio Solution)*/
\trunk
\src
\Project1 /*Each sub-project resulting in single .dll or .exe*/
\Project2
\lib
\tools
\tests
\Solution1.sln
\tags
\branches
\Solution2
\trunk
\src
\Project3 /*Each sub-project resulting in single .dll or .exe*/
\Project1 /*Project1 from Solution1 references with svn:externals*/
\lib
\tools
\tests
\Solution2.sln
\tags
\branches
```
To clear the vocabulary: Solution means single product, Project is a Visual Studio Project (that results in a single .dll or single .exe)
That's how we plan to lay out the repository. The main issue is, that we have multiple Solutions, but we want to share Projects among Solutions.
We thought that there is no point really in moving those shared Projects to their own Solutions, and instead we decided to use svn:externals to share Projects among Solutions. We also want to keep common set of tools and 3rd party libraries in one place in the repository, and them reference them in each Solution with svn:externals.
What do you think about this layout? Especially about the use of svn:externals. It's not an ideal solution, but considering all pros and cons, it's the best we could think of. How would YOU do it?
|
If you follow my recommendations below (I have for years), you will be able to:
-- put each project anywhere in source control, as long as you preserve the structure from the project root directory on down
-- build each project anywhere on any machine, with minimum risk and minimum preparation
-- build each project completely stand-alone, as long as you have access to its binary dependencies (local "library" and "output" directories)
-- build and work with any combination of projects, since they are independent
-- build and work with multiple copies/versions of a single project, since they are independent
-- avoid cluttering your source control repository with generated files or libraries
I recommend (here's the beef):
1. Define each project to produce a single primary deliverable, such as an .DLL, .EXE, or .JAR (default with Visual Studio).
2. Structure each project as a directory tree with a single root.
3. Create an automated build script for each project in its root directory that will build it from scratch, with NO dependencies on an IDE (but don't prevent it from being built in the IDE, if feasible).
4. Consider nAnt for .NET projects on Windows, or something similar based on your OS, target platform, etc.
5. Make every project build script reference its external (3rd-party) dependencies from a single local shared "library" directory, with every such binary FULLY identified by version: `%DirLibraryRoot%\ComponentA-1.2.3.4.dll`, `%DirLibraryRoot%\ComponentB-5.6.7.8.dll`.
6. Make every project build script publish the primary deliverable to a single local shared "output" directory: `%DirOutputRoot%\ProjectA-9.10.11.12.dll`, `%DirOutputRoot%\ProjectB-13.14.15.16.exe`.
7. Make every project build script reference its dependencies via configurable and fully-versioned absolute paths (see above) in the "library" and "output" directories, AND NO WHERE ELSE.
8. NEVER let a project directly reference another project or any of its contents--only allow references to the primary deliverables in the "output" directory (see above).
9. Make every project build script reference its required build tools by a configurable and fully-versioned absolute path: `%DirToolRoot%\ToolA\1.2.3.4`, `%DirToolRoot%\ToolB\5.6.7.8`.
10. Make every project build script reference source content by an absolute path relative to the project root directory: `${project.base.dir}/src`, `${project.base.dir}/tst` (syntax varies by build tool).
11. ALWAYS require a project build script to reference EVERY file or directory via an absolute, configurable path (rooted at a directory specified by a configurable variable): `${project.base.dir}/some/dirs` or `${env.Variable}/other/dir`.
12. NEVER allow a project build script to reference ANYTHING with a relative path like `.\some\dirs\here` or `..\some\more\dirs`, ALWAYS use absolute paths.
13. NEVER allow a project build script to reference ANYTHING using an absolute path that does not have a configurable root directory, like `C:\some\dirs\here` or `\\server\share\more\stuff\there`.
14. For each configurable root directory referenced by a project build script, define an environment variable that will be used for those references.
15. Attempt to minimize the number of environment variables you must create to configure each machine.
16. On each machine, create a shell script that defines the necessary environment variables, which is specific to THAT machine (and possibly specific to that user, if relevant).
17. Do NOT put the machine-specific configuration shell script into source control; instead, for each project, commit a copy of the script in the project root directory as a template.
18. REQUIRE each project build script to check each of its environment variables, and abort with a meaningful message if they are not defined.
19. REQUIRE each project build script to check each of its dependent build tool executables, external library files, and dependent project deliverable files, and abort with a meaningful message if those files do not exist.
20. RESIST the temptation to commit ANY generated files into source control--no project deliverables, no generated source, no generated docs, etc.
21. If you use an IDE, generate whatever project control files you can, and don't commit them to source control (this includes Visual Studio project files).
22. Establish a server with an official copy of all external libraries and tools, to be copied/installed on developer workstations and build machines. Back it up, along with your source control repository.
23. Establish a continuous integration server (build machine) with NO development tools whatsoever.
24. Consider a tool for managing your external libraries and deliverables, such as Ivy (used with Ant).
25. Do NOT use Maven--it will initially make you happy, and eventually make you cry.
Note that none of this is specific to Subversion, and most of it is generic to projects targeted to any OS, hardware, platform, language, etc. I did use a bit of OS- and tool-specific syntax, but only for illustration--I trust that you will translate to your OS or tool of choice.
Additional note regarding Visual Studio solutions: don't put them in source control! With this approach, you don't need them at all or you can generate them (just like the Visual Studio project files). However, I find it best to leave the solution files to individual developers to create/use as they see fit (but not checked in to source control). I keep a `Rob.sln` file on my workstation from which I reference my current project(s). Since my projects all stand-alone, I can add/remove projects at will (that means no project-based dependency references).
Please don't use Subversion externals (or similar in other tools), they are an anti-pattern and, therefore, unnecessary.
When you implement continuous integration, or even when you just want to automate the release process, create a script for it. Make a single shell script that: takes parameters of the project name (as listed in the repository) and tag name, creates a temporary directory within a configurable root directory, checks out the source for the given project name and tag name (by constructing the appropriate URL in the case of Subversion) to that temporary directory, performs a clean build that runs tests and packages the deliverable. This shell script should work on any project and should be checked into source control as part of your "build tools" project. Your continuous integration server can use this script as its foundation for building projects, or it might even provide it (but you still might want your own).
@VonC: You do NOT want to work at all times with "ant.jar" rather than "ant-a.b.c.d.jar" after you get burned when your build script breaks because you unknowingly ran it with an incompatible version of Ant. This is particularly common between Ant 1.6.5 and 1.7.0. Generalizing, you ALWAYS want to know what specific version of EVERY component is being used, including your platform (Java A.B.C.D) and your build tool (Ant E.F.G.H). Otherwise, you will eventually encounter a bug and your first BIG problem will be tracking down what versions of your various components are involved. It is simply better to solve that problem up front.
|
222,833 |
<p>I currently use the following command, but it's a little unwieldy to type. What's a shorter alternative?</p>
<pre><code>find . -name '*.txt' -exec grep 'sometext' '{}' \; -print
</code></pre>
<p>Here are my requirements:</p>
<ul>
<li>limit to a file extension (I use SVN and don't want to be searching through all those .svn directories)</li>
<li>can default to the current directory, but it's nice to be able to specify a different directory</li>
<li>must be recursive</li>
</ul>
<p><strong>UPDATE:</strong> Here's my best solution so far:</p>
<pre><code>grep -r 'sometext' * --include='*.txt'
</code></pre>
<p><strong>UPDATE #2:</strong> After using grep for a bit, I realized that I like the output of my first method better. So, I followed the suggestions of several responders and simply made a shell script and now I call that with two parameters (extension and text to find).</p>
|
[
{
"answer_id": 222838,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 4,
"selected": true,
"text": "<p>grep has -r (recursive) and --include (to search only in files and directories matching a pattern).</p>\n"
},
{
"answer_id": 222854,
"author": "Chris Dodd",
"author_id": 29759,
"author_profile": "https://Stackoverflow.com/users/29759",
"pm_score": 2,
"selected": false,
"text": "<p>If its too unweildy, write a script that does it and put it in your personal bin directory. I have a 'fif' script which searches source files for text, basically just doing a single find like you have here:</p>\n\n<pre><code>#!/bin/bash\n\nset -f # disable pathname expansion\n\npattern=\"-iname *.[chsyl] -o -iname *.[ch]pp -o -iname *.hh -o -iname *.cc\n-o -iname *.java -o -iname *.inl\"\nprune=\"\"\nmoreargs=true\nwhile $moreargs && [ $# -gt 0 ]; do\n case $1 in\n -h)\n pattern=\"-iname *.h -o -iname *.hpp -o -iname *.hh\"\n shift\n ;;\n -prune)\n prune=\"-name $2 -prune -false -o $prune\"\n shift\n shift\n ;;\n *)\n moreargs=false;\n ;;\n esac\ndone\n\nfind . $prune $pattern | sed 's/ /\\\\ /g' | xargs grep \"$@\"\n</code></pre>\n\n<p>it started life as a single-line script and got features added over the years as I needed them.</p>\n"
},
{
"answer_id": 222860,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 1,
"selected": false,
"text": "<p>You could write a script (in bash or whatever -- I have one in Groovy) and place it on the path. E.g.</p>\n\n<pre><code>$ myFind.sh txt targetString\n</code></pre>\n\n<p>where myFind.sh is:</p>\n\n<pre><code>find . -name \"*.$1\" -exec grep $2 {} \\; -print\n</code></pre>\n"
},
{
"answer_id": 222908,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 0,
"selected": false,
"text": "<p>I usualy avoid the \"man find\" by using <code>grep $(find . -name \"*,txt\")</code></p>\n"
},
{
"answer_id": 222959,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 2,
"selected": false,
"text": "<p>I use zsh, which has recursive globbing. If you needed to look at specific filetypes, the following would be equivalent to your example:</p>\n\n<pre><code>grep 'sometext' **/*.txt\n</code></pre>\n\n<p>If you don't care about the filetype, the -r option will be better:</p>\n\n<pre><code>grep -r 'sometext' *\n</code></pre>\n\n<p>Although, A minor tweak to your original example will give you exactly what you want:</p>\n\n<pre><code>find . -name '*.txt' \\! -wholename '*/.svn/*' -exec grep 'sometext' '{}' \\; -print\n</code></pre>\n\n<p>If this is something you do frequently, make it a function (put this in your shell config):</p>\n\n<pre><code>function grep_no_svn {\n find . -name \"${2:-*}\" \\! -wholename '*/.svn/*' -exec grep \"$1\" '{}' \\; -print\n}\n</code></pre>\n\n<p>Where the first argument to the function is the text you're searching for. So:</p>\n\n<pre><code>$ grep_here_no_svn \"sometext\"\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>$ grep_here_no_svn \"sometext\" \"*.txt\"\n</code></pre>\n"
},
{
"answer_id": 223031,
"author": "Liudvikas Bukys",
"author_id": 5845,
"author_profile": "https://Stackoverflow.com/users/5845",
"pm_score": 2,
"selected": false,
"text": "<p>This is much more efficient since it invokes <code>grep</code> many fewer times, though it's hard to say it's more succinct:</p>\n\n<pre><code>find . -name '*.txt' -print0 | xargs -0 grep 'sometext' /dev/null\n</code></pre>\n\n<p>Notes:</p>\n\n<p>/<code>find -print0</code> and <code>xargs -0</code> makes pathnames with embedded blanks work correctly.</p>\n\n<p>The <code>/dev/null</code> argument makes sure grep always prepends a filename.</p>\n"
},
{
"answer_id": 223359,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "<p>Install <a href=\"http://petdance.com/ack/\" rel=\"nofollow noreferrer\"><code>ack</code></a> and use</p>\n\n<pre><code>ack -aG'\\.txt$' 'sometext'\n</code></pre>\n"
},
{
"answer_id": 224382,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": 2,
"selected": false,
"text": "<p>I second ephemient's suggestion of ack. I'm writing this post to highlight a particular issue.</p>\n\n<p>In response to jgormley (in the comments): <code>ack</code> is available as a single file which will work wherever the right Perl version is installed (which is everywhere).</p>\n\n<p>Given that on non-Linux platforms <code>grep</code> regularly does not accept <code>-R</code>, arguably using <code>ack</code> is <em>more</em> portable.</p>\n"
},
{
"answer_id": 240123,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 0,
"selected": false,
"text": "<p>You say that you like the output of your method (using find) better. The only difference I can see between them is that grepping multiple files will put the filename on the front. </p>\n\n<p>You can always (in GNU grep, but you must be using that or -r and --include wouldn't work) turn the filename off by using -h (--no-filename). The opposite, for anyone who does want filenames but has to use find for some other reason, is -H (--with-filename).</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29738/"
] |
I currently use the following command, but it's a little unwieldy to type. What's a shorter alternative?
```
find . -name '*.txt' -exec grep 'sometext' '{}' \; -print
```
Here are my requirements:
* limit to a file extension (I use SVN and don't want to be searching through all those .svn directories)
* can default to the current directory, but it's nice to be able to specify a different directory
* must be recursive
**UPDATE:** Here's my best solution so far:
```
grep -r 'sometext' * --include='*.txt'
```
**UPDATE #2:** After using grep for a bit, I realized that I like the output of my first method better. So, I followed the suggestions of several responders and simply made a shell script and now I call that with two parameters (extension and text to find).
|
grep has -r (recursive) and --include (to search only in files and directories matching a pattern).
|
222,834 |
<p>I want to generate some formatted output of data retrieved from an MS-Access database and stored in a <em>DataTable</em> object/variable, myDataTable. However, some of the fields in myDataTable cotain <em>dbNull</em> data. So, the following VB.net code snippet will give errors if the value of any of the fields <em>lastname</em>, <em>intials</em>, or <em>sID</em> is <em>dbNull</em>.</p>
<pre><code> dim myDataTable as DataTable
dim tmpStr as String
dim sID as Integer = 1
...
myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table
...
For Each myItem As DataRow In myDataTable.Rows
tmpStr = nameItem("lastname") + " " + nameItem("initials")
If myItem("sID")=sID Then
' Do something
End If
' print tmpStr
Next
</code></pre>
<p>So, how do i get the above code to work when the fields may contain <em>dbNull</em> without having to check each time if the data is dbNull as in <a href="https://stackoverflow.com/questions/105671/any-systemdbnullvalue-vs-any-is-systemdbnull">this question</a>?</p>
|
[
{
"answer_id": 222849,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 8,
"selected": true,
"text": "<p>The only way that i know of is to test for it, you can do a combined if though to make it easy.</p>\n\n<pre><code>If NOT IsDbNull(myItem(\"sID\")) AndAlso myItem(\"sID\") = sId Then\n 'Do success\nELSE\n 'Failure\nEnd If\n</code></pre>\n\n<p>I wrote in VB as that is what it looks like you need, even though you mixed languages.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Cleaned up to use IsDbNull to make it more readable</p>\n"
},
{
"answer_id": 222850,
"author": "Azim J",
"author_id": 4612,
"author_profile": "https://Stackoverflow.com/users/4612",
"pm_score": 1,
"selected": false,
"text": "<p>For the rows containing strings, I can convert them to strings as in changing</p>\n\n<pre><code>tmpStr = nameItem(\"lastname\") + \" \" + nameItem(\"initials\")\n</code></pre>\n\n<p>to</p>\n\n<pre><code>tmpStr = myItem(\"lastname\").toString + \" \" + myItem(\"intials\").toString\n</code></pre>\n\n<p>For the comparison in the <em>if</em> statement <em>myItem(\"sID\")=sID</em>, it needs to be change to</p>\n\n<pre><code>myItem(\"sID\").Equals(sID)\n</code></pre>\n\n<p>Then the code will run without any runtime errors due to <em>vbNull</em> data.</p>\n"
},
{
"answer_id": 222856,
"author": "brendan",
"author_id": 225,
"author_profile": "https://Stackoverflow.com/users/225",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the IsDbNull function:</p>\n\n<pre><code> If IsDbNull(myItem(\"sID\")) = False AndAlso myItem(\"sID\")==sID Then\n // Do something\nEnd If\n</code></pre>\n"
},
{
"answer_id": 222863,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use the Convert.ToString() and Convert.ToInteger() methods to convert items with DB null effectivly.</p>\n"
},
{
"answer_id": 961885,
"author": "Christian Hayter",
"author_id": 115413,
"author_profile": "https://Stackoverflow.com/users/115413",
"pm_score": 2,
"selected": false,
"text": "<p>Microsoft came up with DBNull in .NET 1.0 to represent database NULL. However, it's a pain in the behind to use because you can't create a strongly-typed variable to store a genuine value or null. Microsoft sort of solved that problem in .NET 2.0 with nullable types. However, you are still stuck with large chunks of API that use DBNull, and they can't be changed.</p>\n\n<p>Just a suggestion, but what I normally do is this:</p>\n\n<ol>\n<li>All variables containing data read from or written to a database should be able to handle null values. For value types, this means making them Nullable(Of T). For reference types (String and Byte()), this means allowing the value to be Nothing.</li>\n<li>Write a set of functions to convert back and forth between \"object that may contain DBNull\" and \"nullable .NET variable\". Wrap all calls to DBNull-style APIs in these functions, then pretend that DBNull doesn't exist.</li>\n</ol>\n"
},
{
"answer_id": 1723822,
"author": "Steve Wortham",
"author_id": 102896,
"author_profile": "https://Stackoverflow.com/users/102896",
"pm_score": 5,
"selected": false,
"text": "<p>I got tired of dealing with this problem so I wrote a NotNull() function to help me out.</p>\n\n<pre><code>Public Shared Function NotNull(Of T)(ByVal Value As T, ByVal DefaultValue As T) As T\n If Value Is Nothing OrElse IsDBNull(Value) Then\n Return DefaultValue\n Else\n Return Value\n End If\nEnd Function\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>If NotNull(myItem(\"sID\"), \"\") = sID Then\n ' Do something\nEnd If\n</code></pre>\n\n<p>My NotNull() function has gone through a couple of overhauls over the years. Prior to Generics, I simply specified everything as an Object. But I much prefer the Generic version.</p>\n"
},
{
"answer_id": 9953399,
"author": "Greg May",
"author_id": 1304623,
"author_profile": "https://Stackoverflow.com/users/1304623",
"pm_score": 3,
"selected": false,
"text": "<p>A variation on <a href=\"https://stackoverflow.com/a/1723822/7444103\">Steve Wortham's code</a>, to be used nominally with <code>nullable</code> types:</p>\n\n<pre><code>Private Shared Function GetNullable(Of T)(dataobj As Object) As T\n If Convert.IsDBNull(dataobj) Then\n Return Nothing\n Else\n Return CType(dataobj, T)\n End If\nEnd Function\n</code></pre>\n\n<p>e.g.</p>\n\n<pre><code>mynullable = GetNullable(Of Integer?)(myobj)\n</code></pre>\n\n<p>You can then query <code>mynullable</code> (e.g., <code>mynullable.HasValue</code>)</p>\n"
},
{
"answer_id": 12281381,
"author": "John B",
"author_id": 1649034,
"author_profile": "https://Stackoverflow.com/users/1649034",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using a BLL/DAL setup try the iif when reading into the object in the DAL</p>\n\n<pre><code>While reader.Read()\n colDropdownListNames.Add(New DDLItem( _\n CType(reader(\"rid\"), Integer), _\n CType(reader(\"Item_Status\"), String), _\n CType(reader(\"Text_Show\"), String), _\n CType( IIf(IsDBNull(reader(\"Text_Use\")), \"\", reader(\"Text_Use\")) , String), _\n CType(reader(\"Text_SystemOnly\"), String), _\n CType(reader(\"Parent_rid\"), Integer)))\nEnd While\n</code></pre>\n"
},
{
"answer_id": 18170851,
"author": "JAY SINGH",
"author_id": 2670414,
"author_profile": "https://Stackoverflow.com/users/2670414",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Hello Friends</strong></p>\n\n<p><strong>This is the shortest method to check db Null in DataGrid and convert to string</strong></p>\n\n<ol>\n<li>create the cell validating event and write this code</li>\n<li>If Convert.ToString(dgv.CurrentCell.Value) = \"\" Then</li>\n<li>CurrentCell.Value = \"\"</li>\n<li>End If </li>\n</ol>\n"
},
{
"answer_id": 20246737,
"author": "BINU NARAYANAN NELLIYAMPATHI",
"author_id": 3042456,
"author_profile": "https://Stackoverflow.com/users/3042456",
"pm_score": 1,
"selected": false,
"text": "<pre><code> VB.Net\n ========\n Dim da As New SqlDataAdapter\n Dim dt As New DataTable\n Call conecDB() 'Connection to Database\n da.SelectCommand = New SqlCommand(\"select max(RefNo) from BaseData\", connDB)\n\n da.Fill(dt)\n\n If dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) = \"\" Then\n MsgBox(\"datbase is null\")\n\n ElseIf dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) <> \"\" Then\n MsgBox(\"datbase have value\")\n\n End If\n</code></pre>\n"
},
{
"answer_id": 21633737,
"author": "user3284874",
"author_id": 3284874,
"author_profile": "https://Stackoverflow.com/users/3284874",
"pm_score": 0,
"selected": false,
"text": "<p>This is <strong>BY FAR</strong> the easiest way to convert <code>DBNull</code> to a string.\nThe trick is that you <strong>CANNOT</strong> use the <code>TRIM</code> function (which was my initial problem) when referring to the fields from the database:</p>\n\n<p><strong>BEFORE</strong> (produced error msg):</p>\n\n<pre><code>Me.txtProvNum.Text = IIf(Convert.IsDBNull(TRIM(myReader(\"Prov_Num\"))), \"\", TRIM(myReader(\"Prov_Num\")))\n</code></pre>\n\n<p><strong>AFTER</strong> (no more error msg :-) ):</p>\n\n<pre><code>Me.txtProvNum.Text = IIf(Convert.IsDBNull(myReader(\"Prov_Num\")), \"\", myReader(\"Prov_Num\"))\n</code></pre>\n"
},
{
"answer_id": 39711897,
"author": "Sabbir Hassan",
"author_id": 4409462,
"author_profile": "https://Stackoverflow.com/users/4409462",
"pm_score": 1,
"selected": false,
"text": "<p>I think this should be much easier to use:</p>\n\n<blockquote>\n <p>select ISNULL(sum(field),0) from tablename</p>\n</blockquote>\n\n<p>Copied from: <a href=\"http://www.codeproject.com/Questions/736515/How-do-I-avoide-Conversion-from-type-DBNull-to-typ\" rel=\"nofollow\">http://www.codeproject.com/Questions/736515/How-do-I-avoide-Conversion-from-type-DBNull-to-typ</a></p>\n"
},
{
"answer_id": 69917487,
"author": "B H",
"author_id": 1539001,
"author_profile": "https://Stackoverflow.com/users/1539001",
"pm_score": 0,
"selected": false,
"text": "<p>Simple, but not obvious.</p>\n<pre><code>DbNull.Value.Equals(myValue)\n</code></pre>\n<p>I hate VB.NET</p>\n"
},
{
"answer_id": 74531408,
"author": "schlebe",
"author_id": 948359,
"author_profile": "https://Stackoverflow.com/users/948359",
"pm_score": 0,
"selected": false,
"text": "<p>For your problem, you can use following special workaround coding that only exists in <code>VB.Net</code>.</p>\n<pre><code>Dim nId As Integer = dr("id") + "0"\n</code></pre>\n<p>This code will replace <code>DBNull</code> value contained in <code>id</code> column by integer 0.</p>\n<p>The only acceptable default value is "0" because this expression must also be used when <code>dr("id")</code> is not NULL !</p>\n<p>So, using this technic, your code would be</p>\n<pre><code> Dim myDataTable as DataTable\n Dim s as String\n Dim sID as Integer = 1\n\n ...\n myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table\n ...\n\n For Each myItem As DataRow In myDataTable.Rows\n s = nameItem("lastname") + " " + nameItem("initials")\n If myItem("sID") + "0" = sID Then\n ' Do something\n End If\n Next\n</code></pre>\n<p>I have tested this solution and it works on my PC on Visual Studio 2022.</p>\n<p>PS: if <code>sID</code> can be equal to 0 and you want to do something distinct when <code>dr("sID")</code> value is NULL, you must also adept you program and perhaps use <code>Extension</code> as proposed at end of this answer.</p>\n<p>I have tested following statements</p>\n<pre><code>Dim iNo1 As Integer = dr("numero") + "0"\nDim iNo2 As Integer = dr("numero") & "0" '-> iNo = 10 when dr() = 1\nDim iNo3 As Integer = dr("numero") + "4" '-> iNo = 5 when dr() = 1\nDim iNo4 As Integer = dr("numero") & "4" '-> iNo = 14 when dr() = 1\nDim iNo5 As Integer = dr("numero") + "" -> System.InvalidCastException : 'La conversion de la chaîne "" en type 'Integer' n'est pas valide.'\nDim iNo6 As Integer = dr("numero") & "" -> System.InvalidCastException : 'La conversion de la chaîne "" en type 'Integer' n'est pas valide.'\nDim iNo7 As Integer = "" + dr("numero") -> System.InvalidCastException : 'La conversion de la chaîne "" en type 'Integer' n'est pas valide.'\nDim iNo8 As Integer = "" & dr("numero") -> System.InvalidCastException : 'La conversion de la chaîne "" en type 'Integer' n'est pas valide.'\nDim iNo9 As Integer = "0" + dr("numero")\nDim iNo0 As Integer = "0" & dr("numero")\n</code></pre>\n<p>Following statements works also correctly</p>\n<pre><code>Dim iNo9 As Integer = "0" + dr("numero")\nDim iNo0 As Integer = "0" & dr("numero")\n</code></pre>\n<p>I recognize that is a little tricky.</p>\n<p>If trick are not your tips, you can also define an <code>Extension</code> so that following code works.</p>\n<pre><code>Dim iNo = dr.GetInteger("numero",0)\n</code></pre>\n<p>where GetInteger() code can be following</p>\n<pre><code>Module Extension\n '***********************************************************************\n '* GetString()\n '***********************************************************************\n\n <Extension()>\n Public Function GetString(ByRef rd As SqlDataReader, ByRef sName As String, Optional ByVal sDefault As String = "") As String\n Return GetString(rd, rd.GetOrdinal(sName), sDefault)\n End Function\n\n <Extension()>\n Public Function GetString(ByRef rd As SqlDataReader, ByVal iCol As Integer, Optional ByVal sDefault As String = "") As String\n If rd.IsDBNull(iCol) Then\n Return sDefault\n Else\n Return rd.Item(iCol).ToString()\n End If\n End Function\n\n '***********************************************************************\n '* GetInteger()\n '***********************************************************************\n\n <Extension()>\n Public Function GetInteger(ByRef rd As SqlDataReader, ByRef sName As String, Optional ByVal iDefault As Integer = -1) As Integer\n Return GetInteger(rd, rd.GetOrdinal(sName), iDefault)\n End Function\n\n <Extension()>\n Public Function GetInteger(ByRef rd As SqlDataReader, ByVal iCol As Integer, Optional ByVal iDefault As Integer = -1) As Integer\n If rd.IsDBNull(iCol) Then\n Return iDefault\n Else\n Return rd.Item(iCol)\n End If\n End Function\n\nEnd Module\n</code></pre>\n<p>These methods are more explicitely and less tricky.</p>\n<p>In addition, it is possible to define default values other than ZERO and also specific version as <code>GetBoolean()</code> or <code>GetDate()</code>, etc ...</p>\n<p>Another possibility is to report SQL default conversion in SQL command using <code>COALESCE</code> SQL command !</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4612/"
] |
I want to generate some formatted output of data retrieved from an MS-Access database and stored in a *DataTable* object/variable, myDataTable. However, some of the fields in myDataTable cotain *dbNull* data. So, the following VB.net code snippet will give errors if the value of any of the fields *lastname*, *intials*, or *sID* is *dbNull*.
```
dim myDataTable as DataTable
dim tmpStr as String
dim sID as Integer = 1
...
myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table
...
For Each myItem As DataRow In myDataTable.Rows
tmpStr = nameItem("lastname") + " " + nameItem("initials")
If myItem("sID")=sID Then
' Do something
End If
' print tmpStr
Next
```
So, how do i get the above code to work when the fields may contain *dbNull* without having to check each time if the data is dbNull as in [this question](https://stackoverflow.com/questions/105671/any-systemdbnullvalue-vs-any-is-systemdbnull)?
|
The only way that i know of is to test for it, you can do a combined if though to make it easy.
```
If NOT IsDbNull(myItem("sID")) AndAlso myItem("sID") = sId Then
'Do success
ELSE
'Failure
End If
```
I wrote in VB as that is what it looks like you need, even though you mixed languages.
**Edit**
Cleaned up to use IsDbNull to make it more readable
|
222,839 |
<p>I have a WPF window for editing database information, which is represented using an Entity Framework object. When the user closes the window, I'd like to notice in the Closing event whether the information has changed and show a message box offering to save the changes to the database.</p>
<p>Unfortunately, changes to the currently focused edit aren't assigned to the binding source until the edit loses focus, which happens at some point after the Closing event has been processed.</p>
<p>Ideally, there would be a routine which commits all changes in the view hierarchy that I could call before checking to see if my entity has been modified. I've also looked for information on programmatically clearing the focus in the control with focus, but can't figure out how to do it.</p>
<p>My question is, how is this typically handled?</p>
|
[
{
"answer_id": 224287,
"author": "Donnelle",
"author_id": 28074,
"author_profile": "https://Stackoverflow.com/users/28074",
"pm_score": 4,
"selected": true,
"text": "<p>This should get you pretty close:</p>\n\n<pre><code>\n\nprivate void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n{\n ForceDataValidation();\n}\n\n\nprivate static void ForceDataValidation()\n{\n TextBox textBox = Keyboard.FocusedElement as TextBox;\n\n if (textBox != null)\n {\n BindingExpression be = textBox.GetBindingExpression(TextBox.TextProperty);\n if (be != null && !textBox.IsReadOnly && textBox.IsEnabled)\n {\n be.UpdateSource();\n }\n }\n\n}\n\n\n</code></pre>\n"
},
{
"answer_id": 224609,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 0,
"selected": false,
"text": "<p>Also look at the sugestions in <a href=\"https://stackoverflow.com/questions/57493/wpf-databind-before-saving#58443\">this</a> post</p>\n"
},
{
"answer_id": 229871,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is to set the focus somewhere.\nYou can set the focus back immediately, but setting the focus anywhere will trigger the LostFocus-Event on any type of control and make it update its stuff:</p>\n\n<pre><code>IInputElement x = System.Windows.Input.Keyboard.FocusedElement;\nDummyField.Focus();\nx.Focus();\n</code></pre>\n\n<p>Another way would be to get the focused element, get the binding element from the focused element, and trigger the update manually. An example for TextBox and ComboBox (you would need to add any control type you need to support):</p>\n\n<pre><code>TextBox t = Keyboard.FocusedElement as TextBox;\nif ((t != null) && (t.GetBindingExpression(TextBox.TextProperty) != null))\n t.GetBindingExpression(TextBox.TextProperty).UpdateSource();\nComboBox c = Keyboard.FocusedElement as ComboBox;\nif ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null))\n c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();\n</code></pre>\n"
},
{
"answer_id": 4724716,
"author": "Dave the Rave",
"author_id": 580011,
"author_profile": "https://Stackoverflow.com/users/580011",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming that there is more than one control in the tab sequence, the following solution appears to be complete and general (just cut-and-paste)...</p>\n\n<pre><code>Control currentControl = System.Windows.Input.Keyboard.FocusedElement as Control;\n\nif (currentControl != null)\n{\n // Force focus away from the current control to update its binding source.\n currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));\n currentControl.Focus();\n}\n</code></pre>\n"
},
{
"answer_id": 4724828,
"author": "sourcenouveau",
"author_id": 111327,
"author_profile": "https://Stackoverflow.com/users/111327",
"pm_score": 5,
"selected": false,
"text": "<p>In WPF you can change a <code>Binding</code> to update the source on modification, rather than on losing the focus. This is done by setting the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx\"><code>UpdateSourceTrigger</code></a> property to <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger.aspx\"><code>PropertyChanged</code></a>:</p>\n\n<pre><code>Value=\"{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}\"\n</code></pre>\n"
},
{
"answer_id": 26358931,
"author": "user3738532",
"author_id": 3738532,
"author_profile": "https://Stackoverflow.com/users/3738532",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe you need to remove the focus from the current element</p>\n\n<pre><code>private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n{\n FocusManager.SetFocusedElement(this, null);\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30002/"
] |
I have a WPF window for editing database information, which is represented using an Entity Framework object. When the user closes the window, I'd like to notice in the Closing event whether the information has changed and show a message box offering to save the changes to the database.
Unfortunately, changes to the currently focused edit aren't assigned to the binding source until the edit loses focus, which happens at some point after the Closing event has been processed.
Ideally, there would be a routine which commits all changes in the view hierarchy that I could call before checking to see if my entity has been modified. I've also looked for information on programmatically clearing the focus in the control with focus, but can't figure out how to do it.
My question is, how is this typically handled?
|
This should get you pretty close:
```
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
ForceDataValidation();
}
private static void ForceDataValidation()
{
TextBox textBox = Keyboard.FocusedElement as TextBox;
if (textBox != null)
{
BindingExpression be = textBox.GetBindingExpression(TextBox.TextProperty);
if (be != null && !textBox.IsReadOnly && textBox.IsEnabled)
{
be.UpdateSource();
}
}
}
```
|
222,841 |
<p>Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?</p>
|
[
{
"answer_id": 222847,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 11,
"selected": true,
"text": "<pre><code>var arr = Array.prototype.slice.call( htmlCollection )\n</code></pre>\n\n<p>will have the same effect using \"native\" code.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is <em>effectively</em> equivalent:</p>\n\n<pre><code>var arr = [].slice.call(htmlCollection);\n</code></pre>\n\n<p>But note per @JussiR's comment, that unlike the \"verbose\" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Since ECMAScript 2015 (ES 6) there is also <a href=\"http://ecma-international.org/ecma-262/8.0/#sec-array.from\" rel=\"noreferrer\"><em>Array.from</em></a>:</p>\n\n<pre><code>var arr = Array.from(htmlCollection);\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>ECMAScript 2015 also provides the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"noreferrer\">spread operator</a>, which is functionally equivalent to <code>Array.from</code> (although note that <code>Array.from</code> supports a mapping function as the second argument).</p>\n\n<pre><code>var arr = [...htmlCollection];\n</code></pre>\n\n<p>I've confirmed that both of the above work on <code>NodeList</code>.</p>\n\n<p>A performance comparison for the mentioned methods: <a href=\"http://jsben.ch/h2IFA\" rel=\"noreferrer\">http://jsben.ch/h2IFA</a></p>\n"
},
{
"answer_id": 1872365,
"author": "Gareth Davis",
"author_id": 31480,
"author_profile": "https://Stackoverflow.com/users/31480",
"pm_score": 3,
"selected": false,
"text": "<p>For a cross browser implementation I'd sugguest you look at <a href=\"http://prototypejs.org/\" rel=\"noreferrer\">prototype.js</a> <code>$A</code> function </p>\n\n<p><a href=\"http://prototypejs.org/assets/2009/8/31/prototype.js\" rel=\"noreferrer\">copyed from 1.6.1</a>:</p>\n\n<pre><code>function $A(iterable) {\n if (!iterable) return [];\n if ('toArray' in Object(iterable)) return iterable.toArray();\n var length = iterable.length || 0, results = new Array(length);\n while (length--) results[length] = iterable[length];\n return results;\n}\n</code></pre>\n\n<p>It doesn't use <code>Array.prototype.slice</code> probably because it isn't available on every browser. I'm afraid the performance is pretty bad as there a the fall back is a javascript loop over the <code>iterable</code>.</p>\n"
},
{
"answer_id": 16595969,
"author": "Gustavo",
"author_id": 1572493,
"author_profile": "https://Stackoverflow.com/users/1572493",
"pm_score": 2,
"selected": false,
"text": "<p>This is my personal solution, based on the information here (this thread):</p>\n\n<pre><code>var Divs = new Array(); \nvar Elemns = document.getElementsByClassName(\"divisao\");\n try {\n Divs = Elemns.prototype.slice.call(Elemns);\n } catch(e) {\n Divs = $A(Elemns);\n }\n</code></pre>\n\n<p>Where $A was described by Gareth Davis in his post:</p>\n\n<pre><code>function $A(iterable) {\n if (!iterable) return [];\n if ('toArray' in Object(iterable)) return iterable.toArray();\n var length = iterable.length || 0, results = new Array(length);\n while (length--) results[length] = iterable[length];\n return results;\n}\n</code></pre>\n\n<p>If browser supports the best way, ok, otherwise will use the cross browser.</p>\n"
},
{
"answer_id": 22676083,
"author": "Codesmith",
"author_id": 586652,
"author_profile": "https://Stackoverflow.com/users/586652",
"pm_score": 5,
"selected": false,
"text": "<p>I saw a more concise method of getting <code>Array.prototype</code> methods in general that works just as well. Converting an <code>HTMLCollection</code> object into an <code>Array</code> object is demonstrated below:</p>\n\n<pre>\n[].slice.call( yourHTMLCollectionObject );\n</pre>\n\n<p>And, as mentioned in the comments, <strong>for old browsers such as IE7 and earlier,</strong> you simply have to use a compatibility function, like:</p>\n\n<pre><code>function toArray(x) {\n for(var i = 0, a = []; i < x.length; i++)\n a.push(x[i]);\n\n return a\n}\n</code></pre>\n\n<p>I know this is an old question, but I felt the accepted answer was a little incomplete; so I thought I'd throw this out there FWIW.</p>\n"
},
{
"answer_id": 37042313,
"author": "mido",
"author_id": 3074768,
"author_profile": "https://Stackoverflow.com/users/3074768",
"pm_score": 7,
"selected": false,
"text": "<p>not sure if this is the most efficient, but a concise ES6 syntax might be:</p>\n\n<pre><code>let arry = [...htmlCollection] \n</code></pre>\n\n<hr>\n\n<p>Edit: Another one, from Chris_F comment:</p>\n\n<pre><code>let arry = Array.from(htmlCollection)\n</code></pre>\n"
},
{
"answer_id": 38929954,
"author": "Nicholas",
"author_id": 195050,
"author_profile": "https://Stackoverflow.com/users/195050",
"pm_score": 3,
"selected": false,
"text": "<p>This works in all browsers including earlier IE versions.</p>\n\n<pre><code>var arr = [];\n[].push.apply(arr, htmlCollection);\n</code></pre>\n\n<p>Since jsperf is still down at the moment, here is a jsfiddle that compares the performance of different methods. <a href=\"https://jsfiddle.net/qw9qf48j/\" rel=\"noreferrer\">https://jsfiddle.net/qw9qf48j/</a></p>\n"
},
{
"answer_id": 51272101,
"author": "Shahar Shokrani",
"author_id": 6844481,
"author_profile": "https://Stackoverflow.com/users/6844481",
"pm_score": 3,
"selected": false,
"text": "<p>To convert array-like to array in efficient way we can make use of the <a href=\"https://api.jquery.com/jQuery.makeArray/\" rel=\"noreferrer\">jQuery</a> <code>makeArray</code> :</p>\n\n<blockquote>\n <p>makeArray: Convert an array-like object into a true JavaScript array.</p>\n</blockquote>\n\n<p>Usage:</p>\n\n<pre><code>var domArray = jQuery.makeArray(htmlCollection);\n</code></pre>\n\n<hr>\n\n<p>A little extra:</p>\n\n<p>If you do not want to keep reference to the array object (most of the time HTMLCollections are dynamically changes so its better to copy them into another array, This example pay close attention to performance: </p>\n\n<pre><code>var domDataLength = domData.length //Better performance, no need to calculate every iteration the domArray length\nvar resultArray = new Array(domDataLength) // Since we know the length its improves the performance to declare the result array from the beginning.\n\nfor (var i = 0 ; i < domDataLength ; i++) {\n resultArray[i] = domArray[i]; //Since we already declared the resultArray we can not make use of the more expensive push method.\n}\n</code></pre>\n\n<p>What is array-like?</p>\n\n<p><a href=\"https://api.jquery.com/jQuery.makeArray/\" rel=\"noreferrer\">HTMLCollection</a> is an <code>\"array-like\"</code> object, the <a href=\"http://www.nfriedly.com/techblog/2009/06/advanced-javascript-objects-arrays-and-array-like-objects/\" rel=\"noreferrer\">array-like</a> objects are similar to array's object but missing a lot of its functionally definition:</p>\n\n<blockquote>\n <p>Array-like objects look like arrays. They have various numbered\n elements and a length property. But that’s where the similarity stops.\n Array-like objects do not have any of Array’s functions, and for-in\n loops don’t even work!</p>\n</blockquote>\n"
},
{
"answer_id": 65992448,
"author": "Roman Karagodin",
"author_id": 14282340,
"author_profile": "https://Stackoverflow.com/users/14282340",
"pm_score": 2,
"selected": false,
"text": "<p>I suppose that <strong>calling <code>Array.prototype</code> functions</strong> on instances of <code>HTMLCollection</code> is a much better option than converting collections to arrays (e.g.,<code>[...collection]</code> or <code>Array.from(collection)</code>), because in the latter case a collection is unnecessarily implicitly iterated and a new array object is created, and this eats up additional resources. <code>Array.prototype</code> iterating functions can be safely called upon objects with consecutive numeric keys starting from <code>[0]</code> and a <code>length</code> property with a valid number value of such keys' quantity (including, e.g., instances of <code>HTMLCollection</code> and <code>FileList</code>), so it's a reliable way. Also, if there is a frequent need in such operations, an empty array <code>[]</code> can be used for quick access to <code>Array.prototype</code> functions; or a shortcut for <code>Array.prototype</code> can be created instead. A runnable example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const _ = Array.prototype;\nconst collection = document.getElementById('ol').children;\nalert(_.reduce.call(collection, (acc, { textContent }, i) => {\n return acc += `${i+1}) ${textContent}` + '\\n';\n}, ''));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><ol id=\"ol\">\n <li>foo</li>\n <li>bar</li>\n <li>bat</li>\n <li>baz</li>\n</ol></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 70576919,
"author": "Avi",
"author_id": 15185401,
"author_profile": "https://Stackoverflow.com/users/15185401",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes, Even You have written code the correct way, But still it doesn't work properly.</p>\n<pre><code>var allbuttons = document.getElementsByTagName("button");\nconsole.log(allbuttons);\n\nvar copyAllButtons = [];\nfor (let i = 0; i < allbuttons.length; i++) {\n copyAllButtons.push(allbuttons[i]);\n}\nconsole.log(copyAllButtons);\n</code></pre>\n<p>you get empty array.\nLike, This</p>\n<pre><code>HTMLCollection []\n[]\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/YKgwq.jpg\" rel=\"nofollow noreferrer\">Console_javascript</a></p>\n<p>For Solving this problem, You have to add link of javascript file after body tag in html file.</p>\n<pre><code><script src="./script.js"></script>\n</code></pre>\n<p>As you can see below,\n<a href=\"https://i.stack.imgur.com/hCTSf.png\" rel=\"nofollow noreferrer\">html_file</a></p>\n<p>Final Output</p>\n<pre><code>HTMLCollection(6) [button.btn.btn-dark.click-me, button.btn.btn-dark.reset, button#b, button#b, button#b, button#b, b: button#b]\n(6) [button.btn.btn-dark.click-me, button.btn.btn-dark.reset, button#b, button#b, button#b, button#b]\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20/"
] |
Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?
|
```
var arr = Array.prototype.slice.call( htmlCollection )
```
will have the same effect using "native" code.
**Edit**
Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is *effectively* equivalent:
```
var arr = [].slice.call(htmlCollection);
```
But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.
**Edit**
Since ECMAScript 2015 (ES 6) there is also [*Array.from*](http://ecma-international.org/ecma-262/8.0/#sec-array.from):
```
var arr = Array.from(htmlCollection);
```
**Edit**
ECMAScript 2015 also provides the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), which is functionally equivalent to `Array.from` (although note that `Array.from` supports a mapping function as the second argument).
```
var arr = [...htmlCollection];
```
I've confirmed that both of the above work on `NodeList`.
A performance comparison for the mentioned methods: <http://jsben.ch/h2IFA>
|
222,877 |
<p>What's the difference between:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
</code></pre>
<p>and:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
</code></pre>
<p>I've seen <code>super</code> being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.</p>
|
[
{
"answer_id": 222922,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 9,
"selected": true,
"text": "<p>The benefits of <code>super()</code> in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.</p>\n\n<p>However, it's almost impossible to use multiple-inheritance without <code>super()</code>. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended <code>Child</code> and a mixin, their code would not work properly.</p>\n"
},
{
"answer_id": 224020,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 5,
"selected": false,
"text": "<p>Doesn't all of this assume that the base class is a new-style class?</p>\n\n<pre><code>class A:\n def __init__(self):\n print(\"A.__init__()\")\n\nclass B(A):\n def __init__(self):\n print(\"B.__init__()\")\n super(B, self).__init__()\n</code></pre>\n\n<p>Will not work in Python 2. <code>class A</code> must be new-style, i.e: <code>class A(object)</code></p>\n"
},
{
"answer_id": 33469090,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 9,
"selected": false,
"text": "<h2>What's the difference?</h2>\n<pre><code>SomeBaseClass.__init__(self) \n</code></pre>\n<p>means to call <code>SomeBaseClass</code>'s <code>__init__</code>. while</p>\n<pre><code>super().__init__()\n</code></pre>\n<p>means to call a bound <code>__init__</code> from the parent class that follows <code>SomeBaseClass</code>'s child class (the one that defines this method) in the instance's Method Resolution Order (MRO).</p>\n<p>If the instance is a subclass of <em>this</em> child class, there may be a different parent that comes next in the MRO.</p>\n<h3>Explained simply</h3>\n<p>When you write a class, you want other classes to be able to use it. <code>super()</code> makes it easier for other classes to use the class you're writing.</p>\n<p>As Bob Martin says, a good architecture allows you to postpone decision making as long as possible.</p>\n<p><code>super()</code> can enable that sort of architecture.</p>\n<p>When another class subclasses the class you wrote, it could also be inheriting from other classes. And those classes could have an <code>__init__</code> that comes after this <code>__init__</code> based on the ordering of the classes for method resolution.</p>\n<p>Without <code>super</code> you would likely hard-code the parent of the class you're writing (like the example does). This would mean that you would not call the next <code>__init__</code> in the MRO, and you would thus not get to reuse the code in it.</p>\n<p>If you're writing your own code for personal use, you may not care about this distinction. But if you want others to use your code, using <code>super</code> is one thing that allows greater flexibility for users of the code.</p>\n<h3>Python 2 versus 3</h3>\n<p>This works in Python 2 and 3:</p>\n<pre><code>super(Child, self).__init__()\n</code></pre>\n<p>This only works in Python 3:</p>\n<pre><code>super().__init__()\n</code></pre>\n<p>It works with no arguments by moving up in the stack frame and getting the first argument to the method (usually <code>self</code> for an instance method or <code>cls</code> for a class method - but could be other names) and finding the class (e.g. <code>Child</code>) in the free variables (it is looked up with the name <code>__class__</code> as a free closure variable in the method).</p>\n<p>I used to prefer to demonstrate the cross-compatible way of using <code>super</code>, but now that Python 2 is largely deprecated, I will demonstrate the Python 3 way of doing things, that is, calling <code>super</code> with no arguments.</p>\n<h3>Indirection with Forward Compatibility</h3>\n<p>What does it give you? For single inheritance, the examples from the question are practically identical from a static analysis point of view. However, using <code>super</code> gives you a layer of indirection with forward compatibility.</p>\n<p>Forward compatibility is very important to seasoned developers. You want your code to keep working with minimal changes as you change it. When you look at your revision history, you want to see precisely what changed when.</p>\n<p>You may start off with single inheritance, but if you decide to add another base class, you only have to change the line with the bases - if the bases change in a class you inherit from (say a mixin is added) you'd change nothing in this class.</p>\n<p>In Python 2, getting the arguments to <code>super</code> and the correct method arguments right can be a little confusing, so I suggest using the Python 3 only method of calling it.</p>\n<p>If you know you're using <code>super</code> correctly with single inheritance, that makes debugging less difficult going forward.</p>\n<h3>Dependency Injection</h3>\n<p>Other people can use your code and inject parents into the method resolution:</p>\n<pre><code>class SomeBaseClass(object):\n def __init__(self):\n print('SomeBaseClass.__init__(self) called')\n \nclass UnsuperChild(SomeBaseClass):\n def __init__(self):\n print('UnsuperChild.__init__(self) called')\n SomeBaseClass.__init__(self)\n \nclass SuperChild(SomeBaseClass):\n def __init__(self):\n print('SuperChild.__init__(self) called')\n super().__init__()\n</code></pre>\n<p>Say you add another class to your object, and want to inject a class between Foo and Bar (for testing or some other reason):</p>\n<pre><code>class InjectMe(SomeBaseClass):\n def __init__(self):\n print('InjectMe.__init__(self) called')\n super().__init__()\n\nclass UnsuperInjector(UnsuperChild, InjectMe): pass\n\nclass SuperInjector(SuperChild, InjectMe): pass\n</code></pre>\n<p>Using the un-super child fails to inject the dependency because the child you're using has hard-coded the method to be called after its own:</p>\n<pre><code>>>> o = UnsuperInjector()\nUnsuperChild.__init__(self) called\nSomeBaseClass.__init__(self) called\n</code></pre>\n<p>However, the class with the child that uses <code>super</code> can correctly inject the dependency:</p>\n<pre><code>>>> o2 = SuperInjector()\nSuperChild.__init__(self) called\nInjectMe.__init__(self) called\nSomeBaseClass.__init__(self) called\n</code></pre>\n<h3>Addressing a comment</h3>\n<blockquote>\n<p>Why in the world would this be useful?</p>\n</blockquote>\n<p>Python linearizes a complicated inheritance tree via the <a href=\"https://en.wikipedia.org/wiki/C3_linearization\" rel=\"noreferrer\">C3 linearization algorithm</a> to create a Method Resolution Order (MRO).</p>\n<p>We want methods to be looked up <em>in that order</em>.</p>\n<p>For a method defined in a parent to find the next one in that order without <code>super</code>, it would have to</p>\n<ol>\n<li>get the mro from the instance's type</li>\n<li>look for the type that defines the method</li>\n<li>find the next type with the method</li>\n<li>bind that method and call it with the expected arguments</li>\n</ol>\n<blockquote>\n<p>The <code>UnsuperChild</code> should not have access to <code>InjectMe</code>. Why isn't the conclusion "Always avoid using <code>super</code>"? What am I missing here?</p>\n</blockquote>\n<p>The <code>UnsuperChild</code> does <em>not</em> have access to <code>InjectMe</code>. It is the <code>UnsuperInjector</code> that has access to <code>InjectMe</code> - and yet cannot call that class's method from the method it inherits from <code>UnsuperChild</code>.</p>\n<p>Both Child classes intend to call a method by the same name that comes next in the MRO, which might be <em>another</em> class it was not aware of when it was created.</p>\n<p>The one without <code>super</code> hard-codes its parent's method - thus is has restricted the behavior of its method, and subclasses cannot inject functionality in the call chain.</p>\n<p>The one <em>with</em> <code>super</code> has greater flexibility. The call chain for the methods can be intercepted and functionality injected.</p>\n<p>You may not need that functionality, but subclassers of your code may.</p>\n<h2>Conclusion</h2>\n<p>Always use <code>super</code> to reference the parent class instead of hard-coding it.</p>\n<p>What you intend is to reference the parent class that is next-in-line, not specifically the one you see the child inheriting from.</p>\n<p>Not using <code>super</code> can put unnecessary constraints on users of your code.</p>\n"
},
{
"answer_id": 39376081,
"author": "Michael Ekoka",
"author_id": 56974,
"author_profile": "https://Stackoverflow.com/users/56974",
"pm_score": 5,
"selected": false,
"text": "<p>When calling <code>super()</code> to resolve to a parent's version of a classmethod, instance method, or staticmethod, we want to pass the current class whose scope we are in as the first argument, to indicate which parent's scope we're trying to resolve to, and as a second argument the object of interest to indicate which object we're trying to apply that scope to.</p>\n\n<p>Consider a class hierarchy <code>A</code>, <code>B</code>, and <code>C</code> where each class is the parent of the one following it, and <code>a</code>, <code>b</code>, and <code>c</code> respective instances of each.</p>\n\n<pre><code>super(B, b) \n# resolves to the scope of B's parent i.e. A \n# and applies that scope to b, as if b was an instance of A\n\nsuper(C, c) \n# resolves to the scope of C's parent i.e. B\n# and applies that scope to c\n\nsuper(B, c) \n# resolves to the scope of B's parent i.e. A \n# and applies that scope to c\n</code></pre>\n\n<h2>Using <code>super</code> with a staticmethod</h2>\n\n<p>e.g. using <code>super()</code> from within the <code>__new__()</code> method</p>\n\n<pre><code>class A(object):\n def __new__(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n return super(A, cls).__new__(cls, *a, **kw)\n</code></pre>\n\n<p>Explanation: </p>\n\n<p>1- even though it's usual for <code>__new__()</code> to take as its first param a reference to the calling class, it is <em>not</em> implemented in Python as a classmethod, but rather a staticmethod. That is, a reference to a class has to be passed explicitly as the first argument when calling <code>__new__()</code> directly:</p>\n\n<pre><code># if you defined this\nclass A(object):\n def __new__(cls):\n pass\n\n# calling this would raise a TypeError due to the missing argument\nA.__new__()\n\n# whereas this would be fine\nA.__new__(A)\n</code></pre>\n\n<p>2- when calling <code>super()</code> to get to the parent class we pass the child class <code>A</code> as its first argument, then we pass a reference to the object of interest, in this case it's the class reference that was passed when <code>A.__new__(cls)</code> was called. In most cases it also happens to be a reference to the child class. In some situations it might not be, for instance in the case of multiple generation inheritances.</p>\n\n<pre><code>super(A, cls)\n</code></pre>\n\n<p>3- since as a general rule <code>__new__()</code> is a staticmethod, <code>super(A, cls).__new__</code> will also return a staticmethod and needs to be supplied all arguments explicitly, including the reference to the object of insterest, in this case <code>cls</code>.</p>\n\n<pre><code>super(A, cls).__new__(cls, *a, **kw)\n</code></pre>\n\n<p>4- doing the same thing without <code>super</code></p>\n\n<pre><code>class A(object):\n def __new__(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n return object.__new__(cls, *a, **kw)\n</code></pre>\n\n<h2>Using <code>super</code> with an instance method</h2>\n\n<p>e.g. using <code>super()</code> from within <code>__init__()</code></p>\n\n<pre><code>class A(object): \n def __init__(self, *a, **kw):\n # ...\n # you make some changes here\n # ...\n\n super(A, self).__init__(*a, **kw)\n</code></pre>\n\n<p>Explanation:</p>\n\n<p>1- <code>__init__</code> is an instance method, meaning that it takes as its first argument a reference to an instance. When called directly from the instance, the reference is passed implicitly, that is you don't need to specify it:</p>\n\n<pre><code># you try calling `__init__()` from the class without specifying an instance\n# and a TypeError is raised due to the expected but missing reference\nA.__init__() # TypeError ...\n\n# you create an instance\na = A()\n\n# you call `__init__()` from that instance and it works\na.__init__()\n\n# you can also call `__init__()` with the class and explicitly pass the instance \nA.__init__(a)\n</code></pre>\n\n<p>2- when calling <code>super()</code> within <code>__init__()</code> we pass the child class as the first argument and the object of interest as a second argument, which in general is a reference to an instance of the child class.</p>\n\n<pre><code>super(A, self)\n</code></pre>\n\n<p>3- The call <code>super(A, self)</code> returns a proxy that will resolve the scope and apply it to <code>self</code> as if it's now an instance of the parent class. Let's call that proxy <code>s</code>. Since <code>__init__()</code> is an instance method the call <code>s.__init__(...)</code> will implicitly pass a reference of <code>self</code> as the first argument to the parent's <code>__init__()</code>.</p>\n\n<p>4- to do the same without <code>super</code> we need to pass a reference to an instance explicitly to the parent's version of <code>__init__()</code>.</p>\n\n<pre><code>class A(object): \n def __init__(self, *a, **kw):\n # ...\n # you make some changes here\n # ...\n\n object.__init__(self, *a, **kw)\n</code></pre>\n\n<h2>Using <code>super</code> with a classmethod</h2>\n\n<pre><code>class A(object):\n @classmethod\n def alternate_constructor(cls, *a, **kw):\n print \"A.alternate_constructor called\"\n return cls(*a, **kw)\n\nclass B(A):\n @classmethod\n def alternate_constructor(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n print \"B.alternate_constructor called\"\n return super(B, cls).alternate_constructor(*a, **kw)\n</code></pre>\n\n<p>Explanation:</p>\n\n<p>1- A classmethod can be called from the class directly and takes as its first parameter a reference to the class. </p>\n\n<pre><code># calling directly from the class is fine,\n# a reference to the class is passed implicitly\na = A.alternate_constructor()\nb = B.alternate_constructor()\n</code></pre>\n\n<p>2- when calling <code>super()</code> within a classmethod to resolve to its parent's version of it, we want to pass the current child class as the first argument to indicate which parent's scope we're trying to resolve to, and the object of interest as the second argument to indicate which object we want to apply that scope to, which in general is a reference to the child class itself or one of its subclasses.</p>\n\n<pre><code>super(B, cls_or_subcls)\n</code></pre>\n\n<p>3- The call <code>super(B, cls)</code> resolves to the scope of <code>A</code> and applies it to <code>cls</code>. Since <code>alternate_constructor()</code> is a classmethod the call <code>super(B, cls).alternate_constructor(...)</code> will implicitly pass a reference of <code>cls</code> as the first argument to <code>A</code>'s version of <code>alternate_constructor()</code></p>\n\n<pre><code>super(B, cls).alternate_constructor()\n</code></pre>\n\n<p>4- to do the same without using <code>super()</code> you would need to get a reference to the <em>unbound</em> version of <code>A.alternate_constructor()</code> (i.e. the explicit version of the function). Simply doing this would not work:</p>\n\n<pre><code>class B(A):\n @classmethod\n def alternate_constructor(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n print \"B.alternate_constructor called\"\n return A.alternate_constructor(cls, *a, **kw)\n</code></pre>\n\n<p>The above would not work because the <code>A.alternate_constructor()</code> method takes an implicit reference to <code>A</code> as its first argument. The <code>cls</code> being passed here would be its second argument.</p>\n\n<pre><code>class B(A):\n @classmethod\n def alternate_constructor(cls, *a, **kw):\n # ...\n # whatever you want to specialize or override here\n # ...\n\n print \"B.alternate_constructor called\"\n # first we get a reference to the unbound \n # `A.alternate_constructor` function \n unbound_func = A.alternate_constructor.im_func\n # now we call it and pass our own `cls` as its first argument\n return unbound_func(cls, *a, **kw)\n</code></pre>\n"
},
{
"answer_id": 41384524,
"author": "skhalymon",
"author_id": 1322168,
"author_profile": "https://Stackoverflow.com/users/1322168",
"pm_score": 6,
"selected": false,
"text": "<p>I had played a bit with <code>super()</code>, and had recognized that we can change calling order.</p>\n\n<p>For example, we have next hierarchy structure:</p>\n\n<pre><code> A\n / \\\n B C\n \\ /\n D\n</code></pre>\n\n<p>In this case <a href=\"https://stackoverflow.com/a/1848647\">MRO</a> of D will be (only for Python 3):</p>\n\n<pre><code>In [26]: D.__mro__\nOut[26]: (__main__.D, __main__.B, __main__.C, __main__.A, object)\n</code></pre>\n\n<p>Let's create a class where <code>super()</code> calls after method execution.</p>\n\n<pre><code>In [23]: class A(object): # or with Python 3 can define class A:\n...: def __init__(self):\n...: print(\"I'm from A\")\n...: \n...: class B(A):\n...: def __init__(self):\n...: print(\"I'm from B\")\n...: super().__init__()\n...: \n...: class C(A):\n...: def __init__(self):\n...: print(\"I'm from C\")\n...: super().__init__()\n...: \n...: class D(B, C):\n...: def __init__(self):\n...: print(\"I'm from D\")\n...: super().__init__()\n...: d = D()\n...:\nI'm from D\nI'm from B\nI'm from C\nI'm from A\n\n A\n / ⇖\n B ⇒ C\n ⇖ /\n D\n</code></pre>\n\n<p>So we can see that resolution order is same as in MRO. But when we call <code>super()</code> in the beginning of the method:</p>\n\n<pre><code>In [21]: class A(object): # or class A:\n...: def __init__(self):\n...: print(\"I'm from A\")\n...: \n...: class B(A):\n...: def __init__(self):\n...: super().__init__() # or super(B, self).__init_()\n...: print(\"I'm from B\")\n...: \n...: class C(A):\n...: def __init__(self):\n...: super().__init__()\n...: print(\"I'm from C\")\n...: \n...: class D(B, C):\n...: def __init__(self):\n...: super().__init__()\n...: print(\"I'm from D\")\n...: d = D()\n...: \nI'm from A\nI'm from C\nI'm from B\nI'm from D\n</code></pre>\n\n<p>We have a different order it is reversed a order of the MRO tuple.</p>\n\n<pre><code> A\n / ⇘\n B ⇐ C\n ⇘ /\n D \n</code></pre>\n\n<p>For additional reading I would recommend next answers:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/27670178\">C3 linearization example with super (a large hierarchy)</a></li>\n<li><a href=\"https://stackoverflow.com/a/19950198/1322168\">Important behavior changes between old and new style classes</a></li>\n<li><a href=\"http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html\" rel=\"noreferrer\">The Inside Story on New-Style Classes</a></li>\n</ol>\n"
},
{
"answer_id": 51388706,
"author": "dorisxx",
"author_id": 10095572,
"author_profile": "https://Stackoverflow.com/users/10095572",
"pm_score": 0,
"selected": false,
"text": "<pre><code>class Child(SomeBaseClass):\n def __init__(self):\n SomeBaseClass.__init__(self)\n</code></pre>\n\n<p>This is fairly easy to understand.</p>\n\n<pre><code>class Child(SomeBaseClass):\n def __init__(self):\n super(Child, self).__init__()\n</code></pre>\n\n<p>Ok, what happens now if you use <code>super(Child,self)</code>?</p>\n\n<p>When a Child instance is created, its MRO(Method Resolution Order) is in the order of (Child, SomeBaseClass, object) based on the inheritance. (assume SomeBaseClass doesn't have other parents except for the default object)</p>\n\n<p>By passing <code>Child, self</code>, <code>super</code> searches in the MRO of the <code>self</code> instance, and return the proxy object next of Child, in this case it's SomeBaseClass, this object then invokes the <code>__init__</code> method of SomeBaseClass. In other word, if it's <code>super(SomeBaseClass,self)</code>, the proxy object that <code>super</code> returns would be <code>object</code> </p>\n\n<p>For multi inheritance, the MRO could contain many classes, so basically <code>super</code> lets you decide where you want to start searching in the MRO.</p>\n"
},
{
"answer_id": 56715064,
"author": "Aviad Rozenhek",
"author_id": 52917,
"author_profile": "https://Stackoverflow.com/users/52917",
"pm_score": 2,
"selected": false,
"text": "<p>some great answers here, but they do not tackle how to use <code>super()</code> in the case where different classes in the hierarchy have different signatures ... especially in the case of <code>__init__</code> </p>\n\n<p>to answer that part and to be able to effectively use <code>super()</code> i'd suggest reading my answer <a href=\"https://stackoverflow.com/questions/56714419/super-and-changing-the-signature-of-cooperative-methods/56714809#56714809\">super() and changing the signature of cooperative methods</a>. </p>\n\n<p>here's just the solution to this scenario:</p>\n\n<blockquote>\n <ol>\n <li>the top-level classes in your hierarchy must inherit from a custom class like <code>SuperObject</code>:</li>\n <li>if classes can take differing arguments, always pass all arguments you received on to the super function as keyword arguments, and, always accept <code>**kwargs</code>.</li>\n </ol>\n</blockquote>\n\n<pre class=\"lang-py prettyprint-override\"><code>class SuperObject: \n def __init__(self, **kwargs):\n print('SuperObject')\n mro = type(self).__mro__\n assert mro[-1] is object\n if mro[-2] is not SuperObject:\n raise TypeError(\n 'all top-level classes in this hierarchy must inherit from SuperObject',\n 'the last class in the MRO should be SuperObject',\n f'mro={[cls.__name__ for cls in mro]}'\n )\n\n # super().__init__ is guaranteed to be object.__init__ \n init = super().__init__\n init()\n</code></pre>\n\n<p>example usage:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class A(SuperObject):\n def __init__(self, **kwargs):\n print(\"A\")\n super(A, self).__init__(**kwargs)\n\nclass B(SuperObject):\n def __init__(self, **kwargs):\n print(\"B\")\n super(B, self).__init__(**kwargs)\n\nclass C(A):\n def __init__(self, age, **kwargs):\n print(\"C\",f\"age={age}\")\n super(C, self).__init__(age=age, **kwargs)\n\nclass D(B):\n def __init__(self, name, **kwargs):\n print(\"D\", f\"name={name}\")\n super(D, self).__init__(name=name, **kwargs)\n\nclass E(C,D):\n def __init__(self, name, age, *args, **kwargs):\n print( \"E\", f\"name={name}\", f\"age={age}\")\n super(E, self).__init__(name=name, age=age, *args, **kwargs)\n\nE(name='python', age=28)\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>E name=python age=28\nC age=28\nA\nD name=python\nB\nSuperObject\n</code></pre>\n"
},
{
"answer_id": 56741323,
"author": "run_the_race",
"author_id": 5506400,
"author_profile": "https://Stackoverflow.com/users/5506400",
"pm_score": 4,
"selected": false,
"text": "<p>Many great answers, but for visual learners:\nFirstly lets explore with arguments to super, and then without.\n<a href=\"https://i.stack.imgur.com/SvBDY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SvBDY.png\" alt=\"super inheritance tree example\"></a></p>\n\n<p>Imagine theres an instance <code>jack</code> created from the class <code>Jack</code>, who has the inheritance chain as shown in green in the picture. Calling:</p>\n\n<p><code>super(Jack, jack).method(...)</code> </p>\n\n<p>will use the MRO (Method Resolution Order) of <code>jack</code> (its inheritance tree in a certain order), and will start searching from <code>Jack</code>. Why can one provide a parent class? Well if we start searching from the instance <code>jack</code>, it would find the instance method, the whole point is to find its parents method.</p>\n\n<p>If one does not supply arguments to super, its like the first argument passed in is the class of <code>self</code>, and the second argument passed in is <code>self</code>. These are auto-calculated for you in Python3.</p>\n\n<p>However say we dont want to use <code>Jack</code>'s method, instead of passing in <code>Jack</code>, we could of passed in <code>Jen</code> to start searching upwards for the method from <code>Jen</code>.</p>\n\n<p>It searches one layer at a time (width not depth), e.g. if <code>Adam</code> and <code>Sue</code> both have the required method, the one from <code>Sue</code> will be found first.</p>\n\n<p>If <code>Cain</code> and <code>Sue</code> both had the required method, <code>Cain</code>'s method would be called first.\nThis corresponds in code to:</p>\n\n<pre><code>Class Jen(Cain, Sue):\n</code></pre>\n\n<p>MRO is from left to right.</p>\n"
},
{
"answer_id": 61852947,
"author": "tsh",
"author_id": 2045384,
"author_profile": "https://Stackoverflow.com/users/2045384",
"pm_score": 1,
"selected": false,
"text": "<p>Consider the following code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class X():\n def __init__(self):\n print(\"X\")\n\nclass Y(X):\n def __init__(self):\n # X.__init__(self)\n super(Y, self).__init__()\n print(\"Y\")\n\nclass P(X):\n def __init__(self):\n super(P, self).__init__()\n print(\"P\")\n\nclass Q(Y, P):\n def __init__(self):\n super(Q, self).__init__()\n print(\"Q\")\n\nQ()\n</code></pre>\n\n<p>If change constructor of <code>Y</code> to <code>X.__init__</code>, you will get:</p>\n\n<pre><code>X\nY\nQ\n</code></pre>\n\n<p>But using <code>super(Y, self).__init__()</code>, you will get:</p>\n\n<pre><code>X\nP\nY\nQ\n</code></pre>\n\n<p>And <code>P</code> or <code>Q</code> may even be involved from another file which you don't know when you writing <code>X</code> and <code>Y</code>. So, basically, you won't know what <code>super(Child, self)</code> will reference to when you are writing <code>class Y(X)</code>, even the signature of Y is as simple as <code>Y(X)</code>. That's why super could be a better choice.</p>\n"
},
{
"answer_id": 63194428,
"author": "cdude",
"author_id": 9554268,
"author_profile": "https://Stackoverflow.com/users/9554268",
"pm_score": 2,
"selected": false,
"text": "<p>In the case of multiple inheritance, you normally want to call the initializers of both parents, not just the first. Instead of always using the base class, super() finds the class that is next in Method Resolution Order (MRO), and returns the current object as an instance of that class. For example:</p>\n<pre><code>class Base(object):\n def __init__(self):\n print("initializing Base")\n\nclass ChildA(Base):\n def __init__(self):\n print("initializing ChildA")\n Base.__init__(self)\n\nclass ChildB(Base):\n def __init__(self):\n print("initializing ChildB")\n super().__init__()\n\nclass Grandchild(ChildA, ChildB):\n def __init__(self):\n print("initializing Grandchild")\n super().__init__()\n \nGrandchild()\n</code></pre>\n<p>results in</p>\n<pre><code>initializing Grandchild\ninitializing ChildA\ninitializing Base\n</code></pre>\n<p>Replacing <code>Base.__init__(self)</code> with <code>super().__init__()</code> results in</p>\n<pre><code>initializing Grandchild\ninitializing ChildA\ninitializing ChildB\ninitializing Base\n</code></pre>\n<p>as desired.</p>\n"
},
{
"answer_id": 65383999,
"author": "Raymond Hettinger",
"author_id": 424499,
"author_profile": "https://Stackoverflow.com/users/424499",
"pm_score": 4,
"selected": false,
"text": "<h2>Super() in a nutshell</h2>\n<ul>\n<li>Every Python instance has a class that created it.</li>\n<li>Every class in Python has a chain of ancestor classes.</li>\n<li>A method using super() delegates work to the next ancestor in the chain for the instance's class.</li>\n</ul>\n<h2>Example</h2>\n<p>This small example covers all the interesting cases:</p>\n<pre><code>class A:\n def m(self):\n print('A')\n\nclass B(A):\n def m(self):\n print('B start')\n super().m()\n print('B end')\n \nclass C(A):\n def m(self):\n print('C start')\n super().m()\n print('C end')\n\nclass D(B, C):\n def m(self):\n print('D start')\n super().m()\n print('D end')\n</code></pre>\n<p>The exact order of calls is determined by the instance the method is called from:</p>\n<pre><code>>>> a = A()\n>>> b = B()\n>>> c = C()\n>>> d = D()\n</code></pre>\n<p>For instance <em>a</em>, there is no super call:</p>\n<pre><code>>>> a.m()\nA\n</code></pre>\n<p>For instance <em>b</em>, the ancestor chain is <code>B -> A -> object</code>:</p>\n<pre><code>>>> type(b).__mro__ \n(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)\n\n>>> b.m()\nB start\nA\nB end\n</code></pre>\n<p>For instance <em>c</em>, the ancestor chain is <code>C -> A -> object</code>:</p>\n<pre><code>>>> type(c).__mro__ \n(<class '__main__.C'>, <class '__main__.A'>, <class 'object'>)\n\n>>> c.m()\nC start\nA\nC end\n</code></pre>\n<p>For instance <em>d</em>, the ancestor chain is more interesting <code>D -> B -> C -> A -> object</code> (<em><strong>mro</strong></em> stands for method resolution order) :</p>\n<pre><code>>>> type(d).__mro__\n(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)\n\n>>> d.m()\nD start\nB start\nC start\nA\nC end\nB end\nD end\n</code></pre>\n<h2>More information</h2>\n<p>Having answered the question of "What does super do in Python?", the next question is how to use it effectively. See this <a href=\"https://rhettinger.wordpress.com/2011/05/26/super-considered-super/\" rel=\"nofollow noreferrer\">step-by-step tutorial</a> or this <a href=\"https://www.youtube.com/watch?v=EiOglTERPEo&t=847s\" rel=\"nofollow noreferrer\">45 minute video</a>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25785/"
] |
What's the difference between:
```
class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
```
and:
```
class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
```
I've seen `super` being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.
|
The benefits of `super()` in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
However, it's almost impossible to use multiple-inheritance without `super()`. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended `Child` and a mixin, their code would not work properly.
|
222,895 |
<p>I like LINQ to SQL, but it seems like the classes it generates are tightly coupled to the database they are stored in, which seems like a Bad Thing. </p>
<p>For example, using ye olde Northwind database, if I create the dbml with the Products table, a <code>Product</code> class is generated. I can use this class in any other tier, which is all well and good, but if I decide I'd rather use plain old ADO.NET (or switch databases), I'll have to recreate the <code>Product</code> class, along with every other "model."</p>
<p>Is there a way around this? Or to create your object models separately, and then have the tables mapped to them? I've played around with the various mapping classes provided, but haven't found a satisfactory answer yet.</p>
|
[
{
"answer_id": 222919,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 1,
"selected": false,
"text": "<p>Scott Hanselman did a screen talking about asp.net DynamicData where he used Linq To Sql classes. Although he wasn't addressing the particular issue I think the general concept would still work. His approach was to create a separate <strong>partial</strong> class that had the same name as the class, <code>Product</code> in your case, that was generated by the dbml. Then you should always have a <code>Product</code> class that exists outside of what LINQ generates and just \"extends\" what it does.</p>\n"
},
{
"answer_id": 223003,
"author": "Seth Petry-Johnson",
"author_id": 23632,
"author_profile": "https://Stackoverflow.com/users/23632",
"pm_score": 2,
"selected": false,
"text": "<p>My team fought with this issue recently. I really wanted to maintain \"persistence ignorance\", meaning that domain objects could be created as plain old C# objects, without being forced to inherit from a certain base class or clutter up the class with a bunch of attributes. Like you said, we wanted to be able to modify the persistence layer independently of the business model.</p>\n\n<p>In the end, we decided that LINQ isn't the way to go if you want persistence ignorance. We end up writing way too much mapping code to convert between the LINQ layer and our business layer. When we started writing a bunch of reflection-based code to try and do these mappings automatically we realized we were sliding down the rabbit hole, with little to show for it.</p>\n\n<p>If persistence ignorance is important to you, you might be better served with a full-fledged ORM like NHIbernate.</p>\n"
},
{
"answer_id": 223019,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 2,
"selected": false,
"text": "<p>Linq to SQL (or EF) is <em>not</em> about persistence-ignorance. It is about an object view of data.</p>\n\n<p>NHibernate is the persistence-ignorance ORM you may be looking for.</p>\n"
},
{
"answer_id": 223792,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 0,
"selected": false,
"text": "<p>Just copy the generated code into your own classes and switch off the code generation. The magic is in the attributes not anything else.</p>\n\n<p>Alternatively you can write your own plain CLR objects without the attributes and use an external XML mapping file to describe the relationship between the objects and the database. More information can be found in the LINQ to SQL documentation on MSDN.</p>\n"
},
{
"answer_id": 223825,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 2,
"selected": false,
"text": "<p>I've recently achieved this by creating the POCOs myself and manually creating a XML mapping file for the database. It requires a bit of manual work but it gives the desired effect.</p>\n\n<p>Here's a <a href=\"http://www.sidarok.com/web/blog/content/2008/10/14/achieving-poco-s-in-linq-to-sql.html\" rel=\"nofollow noreferrer\">blog post I found useful</a> to get you started. </p>\n"
},
{
"answer_id": 229905,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 4,
"selected": true,
"text": "<p>All these answers and no links! Maybe I can help:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic3\" rel=\"nofollow noreferrer\">The attributes thing that damieng mentioned</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb546176.aspx\" rel=\"nofollow noreferrer\">The partial class thing that Marcus King mentioned</a></p>\n\n<p>I have languished through this difficulty a couple of times, what I ended up doing on my last project was using interfaces as the contract that's shared between all of the different projects in the solution, and having the partial classes implement it.</p>\n\n<pre><code>[Table(Name=\"Products\")]\npublic partial class Product: IProduct { }\n</code></pre>\n\n<p>And yes, unfortunately it took some reflection magic to make it work for the POCO implementation.</p>\n\n<p>In the end, if you are truly concerned about it, I'd go with NHibernate (I don't really like it either), which does exactly what Garry Shulter seems to be describing.</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 364138,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Oh hey, I think I found a solution to this while watching <a href=\"http://www.asp.net/learn/mvc-videos/#MVCStorefrontStarterKit\" rel=\"nofollow noreferrer\">Rob Conery's screencasts on ASP.NET MVC</a>. The trick is to <code>select</code> into an object in your LINQ to SQL query.</p>\n\n<pre><code>public IQueryable<LinqExample.Core.Person> GetAll() {\n var people = from pe in this.db.Persons\n select new Person {\n Id = pe.id,\n FirstName = pe.fname,\n LastName = pe.lname,\n Reports = this.GetReports(pe.id)\n };\n return people;\n}\n</code></pre>\n\n<p>This let's you define a <code>Person</code> class elsewhere in your code. <a href=\"http://www.sogeti-phoenix.com/Blogs/post/2008/12/LINQ-To-SQL-and-Tight-Coupling-Part-4.aspx\" rel=\"nofollow noreferrer\">I blogged about it</a> more in depth. </p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
I like LINQ to SQL, but it seems like the classes it generates are tightly coupled to the database they are stored in, which seems like a Bad Thing.
For example, using ye olde Northwind database, if I create the dbml with the Products table, a `Product` class is generated. I can use this class in any other tier, which is all well and good, but if I decide I'd rather use plain old ADO.NET (or switch databases), I'll have to recreate the `Product` class, along with every other "model."
Is there a way around this? Or to create your object models separately, and then have the tables mapped to them? I've played around with the various mapping classes provided, but haven't found a satisfactory answer yet.
|
All these answers and no links! Maybe I can help:
[The attributes thing that damieng mentioned](http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic3)
[The partial class thing that Marcus King mentioned](http://msdn.microsoft.com/en-us/library/bb546176.aspx)
I have languished through this difficulty a couple of times, what I ended up doing on my last project was using interfaces as the contract that's shared between all of the different projects in the solution, and having the partial classes implement it.
```
[Table(Name="Products")]
public partial class Product: IProduct { }
```
And yes, unfortunately it took some reflection magic to make it work for the POCO implementation.
In the end, if you are truly concerned about it, I'd go with NHibernate (I don't really like it either), which does exactly what Garry Shulter seems to be describing.
Hope that helps!
|
222,897 |
<p>Is it possible to extend LINQ-to-SQL entity-classes with constructor-methods and in the same go; make that entity-class inherit from it's data-context class?--In essence converting the entity-class into a business object.</p>
<p>This is the pattern I am currently using:</p>
<pre><code>namespace Xxx
{
public class User : Xxx.DataContext
{
public enum SiteAccessRights
{
NotRegistered = 0,
Registered = 1,
Administrator = 3
}
private Xxx.Entities.User _user;
public Int32 ID
{
get
{
return this._user.UsersID;
}
}
public Xxx.User.SiteAccessRights AccessRights
{
get
{
return (Xxx.User.SiteAccessRights)this._user.UsersAccessRights;
}
set
{
this._user.UsersAccessRights = (Int32)value;
}
}
public String Alias
{
get
{
return this._user.UsersAlias;
}
set
{
this._user.UsersAlias = value;
}
}
public User(Int32 userID)
{
var user = (from u in base.Users
where u.UsersID == userID
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User();
base.Users.InsertOnSubmit(this._user);
}
}
public User(Xxx.User.SiteAccessRights accessRights, String alias)
{
var user = (from u in base.Users
where u.UsersAccessRights == (Int32)accessRights && u.UsersAlias == alias
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User
{
UsersAccessRights = (Int32)accessRights,
UsersAlias = alias
};
base.Users.InsertOnSubmit(this._user);
}
}
public void DeleteOnSubmit()
{
base.Users.DeleteOnSubmit(this._user);
}
}
}
</code></pre>
<p><strong>Update:</strong></p>
<p>Notice that I have two constructor-methods in my <code>User</code> class. I'd like to transfer those to the <code>User</code> entity-class <em>and</em> extend the <code>User</code> entity-class on it's data-context class, so that the data-context is available to the entity-class on "new-up".</p>
<p>Hope this makes sense.</p>
|
[
{
"answer_id": 222935,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": true,
"text": "<p>It doesn't seem to make sense to make an entity a type of DataContext. It doesn't need to be a DataContext in order to be considered a business object, nor do you necessarily need to create a type that contains the original entity. It might be better to just extend the entity class and contain a reference to a DataContext using composition:</p>\n\n<pre><code>namespace Xxx.Entities\n{\n public partial class User : IDisposable\n { DataContext ctx;\n\n public static GetUserByID(int userID)\n { var ctx = new DataContext();\n var user = ctx.Users.FirstOrDefault(u=>u.UsersID == userID);\n\n if (user == null)\n {\n user = new User();\n ctx.Users.InsertOnSubmit(user);\n }\n\n user.ctx = ctx;\n return user; \n } \n\n public void Dispose() { if (ctx != null) ctx.Dispose(); }\n }\n}\n</code></pre>\n\n<p>If you just want the property names to be different than the database column names, do that in the mapping file.</p>\n"
},
{
"answer_id": 222984,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>Rick Strahl has a number of really good articles that address what I think you are looking for. Check out his list of <a href=\"http://www.west-wind.com/Weblog/ShowPosts.aspx?Category=LINQ\" rel=\"nofollow noreferrer\">Linq Articles Here</a></p>\n"
},
{
"answer_id": 223781,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 1,
"selected": false,
"text": "<p>Inheriting an entity from a data context is a bad idea. They are two discrete objects and are designed to operate that way. Doing this will cause all sorts of issues least of all problems with trying to submit a bunch of related changes together at the same time - going through multiple data contexts will cause this to fail as each tries to work independently.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
Is it possible to extend LINQ-to-SQL entity-classes with constructor-methods and in the same go; make that entity-class inherit from it's data-context class?--In essence converting the entity-class into a business object.
This is the pattern I am currently using:
```
namespace Xxx
{
public class User : Xxx.DataContext
{
public enum SiteAccessRights
{
NotRegistered = 0,
Registered = 1,
Administrator = 3
}
private Xxx.Entities.User _user;
public Int32 ID
{
get
{
return this._user.UsersID;
}
}
public Xxx.User.SiteAccessRights AccessRights
{
get
{
return (Xxx.User.SiteAccessRights)this._user.UsersAccessRights;
}
set
{
this._user.UsersAccessRights = (Int32)value;
}
}
public String Alias
{
get
{
return this._user.UsersAlias;
}
set
{
this._user.UsersAlias = value;
}
}
public User(Int32 userID)
{
var user = (from u in base.Users
where u.UsersID == userID
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User();
base.Users.InsertOnSubmit(this._user);
}
}
public User(Xxx.User.SiteAccessRights accessRights, String alias)
{
var user = (from u in base.Users
where u.UsersAccessRights == (Int32)accessRights && u.UsersAlias == alias
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User
{
UsersAccessRights = (Int32)accessRights,
UsersAlias = alias
};
base.Users.InsertOnSubmit(this._user);
}
}
public void DeleteOnSubmit()
{
base.Users.DeleteOnSubmit(this._user);
}
}
}
```
**Update:**
Notice that I have two constructor-methods in my `User` class. I'd like to transfer those to the `User` entity-class *and* extend the `User` entity-class on it's data-context class, so that the data-context is available to the entity-class on "new-up".
Hope this makes sense.
|
It doesn't seem to make sense to make an entity a type of DataContext. It doesn't need to be a DataContext in order to be considered a business object, nor do you necessarily need to create a type that contains the original entity. It might be better to just extend the entity class and contain a reference to a DataContext using composition:
```
namespace Xxx.Entities
{
public partial class User : IDisposable
{ DataContext ctx;
public static GetUserByID(int userID)
{ var ctx = new DataContext();
var user = ctx.Users.FirstOrDefault(u=>u.UsersID == userID);
if (user == null)
{
user = new User();
ctx.Users.InsertOnSubmit(user);
}
user.ctx = ctx;
return user;
}
public void Dispose() { if (ctx != null) ctx.Dispose(); }
}
}
```
If you just want the property names to be different than the database column names, do that in the mapping file.
|
222,925 |
<p>In PHP, I want to read a file into a variable and process the PHP in the file at the same time without using output buffering. Is this possible?</p>
<p>Essentially I want to be able to accomplish this without using <code>ob_start()</code>:</p>
<pre><code><?php
ob_start();
include 'myfile.php';
$xhtml = ob_get_clean();
?>
</code></pre>
<p>Is this possible in PHP?</p>
<p>Update: I want to do some more complex things within an output callback (where output buffering is not allowed).</p>
|
[
{
"answer_id": 222944,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": 3,
"selected": false,
"text": "<p>From what I can tell in the PHP documentation, no. Why do you want to avoid output buffering?</p>\n\n<p>The only way to get around this would be hacky methods involving either invoking the command line php client or doing a curl request based on what's available and what the particular requirements are.</p>\n"
},
{
"answer_id": 222949,
"author": "Joeri Sebrechts",
"author_id": 20980,
"author_profile": "https://Stackoverflow.com/users/20980",
"pm_score": 0,
"selected": false,
"text": "<p>Do a curl request to the php page, essentially pretending to be the browser.</p>\n"
},
{
"answer_id": 223005,
"author": "Robert K",
"author_id": 24950,
"author_profile": "https://Stackoverflow.com/users/24950",
"pm_score": 0,
"selected": false,
"text": "<p>What you could do, if the file is local, is load the script into a variable as a string, then run eval on the string. Then you can do all your other stuff afterwards. Otherwise, you have to use output buffering.</p>\n"
},
{
"answer_id": 223081,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Joeri Sebrechts is correct.\nAn equivalent and slightly easier method is available if the PHP script is HTTP accessible:</p>\n\n<pre><code>$data = file_get_contents('http://google.com/');\n</code></pre>\n\n<p>It should be noted that using output buffering would be easier on resources.</p>\n"
},
{
"answer_id": 223845,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$fileData = file_get_contents('fileOnDisk.php');\n$results = eval($fileData);\n</code></pre>\n\n<p>But check the documentation on eval, because you actually have to have the file you are calling return its results rather than just echo them:</p>\n\n<p><a href=\"http://us2.php.net/eval\" rel=\"nofollow noreferrer\">http://us2.php.net/eval</a></p>\n"
},
{
"answer_id": 223865,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 2,
"selected": false,
"text": "<p>After reading everybody's suggestions, reading a bunch of documentation, and playing around with some things, I came up with this:</p>\n\n<pre><code><?php\n$file = file_get_contents('/path/to/file.php');\n$xhtml = eval(\"?>$file\");\n?>\n</code></pre>\n\n<p>It's as close as I could get but it unfortunately doesn't work. The key to this is to include the closing PHP bit (<code>?></code>) before the contents of the file. This will take the <code>eval()</code> out of PHP-evaluation mode and will treat the contents of the file starting as non-PHP code. Then if there are PHP code blocks within the file, those will be evaluated as PHP. The bummer is that it doesn't save the eval'd content in the variable, it just outputs it to the page.</p>\n\n<p>Thanks for the help everybody!</p>\n"
},
{
"answer_id": 229193,
"author": "Wes Mason",
"author_id": 2228202,
"author_profile": "https://Stackoverflow.com/users/2228202",
"pm_score": 6,
"selected": true,
"text": "<p>A little known feature of PHP is being able to treat an included/required file like a function call, with a return value.</p>\n\n<p>For example:</p>\n\n<pre><code>// myinclude.php\n$value = 'foo';\n$otherValue = 'bar';\nreturn $value . $otherValue;\n\n\n// index.php\n$output = include './myinclude.php';\necho $output;\n// Will echo foobar\n</code></pre>\n"
},
{
"answer_id": 26656953,
"author": "David Newcomb",
"author_id": 52070,
"author_profile": "https://Stackoverflow.com/users/52070",
"pm_score": -1,
"selected": false,
"text": "<p>Hack Alert! You could do the evaluation of the PHP yourself with a bit of hackery using <code>preg_replace_callback</code> to search and replace the PHP blocks.</p>\n\n<pre><code>function evalCallback($matches)\n{\n // [0] = <?php return returnOrEcho(\"hi1\");?>\n // [1] = <?php\n // [2] = return returnOrEcho(\"hi1\");\n // [3] = ?>\n return eval($matches[2]);\n}\n\nfunction evalPhp($file)\n{\n // Load contents\n $contents = file_get_contents($file);\n // Add returns\n $content_with_returns = str_replace(\n \"returnOrEcho\"\n ,\"return returnOrEcho\"\n ,$contents);\n // eval\n $modified_content = preg_replace_callback(\n array(\"|(\\<\\?php)(.*)(\\?\\>)|\"\n ,\"evalCallback\"\n ,$content_with_returns);\n return $modified_content;\n}\n</code></pre>\n\n<p>You would have to modify the PHP file you are including to use a <code>returnOrEcho</code> function so that it can be overloaded for this case and the normal case. In this case you want to <code>return</code> so that it will be picked up by the <code>eval</code> in the way you want, but the normal case is to <code>echo</code> without a return.</p>\n\n<p>So for this case you would define:</p>\n\n<pre><code>function returnOrEcho($str)\n{\n return $str;\n}\n</code></pre>\n\n<p>and for the normal case you would define:</p>\n\n<pre><code>function returnOrEcho($str)\n{\n echo $str;\n}\n</code></pre>\n\n<p>In your included PHP file (or view file) you would have something like this:</p>\n\n<pre><code><?php returnOrEcho(\"hi1\");?>\n<?php returnOrEcho(\"hi3\".\"oo\");?>\n<?php returnOrEcho(6*7);?>\n</code></pre>\n\n<p>I couldn't get <code>preg_replace_callback</code> inline callback working so I used a separate function, but there is an example of how to do it: <a href=\"https://stackoverflow.com/questions/11164563/preg-replace-callback-calback-inside-current-object-instance\">preg_replace_callback() - Calback inside current object instance</a>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18986/"
] |
In PHP, I want to read a file into a variable and process the PHP in the file at the same time without using output buffering. Is this possible?
Essentially I want to be able to accomplish this without using `ob_start()`:
```
<?php
ob_start();
include 'myfile.php';
$xhtml = ob_get_clean();
?>
```
Is this possible in PHP?
Update: I want to do some more complex things within an output callback (where output buffering is not allowed).
|
A little known feature of PHP is being able to treat an included/required file like a function call, with a return value.
For example:
```
// myinclude.php
$value = 'foo';
$otherValue = 'bar';
return $value . $otherValue;
// index.php
$output = include './myinclude.php';
echo $output;
// Will echo foobar
```
|
222,957 |
<p>Before I get into the details of this problem, I'd like to make the situation clear. Our web analytics company works as a consultant for large sites, and (other than adding a single SCRIPT tag) we have no control over the pages themselves.</p>
<p>Our existing script installs handlers using "old" way (a fancy version of element.onclick = blah; that also executes the original handler) which is completely unaware of "new" (addEventListener or attachEvent) handlers on the page. We'd like to fix this to make our script able to run on more sites without requiring as much custom development.</p>
<p>The initial thought here was to have our own script use addEventListener/attachEvent, but this presents a problem: of the client's site sets a handler using the "old" way, it would wipe out the handler we installed the "new" way. Quick and dirty testing shows this happens in both IE7 and FF3, although I didn't test the whole range of browsers. There's also a risk that if we use the "new" way after the page's event handlers are already set, we could erase their handlers.</p>
<p>So my question is: what safe technique can I use to add an event handler in Javascript using addEventListener/attachEvent that works regardless of how other event handlers on the page are installed?</p>
<p>Please remember: we have no way of modifying the site that our script is installed on. (I have to emphasize that because the default answer to questions like this is always, "just rewrite the page to do everything the same way.")</p>
|
[
{
"answer_id": 222966,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 1,
"selected": false,
"text": "<p>addEventListener/attachEvent is safe in a sense you ask. They add a new event handler to a Node without altering any handlers previously added to it (even once assigned through a property onxxx). For a company that bring some to a foreign page using addEventListener/attachEvent must be the only practice. Assigning onxxx handler via properties indeed would break hosting pages scipts (that have been previously assigned the same way)</p>\n"
},
{
"answer_id": 222990,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 4,
"selected": true,
"text": "<p>Can you try your quick-and-dirty testing again? This doesn't happen for me in FF3.</p>\n\n<pre><code>elem.onclick = function() { alert(\"foo\"); };\nelem.addEventListener(\"click\", function() { alert(\"bar\"); }, false);\n</code></pre>\n\n<p>Both handlers fire for me when I click on the element.</p>\n\n<p>I'm guessing you forgot the final boolean argument in <code>addEventListener</code> (whether to use the capture phase). I'm also guessing you forgot that IE's <code>attachEvent</code> needs <code>onclick</code>, not <code>click</code>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30050/"
] |
Before I get into the details of this problem, I'd like to make the situation clear. Our web analytics company works as a consultant for large sites, and (other than adding a single SCRIPT tag) we have no control over the pages themselves.
Our existing script installs handlers using "old" way (a fancy version of element.onclick = blah; that also executes the original handler) which is completely unaware of "new" (addEventListener or attachEvent) handlers on the page. We'd like to fix this to make our script able to run on more sites without requiring as much custom development.
The initial thought here was to have our own script use addEventListener/attachEvent, but this presents a problem: of the client's site sets a handler using the "old" way, it would wipe out the handler we installed the "new" way. Quick and dirty testing shows this happens in both IE7 and FF3, although I didn't test the whole range of browsers. There's also a risk that if we use the "new" way after the page's event handlers are already set, we could erase their handlers.
So my question is: what safe technique can I use to add an event handler in Javascript using addEventListener/attachEvent that works regardless of how other event handlers on the page are installed?
Please remember: we have no way of modifying the site that our script is installed on. (I have to emphasize that because the default answer to questions like this is always, "just rewrite the page to do everything the same way.")
|
Can you try your quick-and-dirty testing again? This doesn't happen for me in FF3.
```
elem.onclick = function() { alert("foo"); };
elem.addEventListener("click", function() { alert("bar"); }, false);
```
Both handlers fire for me when I click on the element.
I'm guessing you forgot the final boolean argument in `addEventListener` (whether to use the capture phase). I'm also guessing you forgot that IE's `attachEvent` needs `onclick`, not `click`.
|
222,981 |
<p>I cannot correctly position the div <code>form</code> in my layout.</p>
<p>By looking at my div placement and css below, does anyone have an idea what I could be doing wrong?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#floorplans {
float: left;
height: 165px;
width: 203px;
border-right: 1px solid #FFFFFF;
border-bottom: 1px solid #FFFFFF;
position: relative;
background: #FFFFFF url(https://lorempixel.com/320/170/) no-repeat;
padding-top: 14px;
padding-left: 20px;
display: block;
color: #000000;
line-height: 1.5em;
padding-right: 10px;
}
#development {
float: left;
height: 165px;
width: 204px;
border-right: 1px solid #FFFFFF;
border-bottom: 1px solid #FFFFFF;
position: relative;
background: #FFFFFF url(https://lorempixel.com/204/165/) no-repeat;
padding-top: 14px;
padding-left: 20px;
display: block;
color: #000000;
line-height: 1.5em;
padding-right: 10px;
}
#projects {
background: #FFFFFF url(https://lorempixel.com/153/127/) no-repeat;
height: 127px;
width: 153px;
text-align: left;
padding-left: 300px;
color: #333333;
padding-top: 25px;
display: block;
float: left;
position: relative;
line-height: 1.5em;
font-size: 10px;
padding-right: 15px;
clear: left;
}
#form {
background: #990000 url(https://lorempixel.com/450/309/) no-repeat;
float: left;
height: 309px;
width: 450px;
position: relative;
padding-top: 20px;
padding-left: 30px;
padding-right: 30px;
color: #FFFFFF;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<div id="logo"></div>
<div id="topnav"></div>
<div id="nav">
<ul>
<li><a href="#">link</a></li>
<li><a href="#">link2</a></li>
<li><a href="#">link3</a></li>
<li id="last"><a href="#">link4</a></li>
</ul>
</div>
<div id="gallery"></div>
<div id="floorplans"></div>
<div id="development"></div>
<div id="projects"></div>
<div id="form">
<div>
</div>
<div id="footer"></div>
</div></code></pre>
</div>
</div>
</p>
<p>You'll notice the div <code>form</code> is dropping down. What should I do to get things to line up? Should I rework the placement of the divs?</p>
|
[
{
"answer_id": 222994,
"author": "Dave Rutledge",
"author_id": 2486915,
"author_profile": "https://Stackoverflow.com/users/2486915",
"pm_score": 1,
"selected": false,
"text": "<p>Because you have two blocks (FLOORPLANS and DEVELOPMENT INFO) each with a border, they're now too wide to sit next to the form block. Test this by removing one or both borders and seeing if the form then pops back up there.</p>\n\n<p>Note, negative margin often has issues in IE6, be sure and check any solution against that.</p>\n"
},
{
"answer_id": 223015,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": true,
"text": "<p>The form <code>div</code>'s top is in line with the top of the <code>div</code> that precedes it. The <code>clear:left;</code> on <code>#projects</code> moves <code>#projects</code> to the next line (good), along with the following content (bad). Try a negative top margin, or consider restructuring your HTML to put <code>#form</code> before <code>#projects</code>.</p>\n\n<p>Adding the following should work:</p>\n\n<pre><code>#form {\n margin-top:-180px;\n}\n#projects {\n border-right: 1px solid #FFFFFF;\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30043/"
] |
I cannot correctly position the div `form` in my layout.
By looking at my div placement and css below, does anyone have an idea what I could be doing wrong?
```css
#floorplans {
float: left;
height: 165px;
width: 203px;
border-right: 1px solid #FFFFFF;
border-bottom: 1px solid #FFFFFF;
position: relative;
background: #FFFFFF url(https://lorempixel.com/320/170/) no-repeat;
padding-top: 14px;
padding-left: 20px;
display: block;
color: #000000;
line-height: 1.5em;
padding-right: 10px;
}
#development {
float: left;
height: 165px;
width: 204px;
border-right: 1px solid #FFFFFF;
border-bottom: 1px solid #FFFFFF;
position: relative;
background: #FFFFFF url(https://lorempixel.com/204/165/) no-repeat;
padding-top: 14px;
padding-left: 20px;
display: block;
color: #000000;
line-height: 1.5em;
padding-right: 10px;
}
#projects {
background: #FFFFFF url(https://lorempixel.com/153/127/) no-repeat;
height: 127px;
width: 153px;
text-align: left;
padding-left: 300px;
color: #333333;
padding-top: 25px;
display: block;
float: left;
position: relative;
line-height: 1.5em;
font-size: 10px;
padding-right: 15px;
clear: left;
}
#form {
background: #990000 url(https://lorempixel.com/450/309/) no-repeat;
float: left;
height: 309px;
width: 450px;
position: relative;
padding-top: 20px;
padding-left: 30px;
padding-right: 30px;
color: #FFFFFF;
}
```
```html
<div id="wrapper">
<div id="logo"></div>
<div id="topnav"></div>
<div id="nav">
<ul>
<li><a href="#">link</a></li>
<li><a href="#">link2</a></li>
<li><a href="#">link3</a></li>
<li id="last"><a href="#">link4</a></li>
</ul>
</div>
<div id="gallery"></div>
<div id="floorplans"></div>
<div id="development"></div>
<div id="projects"></div>
<div id="form">
<div>
</div>
<div id="footer"></div>
</div>
```
You'll notice the div `form` is dropping down. What should I do to get things to line up? Should I rework the placement of the divs?
|
The form `div`'s top is in line with the top of the `div` that precedes it. The `clear:left;` on `#projects` moves `#projects` to the next line (good), along with the following content (bad). Try a negative top margin, or consider restructuring your HTML to put `#form` before `#projects`.
Adding the following should work:
```
#form {
margin-top:-180px;
}
#projects {
border-right: 1px solid #FFFFFF;
}
```
|
222,988 |
<p>My code is in c# asp.net 3.5</p>
<p>In the following code the "Msg" has many words with spaces and characters (eg:Failed to prepare Sync Favorites : Directory does not exist: \STL-FNP-02\ryounes$\Sync\Favorites). This "Msg" is pulled from database to a gridview. I am not able to create hyperlink for this "Msg" in gridview. Since it has spaces it is not creating hyperlink.</p>
<p>I need to create hyperlink for this "Msg" and latter use it in linq query. </p>
<p>I think one shud either use eval or url encoder. I am not sure how to do it. Can anyone say how to go about it?</p>
<pre><code> <asp:HyperLinkField DataTextField="Msg" HeaderText="Msg" DataNavigateUrlFields="Msg"
DataNavigateUrlFormatString="Sync.aspx?Msg={0}" />
</code></pre>
|
[
{
"answer_id": 223001,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>It doesn't create the link as it is not a valid URL, rather than using a hyperlink column most likely you are going to need to migrate to a template and manage it yourself, or at minimum do some formatting on it.</p>\n\n<p>I would be cautious regardless of making that a hyperlink, where is it going to go anway?</p>\n\n<p>If there is a specific place based on message that you should be going, calculate that BEFORE you bind to the grid...</p>\n"
},
{
"answer_id": 223012,
"author": "Rafe",
"author_id": 27497,
"author_profile": "https://Stackoverflow.com/users/27497",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like you need to url-encode the string so that the words and spaces can exist as one variable in the query string. Take a look at this function: <a href=\"http://msdn.microsoft.com/en-us/library/zttxte6w.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/zttxte6w.aspx</a></p>\n"
},
{
"answer_id": 223062,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 3,
"selected": true,
"text": "<p>The easiest way to get around it is to use something like </p>\n\n<pre><code><asp:TemplateField HeaderText=\"Msg\"> \n <asp:HyperLink runat=\"server\" Text='<%# HttpUtility.UrlEncode(Eval(\"Msg\")) %>' NavigateUrl='<%#Eval(\"Msg\")%>' />\n</asp:TemplateField>\n</code></pre>\n\n<p>Not 100% certain that the syntax is correct but you get the general idea</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
My code is in c# asp.net 3.5
In the following code the "Msg" has many words with spaces and characters (eg:Failed to prepare Sync Favorites : Directory does not exist: \STL-FNP-02\ryounes$\Sync\Favorites). This "Msg" is pulled from database to a gridview. I am not able to create hyperlink for this "Msg" in gridview. Since it has spaces it is not creating hyperlink.
I need to create hyperlink for this "Msg" and latter use it in linq query.
I think one shud either use eval or url encoder. I am not sure how to do it. Can anyone say how to go about it?
```
<asp:HyperLinkField DataTextField="Msg" HeaderText="Msg" DataNavigateUrlFields="Msg"
DataNavigateUrlFormatString="Sync.aspx?Msg={0}" />
```
|
The easiest way to get around it is to use something like
```
<asp:TemplateField HeaderText="Msg">
<asp:HyperLink runat="server" Text='<%# HttpUtility.UrlEncode(Eval("Msg")) %>' NavigateUrl='<%#Eval("Msg")%>' />
</asp:TemplateField>
```
Not 100% certain that the syntax is correct but you get the general idea
|
222,996 |
<p>I have the following class which uses BinaryReader internally and implements IDisposable.</p>
<pre>
class DisposableClass : IDisposable
{
private BinaryReader reader;
public DisposableClass(Stream stream)
{
reader = new BinaryReader(stream);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)reader).Dispose();
// reader.Dispose();// this won't compile
}
}
public void Dispose()
{
this.Dispose(true);
}
}
</pre>
<p>I have already figured out that I need to cast BinaryReader to IDisposable to be able to call Dispose on it, but I don't understand why I can't just call the Dispose() method directly without casting to IDisposable?</p>
|
[
{
"answer_id": 223020,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 4,
"selected": true,
"text": "<p>It won't work because the <code>Dispose</code> method on <code>BinaryReader</code> has been explicitly implemented.</p>\n\n<p>Instead of being implicitly implemented, as in:</p>\n\n<pre><code>public void Dispose()\n{\n}\n</code></pre>\n\n<p>...it has been explicitly implemented, as in:</p>\n\n<pre><code>void IDisposable.Dispose()\n{\n}\n</code></pre>\n\n<p>...which means it can only be accessed via the <code>IDisposable</code> interface. Therefore, you have to cast the instance to <code>IDisposable</code> first.</p>\n"
},
{
"answer_id": 223169,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>Expanding on my comments <a href=\"https://stackoverflow.com/questions/222996/why-calling-dispose-on-binaryreader-results-in-compile-error#223020\">here</a>, the <code>BinaryReader</code> class does not properly implement the Dispose pattern.</p>\n\n<p>Looking at this class in Reflector, it looks like this (for .NET 3.5):</p>\n\n<pre><code>public class BinaryReader : IDisposable\n{\n public virtual void Close()\n {\n this.Dispose(true);\n }\n protected virtual void Dispose(bool disposing)\n {\n if (disposing)\n {\n Stream stream = this.m_stream;\n this.m_stream = null;\n if (stream != null)\n {\n stream.Close();\n }\n }\n this.m_stream = null;\n this.m_buffer = null;\n this.m_decoder = null;\n this.m_charBytes = null;\n this.m_singleChar = null;\n this.m_charBuffer = null;\n }\n void IDisposable.Dispose()\n {\n this.Dispose(true);\n }\n}\n</code></pre>\n\n<p>The problem here is that by making <code>IDisposable.Dispose()</code> an explicit interface implementaiton it forces a developer to call <code>Close()</code> instead of <code>Dispose()</code>. </p>\n\n<p>In this context, we have a case of imbalanced semantics. There was never a call to \"Open\" the reader so it is not intuitive to \"Close\" the reader. </p>\n\n<p>Going one step further, in order to call Dispose() you must then explicitly cast to <code>IDisposable</code>, which is not something you ordinarily need to do. You do have the option of calling <code>Dispose(bool)</code> directly, but how do you know what the boolean parameter should be?</p>\n\n<p>To properly follow the pattern, it should have been implmented as:</p>\n\n<pre><code>public class BinaryReader : IDisposable\n{\n public virtual void Close()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n protected virtual void Dispose(bool disposing)\n {\n if (disposing)\n {\n Stream stream = this.m_stream;\n this.m_stream = null;\n if (stream != null)\n {\n stream.Close();\n }\n }\n this.m_stream = null;\n this.m_buffer = null;\n this.m_decoder = null;\n this.m_charBytes = null;\n this.m_singleChar = null;\n this.m_charBuffer = null;\n }\n public void Dispose()\n {\n this.Close();\n }\n}\n</code></pre>\n\n<p>This would allow you to call either <code>Close()</code> or <code>Dispose()</code>, in which case either call continues to result in calling <code>Dispose(true)</code>. (This is the same flow as the actual implementation by calling <code>Close()</code> or <code>((IDisposable)reader).Dispose()</code>).</p>\n\n<p>Fortunately (or unfortunately, depending on which way you choose to look at it) because <code>BinaryReader</code> does implement the <code>IDisposable</code> interface it is allowed in a using statement:</p>\n\n<pre><code>using (BinaryReader reader = new BinaryReader(...))\n{\n}\n</code></pre>\n"
},
{
"answer_id": 223794,
"author": "trampster",
"author_id": 78561,
"author_profile": "https://Stackoverflow.com/users/78561",
"pm_score": 1,
"selected": false,
"text": "<p>Actually they have chosen to use Close() instead of Dispose()\nDispose has been explicitly implemented. Which is why you can't see it.</p>\n\n<p>However Close does the same thing as dispose and this is the method they want you to use. Reflector gives the following disassembly for the Close method</p>\n\n<pre><code>public virtual void Close()\n{\n this.Dispose(true);\n}\n</code></pre>\n\n<p>Close() is used because it is a better choice of words in the context of a binary reader.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1534/"
] |
I have the following class which uses BinaryReader internally and implements IDisposable.
```
class DisposableClass : IDisposable
{
private BinaryReader reader;
public DisposableClass(Stream stream)
{
reader = new BinaryReader(stream);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)reader).Dispose();
// reader.Dispose();// this won't compile
}
}
public void Dispose()
{
this.Dispose(true);
}
}
```
I have already figured out that I need to cast BinaryReader to IDisposable to be able to call Dispose on it, but I don't understand why I can't just call the Dispose() method directly without casting to IDisposable?
|
It won't work because the `Dispose` method on `BinaryReader` has been explicitly implemented.
Instead of being implicitly implemented, as in:
```
public void Dispose()
{
}
```
...it has been explicitly implemented, as in:
```
void IDisposable.Dispose()
{
}
```
...which means it can only be accessed via the `IDisposable` interface. Therefore, you have to cast the instance to `IDisposable` first.
|
222,999 |
<p>I created a single page (with code behind .vb) and created Public intFileID As Integer</p>
<p>in the Page load I check for the querystring and assign it if available or set intFileID = 0.</p>
<pre><code>Public intFileID As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.QueryString("fileid") Is Nothing Then
intFileID = CInt(Request.QueryString("fileid"))
End If
If intFileID > 0 Then
GetFile(intFileID)
End If
End If
End Sub
Private Sub GetFile()
'uses intFileID to retrieve the specific record from database and set's the various textbox.text
End Sub
</code></pre>
<p>There is a click event for the Submit button that inserts or updates a record based on the value of the intFileID variable. I need to be able to persist that value on postback for it all to work.</p>
<p>The page simply inserts or updates a record in a SQL database. I'm not using a gridview,formview,detailsview, or any other rad type object which persists the key value by itself and I don't want to use any of them.</p>
<p>How can I persist the value set in intFileID without creating something in the HTML which could possibly be changed.</p>
<p><strong>[EDIT] Changed Page_Load to use ViewState to persist the intFileID value</strong></p>
<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.QueryString("fileid") Is Nothing Then
intFileID = CInt(Request.QueryString("fileid"))
End If
If intFileID > 0 Then
GetFile(intFileID)
End If
ViewState("intFileID") = intFileID
Else
intFileID = ViewState("intFileID")
End If
End Sub
</code></pre>
|
[
{
"answer_id": 223006,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>Store it in the Session.</p>\n\n<pre><code>Page.Session[\"MyPage_FileID\"] = intFileID\n</code></pre>\n\n<p>You'll need to have logic that manages it as the user navigates around, but if it is always set when the page loads from a GET (or you clear it, if not available on GET) then you should be ok using it later from the Session on your submit PostBack.</p>\n"
},
{
"answer_id": 223033,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 3,
"selected": false,
"text": "<p>Store in:</p>\n\n<ul>\n<li>Session</li>\n<li>ViewState</li>\n<li>Hidden input</li>\n</ul>\n"
},
{
"answer_id": 223048,
"author": "jerhinesmith",
"author_id": 1108,
"author_profile": "https://Stackoverflow.com/users/1108",
"pm_score": 6,
"selected": true,
"text": "<p>As others have pointed out, you can store it in the Session or the ViewState. If it's page specific, I like to store it in the ViewState as opposed to the Session, but I don't know if one method is generally preferred over the other.</p>\n\n<p>In VB, you would store an item in the ViewState like:</p>\n\n<pre><code>ViewState(key) = value\n</code></pre>\n\n<p>And retrieve it like:</p>\n\n<pre><code>value = ViewState(key)\n</code></pre>\n"
},
{
"answer_id": 223054,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Remember:</p>\n\n<p>Each time your server code runs, it's in a brand new instance of your page class. That's for every postback.</p>\n"
},
{
"answer_id": 223059,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 3,
"selected": false,
"text": "<p>Just to summarize what is said above.</p>\n\n<p>You can use Session, Viewstate, or a hidden field.</p>\n\n<p>I personally prefer viewstate as it will work in web farm environments, Session does not, it does not store it on the server waiting for the user, for up to 20 minutes to be removed, and in general viewstate is the place to be for page level data.</p>\n\n<p>You can use a hidden field, but then a user could more easily modify it.</p>\n"
},
{
"answer_id": 223156,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, since an ASP.NET page postbacks to itself - including the query string - you could just remove the <code>If Not Page.IsPostBack</code> condition. Then it'd set itself on each postback.</p>\n"
},
{
"answer_id": 227493,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I personally would choose to store the value in control state instead of viewstate as viewstate can easily be switched off. ControlState will persist even if viewstate is switched off for any reason. I have included an example on how this may be done.</p>\n\n<pre><code>Private intFileId As Integer = 0\n\nPublic Property FileID() As Integer\n Get\n Return intFileId\n End Get\n Set(ByVal value As Integer)\n intFileId = value\n End Set\nEnd Property\n\n\nProtected Overrides Function SaveControlState() As Object\n Dim objState(2) As Object\n objState(0) = MyBase.SaveControlState()\n objState(1) = Me.FileID\n Return objState\nEnd Function\n\n\nProtected Overrides Sub LoadControlState(ByVal savedState As Object)\n Dim objState() As Object\n objState = savedState\n MyBase.LoadControlState(objState(0))\n Me.FileID = CInt(objState(1))\nEnd Sub\n\n\n\n\nProtected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n Me.Page.RegisterRequiresControlState(Me)\nEnd Sub\n\n\nProtected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n\n If Not Page.IsPostBack Then\n If Not String.IsNullOrEmpty(Request.QueryString(\"fileid\")) Then\n Me.FileID = CInt(Request.QueryString(\"fileid\"))\n End If\n End If\n\n Response.Write(Me.FileID.ToString())\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 8103992,
"author": "Sen Jacob",
"author_id": 399414,
"author_profile": "https://Stackoverflow.com/users/399414",
"pm_score": 0,
"selected": false,
"text": "<p>I'll use Session as <a href=\"https://stackoverflow.com/questions/222999/how-to-persist-variable-on-postback/223006#223006\">suggested by tvanfosson.</a>\nViewState and HiddenField might be too heavy if you want to keep large data like a dataset for comments in a forum's topic pages..</p>\n"
},
{
"answer_id": 34962176,
"author": "Sahil Saini",
"author_id": 4846477,
"author_profile": "https://Stackoverflow.com/users/4846477",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p><code>Session[\"KeyName\"] = your value;</code></p>\n \n <ol>\n <li>Type cast to the type to retrieve and store the data from session like given below :</li>\n </ol>\n \n <p><code>Datatable dt = (DataTable)(Session[\"KeyName\"]);</code></p>\n</blockquote>\n\n<p>or</p>\n\n<blockquote>\n <p><code>ViewState[\"KEY\"]= value;</code></p>\n \n <ol start=\"2\">\n <li>Type cast to the type to retrieve and store the data from session like given below :</li>\n </ol>\n \n <p><code>String str = (String)ViewState[\"KEY\"];</code></p>\n</blockquote>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
I created a single page (with code behind .vb) and created Public intFileID As Integer
in the Page load I check for the querystring and assign it if available or set intFileID = 0.
```
Public intFileID As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.QueryString("fileid") Is Nothing Then
intFileID = CInt(Request.QueryString("fileid"))
End If
If intFileID > 0 Then
GetFile(intFileID)
End If
End If
End Sub
Private Sub GetFile()
'uses intFileID to retrieve the specific record from database and set's the various textbox.text
End Sub
```
There is a click event for the Submit button that inserts or updates a record based on the value of the intFileID variable. I need to be able to persist that value on postback for it all to work.
The page simply inserts or updates a record in a SQL database. I'm not using a gridview,formview,detailsview, or any other rad type object which persists the key value by itself and I don't want to use any of them.
How can I persist the value set in intFileID without creating something in the HTML which could possibly be changed.
**[EDIT] Changed Page\_Load to use ViewState to persist the intFileID value**
```
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.QueryString("fileid") Is Nothing Then
intFileID = CInt(Request.QueryString("fileid"))
End If
If intFileID > 0 Then
GetFile(intFileID)
End If
ViewState("intFileID") = intFileID
Else
intFileID = ViewState("intFileID")
End If
End Sub
```
|
As others have pointed out, you can store it in the Session or the ViewState. If it's page specific, I like to store it in the ViewState as opposed to the Session, but I don't know if one method is generally preferred over the other.
In VB, you would store an item in the ViewState like:
```
ViewState(key) = value
```
And retrieve it like:
```
value = ViewState(key)
```
|
223,013 |
<p>I often need to run reduce (also called foldl / foldr, depending on your contexts) in java to aggregate elements of an Itterable. </p>
<p>Reduce takes a collection/iterable/etc, a function of two parameters, and an optional start value (depending on the implementation details). The function is successively applied to an element of the collection and the output of the previous invocation of reduce until all elements have been processed, and returns the final value.</p>
<p>Is there a type-safe implementation of reduce in any common java api? <a href="http://google-collections.googlecode.com" rel="noreferrer">Google Collections</a> <em>seems</em> like it should have one, but I haven't been able to find it. (possibly because I don't know what other names it would use.)</p>
|
[
{
"answer_id": 223055,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 1,
"selected": false,
"text": "<p>Try the <a href=\"http://commons.apache.org/sandbox/functor/\" rel=\"nofollow noreferrer\">commons functor package</a>. It's been in sandbox forever, but I think it'll do what you want.</p>\n"
},
{
"answer_id": 223152,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 3,
"selected": true,
"text": "<p>you could probably roll your own generic pretty easily, based on your description:</p>\n\n<pre><code>public interface Reducer<A, T>\n{\n public A foldIn(A accum, T next);\n}\n</code></pre>\n\n<p>Then using the strategy pattern:</p>\n\n<pre><code>public class Reductor<A, T>\n{\n private Reducer<A, T> worker;\n public Reductor<A, T>(Reducer<A, T> worker)\n {\n this.worker = worker;\n }\n\n public A fold(A rval, Iterator<T> itr)\n {\n while(itr.hasNext())\n {\n A rval = worker.foldIn(rval, itr.next());\n }\n return rval;\n }\n}\n</code></pre>\n\n<p>I'm sure there are a ton of syntax errors but that's the main point (there a few choices you could make about how to get the empty accumulator value. Then to use it on a particular iterator just define your Reducer on the fly:</p>\n\n<pre><code>Reductor r = new Reductor<A, T>(new Reducer<A, T>()\n{\n public A foldIn(A prev, T next)\n {\n A rval;\n //do stuff...\n return rval;\n }\n }\n\n A fold = r.fold(new A(), collection.getIterator());\n</code></pre>\n\n<p>depending on how your iterator works this can fold left or fold right as long as the iterator goes in the right direction.</p>\n\n<p>hope this helps.</p>\n"
},
{
"answer_id": 3088389,
"author": "Greg Haines",
"author_id": 372559,
"author_profile": "https://Stackoverflow.com/users/372559",
"pm_score": 2,
"selected": false,
"text": "<p>Based on Luke's suggestion, here is a legit Java implementation:</p>\n\n<pre><code>public interface Reducer<A,T>\n{\n A foldIn(A accum, T next);\n}\n\npublic static <T> T reduce(final Reducer<T,T> reducer, \n final Iterable<? extends T> i)\n{\n T result = null;\n final Iterator<? extends T> iter = i.iterator();\n if (iter.hasNext())\n {\n result = iter.next();\n while (iter.hasNext())\n {\n result = reducer.foldIn(result, iter.next());\n }\n }\n return result;\n}\n\npublic static <A,T> A reduce(final Reducer<A,T> reducer, \n final Iterable<? extends T> i, \n final A initializer)\n{\n A result = initializer;\n final Iterator<? extends T> iter = i.iterator();\n while (iter.hasNext())\n {\n result = reducer.foldIn(result, iter.next());\n }\n return result;\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
] |
I often need to run reduce (also called foldl / foldr, depending on your contexts) in java to aggregate elements of an Itterable.
Reduce takes a collection/iterable/etc, a function of two parameters, and an optional start value (depending on the implementation details). The function is successively applied to an element of the collection and the output of the previous invocation of reduce until all elements have been processed, and returns the final value.
Is there a type-safe implementation of reduce in any common java api? [Google Collections](http://google-collections.googlecode.com) *seems* like it should have one, but I haven't been able to find it. (possibly because I don't know what other names it would use.)
|
you could probably roll your own generic pretty easily, based on your description:
```
public interface Reducer<A, T>
{
public A foldIn(A accum, T next);
}
```
Then using the strategy pattern:
```
public class Reductor<A, T>
{
private Reducer<A, T> worker;
public Reductor<A, T>(Reducer<A, T> worker)
{
this.worker = worker;
}
public A fold(A rval, Iterator<T> itr)
{
while(itr.hasNext())
{
A rval = worker.foldIn(rval, itr.next());
}
return rval;
}
}
```
I'm sure there are a ton of syntax errors but that's the main point (there a few choices you could make about how to get the empty accumulator value. Then to use it on a particular iterator just define your Reducer on the fly:
```
Reductor r = new Reductor<A, T>(new Reducer<A, T>()
{
public A foldIn(A prev, T next)
{
A rval;
//do stuff...
return rval;
}
}
A fold = r.fold(new A(), collection.getIterator());
```
depending on how your iterator works this can fold left or fold right as long as the iterator goes in the right direction.
hope this helps.
|
223,021 |
<p>I'm using the 'using' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary 'std::'s).</p>
<pre><code>using std::string;
using std::vector;
class Foo { /*...*/ };
</code></pre>
<p>What is the scope on this declaration? If I do this in a header, will it inject these 'using' declarations into every cpp file that includes the header?</p>
|
[
{
"answer_id": 223030,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<p>In the case cited, the file (\"translation unit\"), which means yes, every file that includes it.</p>\n\n<p>You can also put the using statement inside the class, in which case, it's in effect just for that class. </p>\n\n<p>Generally, if you need to specify a namespace in a header, it's often best to just fully-qualify every identifier necessary. </p>\n"
},
{
"answer_id": 223036,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 2,
"selected": false,
"text": "<p>That is correct. The scope is the module that uses the <code>using</code> declaration. If any header files that a module includes have <code>using</code> declarations, the scope of those declarations will be that module, as well as any other modules that include the same headers.</p>\n"
},
{
"answer_id": 223047,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 7,
"selected": true,
"text": "<p>When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a <code>using</code> declaration has the exact same effect of placing the <code>using</code> declaration at the top of each file that includes that header file.</p>\n"
},
{
"answer_id": 223050,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 7,
"selected": false,
"text": "<p>There's nothing special about header files that would keep the <code>using</code> declaration out. It's a simple text substitution before the compilation even starts.</p>\n\n<p>You can limit a <code>using</code> declaration to a scope:</p>\n\n<pre><code>void myFunction()\n{\n using namespace std; // only applies to the function's scope\n vector<int> myVector;\n}\n</code></pre>\n"
},
{
"answer_id": 223221,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 3,
"selected": false,
"text": "<p>The scope is whatever scope the using declaration is in.</p>\n\n<p>If this is global scope, then it will be at global scope. If it is in global scope of a header file, then it will be in the global scope of every source file that includes the header.</p>\n\n<p>So, the general advice is to <strong>avoid using declarations in global scope of header files</strong>.</p>\n"
},
{
"answer_id": 223250,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 6,
"selected": false,
"text": "<p>The scope of the using statement depends on where it is located in the code:</p>\n\n<ul>\n<li>Placed at the top of a file, it has scope throughout that file.</li>\n<li>If this is a header file, it will have scope in all files that include that header. In general, this is \"<em>not a good idea</em>\" as it can have unexpected side effects</li>\n<li>Otherwise the <em>using</em> statement has scope within the block that contains it from the point it occurs to the end of the block. If it is placed within a method, it will have scope within that method. If it is placed within a class definition it will have scope within that class.</li>\n</ul>\n"
},
{
"answer_id": 224909,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>There are a few comments that are rather unqualified when they say \"Don't\". That is too stern, but you have to understand when it is OK.</p>\n\n<p>Writing <code>using std::string</code> is never OK. Writing <code>using ImplementationDetail::Foo</code> in your own header, when that header declares ImplementationDetail::Foo can be OK, moreso if the using declaration happens in your namespace. E.g.</p>\n\n<pre><code>namespace MyNS {\n namespace ImplementationDetail {\n int Foo;\n }\n using ImplementationDetail::Foo;\n}\n</code></pre>\n"
},
{
"answer_id": 68379432,
"author": "Stardusstt",
"author_id": 12790909,
"author_profile": "https://Stackoverflow.com/users/12790909",
"pm_score": 0,
"selected": false,
"text": "<p>Edited:</p>\n<p>As a additional information , put "using" in your source file will affect your header when the statement is placed <strong>"before the #include"</strong> . ( The scope of using <strong>does not extend "backwards"</strong> )</p>\n<p>header.h</p>\n<pre><code>//header.h\n#include <string>\n\nstd::string t1; // ok\nstring t2; // ok\n</code></pre>\n<p>header.cpp</p>\n<pre><code>//header.cpp\nusing namespace std ;\n\n#include "header.h"\n\n...\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13300/"
] |
I'm using the 'using' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary 'std::'s).
```
using std::string;
using std::vector;
class Foo { /*...*/ };
```
What is the scope on this declaration? If I do this in a header, will it inject these 'using' declarations into every cpp file that includes the header?
|
When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a `using` declaration has the exact same effect of placing the `using` declaration at the top of each file that includes that header file.
|
223,040 |
<p>If two users edit the same wiki topic, what methods have been used in wikis (or in similar collaborative editing software) to merge the second user's edits with the first?</p>
<p>I'd like a solution that:</p>
<ul>
<li>doesn't require locking</li>
<li>doesn't lose any additions to the page.</li>
<li>It may add extra "boilerplate" text to indicate where differing changes were made.</li>
</ul>
<p>(I'm interested in a solution that could be used to implement <a href="https://web.archive.org/web/20081009065531/http://stackoverflow.uservoice.com:80/pages/general/suggestions/28245" rel="nofollow noreferrer">this uservoice idea</a> for stack overflow.)</p>
|
[
{
"answer_id": 223060,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>You can write a \"lock\" in an other database table with the id of the user and the time and delete the \"lock\" (that isn't a real lock for those who do not understand) when the person save or after x minute.</p>\n\n<p>This way, when someone try to edit and someone already doing it. A message can appear with the time remaining OR by just telling that someone else is currently editing the post.</p>\n"
},
{
"answer_id": 223061,
"author": "64BitBob",
"author_id": 16339,
"author_profile": "https://Stackoverflow.com/users/16339",
"pm_score": 2,
"selected": false,
"text": "<p>My experience with most Wiki software (e.g. MediaWiki) is that it tracks the version of the document you are editing. If the document changes during your time editing, your change is rejected and you are prompted to perform a manual merge. </p>\n"
},
{
"answer_id": 223116,
"author": "AaronSieb",
"author_id": 16911,
"author_profile": "https://Stackoverflow.com/users/16911",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could use a merging algorithm, like that used by source control software. You'd probably want to make it check for changes at the paragraph level, to help maintain readability.</p>\n\n<p>If there was a potential conflict (e.g. two users editing the same paragraph), you would probably need to simply present both versions with boilerplate text and/or notify the second and subsequent submitters that the contents of their post may have changed from what they submitted.</p>\n"
},
{
"answer_id": 223577,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://twiki.org\" rel=\"nofollow noreferrer\">TWiki</a> automatically merges <a href=\"http://twiki.org/cgi-bin/view/TWiki.SimultaneousEdits\" rel=\"nofollow noreferrer\">Simultaneous Edits</a>.</p>\n\n<blockquote>\n <p>TWiki allows multiple simultaneous edits of the same topic, and then merges the different changes automatically. You probably won't even notice this happening unless there is a conflict that cannot be merged automatically. In this case, you may see TWiki inserting \"change marks\" into the text to highlight conflicts between your edits and another person's. These change marks are only used if you edit the same part of a topic as someone else, and they indicate what the text used to look like, what the other person's edits were, and what your edits were.</p>\n \n <p>TWiki will warn if you attempt to edit a topic that someone else is editing. It will also warn if a merge was required during a save. </p>\n</blockquote>\n\n<p>There was also some <a href=\"http://twiki.org/cgi-bin/view/Codev/DakarMergeModel\" rel=\"nofollow noreferrer\">documentation</a> from that feature being developed detailing how it would behave.</p>\n\n<blockquote>\n <p>The basic principles I used in coding up the mergeing algorithm were:</p>\n \n <ol>\n <li>If it's possible to merge without using conflict markers, do so.</li>\n <li>If it's possible to merge using conflict markers, do so.</li>\n <li>If it's not possible to merge, then the most recent checkin wins. </li>\n </ol>\n</blockquote>\n\n<p>It's worth noting that TWiki has a similar feature to Stack Overflow for collapsing subsequent revisions by the same user within a certain time limit and this <a href=\"http://develop.twiki.org/~twiki4/cgi-bin/view/Bugs/Item1897\" rel=\"nofollow noreferrer\">caused a bug when happening in conjunction with a merge</a>.</p>\n\n<blockquote>\n <ol>\n <li>User A edits topic</li>\n <li>User A saves rev N</li>\n <li>User B edits topic, picks up rev N</li>\n <li>User A edits topic again, picks up rev N</li>\n <li>User A saves changes; save sees that the change is within the ReplceIfEditiedWithin? window, <strong>so does not increment the rev number</strong></li>\n <li>User B saves, code sees that <strong>the rev number on disc has not changed since they started editing</strong> so doesn't detect a need to merge. </li>\n </ol>\n</blockquote>\n\n<p>Also worth noting is that TWiki will warn the second user that the topic is being edited:</p>\n\n<blockquote>\n <p>So I invented the concept of \"leases\". When a topic is edited, a lease is taken on the topic for a fixed period of time (default 1h). If someone else tries to edit, they are told that there is already a lease on the topic, but that doesn't stop them from editing. It isn't a lock, it's just a way of advising them. Mergeing is still the prime resolution mechanism; the lease is purely advisory. If a user - or a plugin - chooses to back away from a topic because someone has a lease out on it, well, that's up to the plugin.</p>\n \n <p>The descriptive comment in TWiki.cfg is as follows:</p>\n\n<pre><code> # When a topic is edited, the user takes a \"lease\" on that topic.\n # If another user tries to also edit the topic while the lease\n # is still active, they will get a warning. The warning text will\n # be different depending on whether the lease has \"expired\" or\n # not i.e. if it was taken out more than LeaseLength seconds ago.\n</code></pre>\n</blockquote>\n\n<p>note that the lease terminology is only for developers, not end users.</p>\n"
},
{
"answer_id": 223698,
"author": "Marcin",
"author_id": 21640,
"author_profile": "https://Stackoverflow.com/users/21640",
"pm_score": 0,
"selected": false,
"text": "<p>Well now, I think that that would be a terrible, terrible idea. Let's be honest: merging is pretty dicey in code, and that at least has elements that might be isolated. Don't do this - human intelligence will always be better. Instead you are trying to replace it with an automatic solution that can result in output that is not sane, for no benefit.</p>\n"
},
{
"answer_id": 223701,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 0,
"selected": false,
"text": "<p>In researching the TWiki answer I also stumbled across <a href=\"http://synchroedit.com/\" rel=\"nofollow noreferrer\">SynchroEdit</a> which appears to be a <a href=\"http://www.codingmonkeys.de/subethaedit/\" rel=\"nofollow noreferrer\">SubEthaEdit</a> style browser-based simultaneous multiuser editor. It looks like it may have been abandoned around September 2007, but there's source code available for download.</p>\n"
},
{
"answer_id": 412328,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 0,
"selected": false,
"text": "<p>For documentation sake: <a href=\"http://www.dokuwiki.org/dokuwiki\" rel=\"nofollow noreferrer\">DokuWiki</a> places a 15 minutes lock on edited pages, which gets renewed whenever you preview your edits (ie. 15 minutes from your preview or edit start).</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] |
If two users edit the same wiki topic, what methods have been used in wikis (or in similar collaborative editing software) to merge the second user's edits with the first?
I'd like a solution that:
* doesn't require locking
* doesn't lose any additions to the page.
* It may add extra "boilerplate" text to indicate where differing changes were made.
(I'm interested in a solution that could be used to implement [this uservoice idea](https://web.archive.org/web/20081009065531/http://stackoverflow.uservoice.com:80/pages/general/suggestions/28245) for stack overflow.)
|
[TWiki](http://twiki.org) automatically merges [Simultaneous Edits](http://twiki.org/cgi-bin/view/TWiki.SimultaneousEdits).
>
> TWiki allows multiple simultaneous edits of the same topic, and then merges the different changes automatically. You probably won't even notice this happening unless there is a conflict that cannot be merged automatically. In this case, you may see TWiki inserting "change marks" into the text to highlight conflicts between your edits and another person's. These change marks are only used if you edit the same part of a topic as someone else, and they indicate what the text used to look like, what the other person's edits were, and what your edits were.
>
>
> TWiki will warn if you attempt to edit a topic that someone else is editing. It will also warn if a merge was required during a save.
>
>
>
There was also some [documentation](http://twiki.org/cgi-bin/view/Codev/DakarMergeModel) from that feature being developed detailing how it would behave.
>
> The basic principles I used in coding up the mergeing algorithm were:
>
>
> 1. If it's possible to merge without using conflict markers, do so.
> 2. If it's possible to merge using conflict markers, do so.
> 3. If it's not possible to merge, then the most recent checkin wins.
>
>
>
It's worth noting that TWiki has a similar feature to Stack Overflow for collapsing subsequent revisions by the same user within a certain time limit and this [caused a bug when happening in conjunction with a merge](http://develop.twiki.org/~twiki4/cgi-bin/view/Bugs/Item1897).
>
> 1. User A edits topic
> 2. User A saves rev N
> 3. User B edits topic, picks up rev N
> 4. User A edits topic again, picks up rev N
> 5. User A saves changes; save sees that the change is within the ReplceIfEditiedWithin? window, **so does not increment the rev number**
> 6. User B saves, code sees that **the rev number on disc has not changed since they started editing** so doesn't detect a need to merge.
>
>
>
Also worth noting is that TWiki will warn the second user that the topic is being edited:
>
> So I invented the concept of "leases". When a topic is edited, a lease is taken on the topic for a fixed period of time (default 1h). If someone else tries to edit, they are told that there is already a lease on the topic, but that doesn't stop them from editing. It isn't a lock, it's just a way of advising them. Mergeing is still the prime resolution mechanism; the lease is purely advisory. If a user - or a plugin - chooses to back away from a topic because someone has a lease out on it, well, that's up to the plugin.
>
>
> The descriptive comment in TWiki.cfg is as follows:
>
>
>
> ```
> # When a topic is edited, the user takes a "lease" on that topic.
> # If another user tries to also edit the topic while the lease
> # is still active, they will get a warning. The warning text will
> # be different depending on whether the lease has "expired" or
> # not i.e. if it was taken out more than LeaseLength seconds ago.
>
> ```
>
>
note that the lease terminology is only for developers, not end users.
|
223,058 |
<p><strong><em>Imagine</em></strong> a base class with many constructors and a virtual method</p>
<pre><code>public class Foo
{
...
public Foo() {...}
public Foo(int i) {...}
...
public virtual void SomethingElse() {...}
...
}
</code></pre>
<p>and now i want to create a descendant class that overrides the virtual method:</p>
<pre><code>public class Bar : Foo
{
public override void SomethingElse() {...}
}
</code></pre>
<p>And another descendant that does some more stuff:</p>
<pre><code>public class Bah : Bar
{
public void DoMoreStuff() {...}
}
</code></pre>
<p>Do i really have to copy all constructors from Foo into Bar and Bah? And then if i change a constructor signature in Foo, do i have to update it in Bar and Bah?</p>
<p>Is there no way to inherit constructors? Is there no way to encourage code reuse?</p>
|
[
{
"answer_id": 223068,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 8,
"selected": true,
"text": "<p>Yes, you will have to implement the constructors that make sense for each derivation and then use the <code>base</code> keyword to direct that constructor to the appropriate base class or the <code>this</code> keyword to direct a constructor to another constructor in the same class.</p>\n<p>If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like <code>null</code> and only expose the necessary ones through their constructors.</p>\n<h1>Update</h1>\n<p>In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.</p>\n"
},
{
"answer_id": 223072,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": false,
"text": "<p>Yes, you have to copy all 387 constructors. You can do some reuse by redirecting them:</p>\n\n<pre><code> public Bar(int i): base(i) {}\n public Bar(int i, int j) : base(i, j) {}\n</code></pre>\n\n<p>but that's the best you can do.</p>\n"
},
{
"answer_id": 223073,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 6,
"selected": false,
"text": "<p>387 constructors?? That's your main problem. How about this instead?</p>\n\n<pre><code>public Foo(params int[] list) {...}\n</code></pre>\n"
},
{
"answer_id": 223078,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>Too many constructors is a sign of a broken design. Better a class with few constructors and the ability to set properties. If you really need control over the properties, consider a factory in the same namespace and make the property setters internal. Let the factory decide how to instantiate the class and set its properties. The factory can have methods that take as many parameters as necessary to configure the object properly.</p>\n"
},
{
"answer_id": 223086,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is not that Bar and Bah have to copy 387 constructors, the problem is that Foo has 387 constructors. Foo clearly does too many things - refactor quick! Also, unless you have a really good reason to have values set in the constructor (which, if you provide a parameterless constructor, you probably don't), I'd recommend using property getting/setting.</p>\n"
},
{
"answer_id": 223113,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 2,
"selected": false,
"text": "<p>No, you don't need to copy all 387 constructors to Bar and Bah. Bar and Bah can have as many or as few constructors as you want independent of how many you define on Foo. For example, you could choose to have just one Bar constructor which constructs Foo with Foo's 212th constructor.</p>\n\n<p>Yes, any constructors you change in Foo that Bar or Bah depend on will require you to modify Bar and Bah accordingly.</p>\n\n<p>No, there is no way in .NET to inherit constructors. But you can achieve code reuse by calling a base class's constructor inside the subclass's constructor or by calling a virtual method you define (like Initialize()).</p>\n"
},
{
"answer_id": 223121,
"author": "Greg D",
"author_id": 6932,
"author_profile": "https://Stackoverflow.com/users/6932",
"pm_score": 1,
"selected": false,
"text": "<p>You may be able to adapt a version of the <a href=\"http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8\" rel=\"nofollow noreferrer\">C++ virtual constructor idiom</a>. As far as I know, C# doesn't support covariant return types. I believe that's on many peoples' wish lists.</p>\n"
},
{
"answer_id": 223458,
"author": "dviljoen",
"author_id": 29021,
"author_profile": "https://Stackoverflow.com/users/29021",
"pm_score": 5,
"selected": false,
"text": "<p>Don't forget that you can also redirect constructors to other constructors at the same level of inheritance:</p>\n\n<pre><code>public Bar(int i, int j) : this(i) { ... }\n ^^^^^\n</code></pre>\n"
},
{
"answer_id": 223500,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>As <code>Foo</code> is a class can you not create virtual overloaded <code>Initialise()</code> methods? Then they would be available to sub-classes and still extensible?</p>\n\n<pre><code>public class Foo\n{\n ...\n public Foo() {...}\n\n public virtual void Initialise(int i) {...}\n public virtual void Initialise(int i, int i) {...}\n public virtual void Initialise(int i, int i, int i) {...}\n ... \n public virtual void Initialise(int i, int i, ..., int i) {...}\n\n ...\n\n public virtual void SomethingElse() {...}\n ...\n}\n</code></pre>\n\n<p>This shouldn't have a higher performance cost unless you have lots of default property values and you hit it a lot.</p>\n"
},
{
"answer_id": 739591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Too bad we're kind of forced to tell the compiler the obvious:</p>\n\n<pre><code>Subclass(): base() {}\nSubclass(int x): base(x) {}\nSubclass(int x,y): base(x,y) {}\n</code></pre>\n\n<p>I only need to do 3 constructors in 12 subclasses, so it's no big deal, but I'm not too fond of repeating that on every subclass, after being used to not having to write it for so long. I'm sure there's a valid reason for it, but I don't think I've ever encountered a problem that requires this kind of restriction.</p>\n"
},
{
"answer_id": 3831476,
"author": "Pavlo Neiman",
"author_id": 164001,
"author_profile": "https://Stackoverflow.com/users/164001",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public class BaseClass\n{\n public BaseClass(params int[] parameters)\n {\n\n } \n}\n\npublic class ChildClass : BaseClass\n{\n public ChildClass(params int[] parameters)\n : base(parameters)\n {\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6784218,
"author": "Aaron Murgatroyd",
"author_id": 738380,
"author_profile": "https://Stackoverflow.com/users/738380",
"pm_score": 3,
"selected": false,
"text": "<p>Personally I think this is a mistake on Microsofts part, they should have allowed the programmer to override visibility of Constructors, Methods and Properties in base classes, and then make it so that Constructors are always inherited.</p>\n\n<p>This way we just simply override (with lower visibility - ie. Private) the constructors we DONT want instead of having to add all the constructors we DO want. Delphi does it this way, and I miss it.</p>\n\n<p>Take for example if you want to override the System.IO.StreamWriter class, you need to add all 7 constructors to your new class, and if you like commenting you need to comment each one with the header XML. To make it worse, the metadata view dosnt put the XML comments as proper XML comments, so we have to go line by line and copy and paste them. What was Microsoft thinking here?</p>\n\n<p>I have actually written a small utility where you can paste in the metadata code and it will convert it to XML comments using overidden visibility.</p>\n"
},
{
"answer_id": 8143922,
"author": "Exocubic",
"author_id": 1048558,
"author_profile": "https://Stackoverflow.com/users/1048558",
"pm_score": 3,
"selected": false,
"text": "<p>Another simple solution could be to use a structure or simple data class that contains the parameters as properties; that way you can have all the default values and behaviors set up ahead of time, passing the \"parameter class\" in as the single constructor parameter:</p>\n\n<pre><code>public class FooParams\n{\n public int Size...\n protected myCustomStruct _ReasonForLife ...\n}\npublic class Foo\n{\n private FooParams _myParams;\n public Foo(FooParams myParams)\n {\n _myParams = myParams;\n }\n}\n</code></pre>\n\n<p>This avoids the mess of multiple constructors (sometimes) and gives strong typing, default values, and other benefits not provided by a parameter array. It also makes it easy to carry forward since anything that inherits from Foo can still get to, or even add to, FooParams as needed. You still need to copy the constructor, but you always (most of the time) only (as a general rule) ever (at least, for now) need one constructor.</p>\n\n<pre><code>public class Bar : Foo\n{\n public Bar(FooParams myParams) : base(myParams) {}\n}\n</code></pre>\n\n<p>I really like the overloaded Initailize() and Class Factory Pattern approaches better, but sometimes you just need to have a smart constructor. Just a thought.</p>\n"
},
{
"answer_id": 24743423,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Do i really have to copy all constructors from <code>Foo</code> into <code>Bar</code> and <code>Bah</code>? And then if i change a constructor signature in <code>Foo</code>, do i have to update it in <code>Bar</code> and <code>Bah</code>?</p>\n</blockquote>\n\n<p>Yes, if you use constructors to create instances.</p>\n\n<blockquote>\n <p>Is there no way to inherit constructors?</p>\n</blockquote>\n\n<p>Nope.</p>\n\n<blockquote>\n <p>Is there no way to encourage code reuse?</p>\n</blockquote>\n\n<p>Well, I won't get into whether inheriting constructors would be a good or bad thing and whether it would encourage code reuse, since we don't have them and we're not going to get them. :-)</p>\n\n<p>But here in 2014, with the current C#, you can get something very much <em>like</em> inherited constructors by using a generic <code>create</code> method instead. It can be a useful tool to have in your belt, but you wouldn't reach for it lightly. I reached for it recently when faced with needing to pass something into the constructor of a base type used in a couple of hundred derived classes (until recently, the base didn't need any arguments, and so the default constructor was fine — the derived classes didn't declare constructors at all, and got the automatically-supplied one).</p>\n\n<p>It looks like this:</p>\n\n<pre><code>// In Foo:\npublic T create<T>(int i) where: where T : Foo, new() {\n T obj = new T();\n // Do whatever you would do with `i` in `Foo(i)` here, for instance,\n // if you save it as a data member; `obj.dataMember = i;`\n return obj;\n}\n</code></pre>\n\n<p>That says that you can call the generic <code>create</code> function using a type parameter which is any subtype of <code>Foo</code> that has a zero-arguments constructor.</p>\n\n<p>Then, instead of doing <code>Bar b new Bar(42)</code>, you'd do this:</p>\n\n<pre><code>var b = Foo.create<Bar>(42);\n// or\nBar b = Foo.create<Bar>(42);\n// or\nvar b = Bar.create<Bar>(42); // But you still need the <Bar> bit\n// or\nBar b = Bar.create<Bar>(42);\n</code></pre>\n\n<p>There I've shown the <code>create</code> method being on <code>Foo</code> directly, but of course it could be in a factory class of some sort, if the information it's setting up can be set by that factory class.</p>\n\n<p>Just for clarity: The name <code>create</code> isn't important, it could be <code>makeThingy</code> or whatever else you like.</p>\n\n<p>Full Example</p>\n\n<pre><code>using System.IO;\nusing System;\n\nclass Program\n{\n static void Main()\n {\n Bar b1 = Foo.create<Bar>(42);\n b1.ShowDataMember(\"b1\");\n\n Bar b2 = Bar.create<Bar>(43); // Just to show `Foo.create` vs. `Bar.create` doesn't matter\n b2.ShowDataMember(\"b2\");\n }\n\n class Foo\n {\n public int DataMember { get; private set; }\n\n public static T create<T>(int i) where T: Foo, new()\n {\n T obj = new T();\n obj.DataMember = i;\n return obj;\n }\n }\n\n class Bar : Foo\n {\n public void ShowDataMember(string prefix)\n {\n Console.WriteLine(prefix + \".DataMember = \" + this.DataMember);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
***Imagine*** a base class with many constructors and a virtual method
```
public class Foo
{
...
public Foo() {...}
public Foo(int i) {...}
...
public virtual void SomethingElse() {...}
...
}
```
and now i want to create a descendant class that overrides the virtual method:
```
public class Bar : Foo
{
public override void SomethingElse() {...}
}
```
And another descendant that does some more stuff:
```
public class Bah : Bar
{
public void DoMoreStuff() {...}
}
```
Do i really have to copy all constructors from Foo into Bar and Bah? And then if i change a constructor signature in Foo, do i have to update it in Bar and Bah?
Is there no way to inherit constructors? Is there no way to encourage code reuse?
|
Yes, you will have to implement the constructors that make sense for each derivation and then use the `base` keyword to direct that constructor to the appropriate base class or the `this` keyword to direct a constructor to another constructor in the same class.
If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like `null` and only expose the necessary ones through their constructors.
Update
======
In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.
|
223,063 |
<p>I would like to create an application that serves web pages internally and can be run in multiple instances on the same machine. To do so, I would like to create an <code>HttpListener</code> that listens on a port that is:</p>
<ol>
<li>Randomly selected </li>
<li>Currently unused</li>
</ol>
<p>Essentially, what I would like is something like:</p>
<pre><code>mListener = new HttpListener();
mListener.Prefixes.Add("http://*:0/");
mListener.Start();
selectedPort = mListener.Port;
</code></pre>
<p>How can I accomplish this?</p>
|
[
{
"answer_id": 223188,
"author": "Snooganz",
"author_id": 28224,
"author_profile": "https://Stackoverflow.com/users/28224",
"pm_score": 4,
"selected": false,
"text": "<p>How about something like this:</p>\n\n<pre><code> static List<int> usedPorts = new List<int>();\n static Random r = new Random();\n\n public HttpListener CreateNewListener()\n {\n HttpListener mListener;\n int newPort = -1;\n while (true)\n {\n mListener = new HttpListener();\n newPort = r.Next(49152, 65535); // IANA suggests the range 49152 to 65535 for dynamic or private ports.\n if (usedPorts.Contains(newPort))\n {\n continue;\n }\n mListener.Prefixes.Add(string.Format(\"http://*:{0}/\", newPort));\n try\n {\n mListener.Start();\n }\n catch\n {\n continue;\n }\n usedPorts.Add(newPort);\n break;\n }\n\n return mListener;\n }\n</code></pre>\n\n<p>I'm not sure how you would find all of the ports that are in use on that machine, but you should get an exception if you try to listen on a port that is already being used, in which case the method will simply pick another port.</p>\n"
},
{
"answer_id": 3978040,
"author": "Richard Dingwall",
"author_id": 91551,
"author_profile": "https://Stackoverflow.com/users/91551",
"pm_score": 5,
"selected": false,
"text": "<p>TcpListener will find a random un-used port to listen on if you bind to port 0.</p>\n\n<pre><code>public static int GetRandomUnusedPort()\n{\n var listener = new TcpListener(IPAddress.Any, 0);\n listener.Start();\n var port = ((IPEndPoint)listener.LocalEndpoint).Port;\n listener.Stop();\n return port;\n}\n</code></pre>\n"
},
{
"answer_id": 33157951,
"author": "Andrew Rondeau",
"author_id": 1711103,
"author_profile": "https://Stackoverflow.com/users/1711103",
"pm_score": 0,
"selected": false,
"text": "<p>I do not believe this is possible. The documentation for UriBuilder.Port states, \"If a port is not specified as part of the URI, ... the default port value for the protocol scheme will be used to connect to the host.\".</p>\n\n<p>See <a href=\"https://msdn.microsoft.com/en-us/library/system.uribuilder.port(v=vs.110).aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/system.uribuilder.port(v=vs.110).aspx</a></p>\n"
},
{
"answer_id": 38260563,
"author": "Ramon de Klein",
"author_id": 956435,
"author_profile": "https://Stackoverflow.com/users/956435",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately, this isn't possible. As Richard Dingwall already suggested, you could create a TCP listener and use that port. This approach has two possible problems:</p>\n\n<ul>\n<li>In theory a race condition may occur, because another TCP listener might use this port after closing it.</li>\n<li>If you're not running as an Administrator, then you need to allocate prefixes and port combinations to allow binding to it. This is impossible to manage if you don't have administrator privileges. Essentially this would impose that you need to run your HTTP server with administrator privileges (which is generally a bad idea).</li>\n</ul>\n"
},
{
"answer_id": 39772904,
"author": "dodbrian",
"author_id": 2537328,
"author_profile": "https://Stackoverflow.com/users/2537328",
"pm_score": 1,
"selected": false,
"text": "<p>Since you are using an HttpListener (and therefore TCP connections) you can get a list of active TCP listeners using <code>GetActiveTcpListeners</code> method of the <code>IPGlobalProperties</code> object and inspect their <code>Port</code> property.</p>\n\n<p>The possible solution may look like this:</p>\n\n<pre><code>private static bool TryGetUnusedPort(int startingPort, ref int port)\n{\n var listeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();\n\n for (var i = startingPort; i <= 65535; i++)\n {\n if (listeners.Any(x => x.Port == i)) continue;\n port = i;\n return true;\n }\n\n return false;\n}\n</code></pre>\n\n<p>This code will find first unused port beginning from the <code>startingPort</code> port number and return <code>true</code>. In case all ports are already occupied (which is very unlikely) the method returns <code>false</code>.</p>\n\n<p>Also keep in mind the possibility of a race condition that may happen when some other process takes the found port before you do.</p>\n"
},
{
"answer_id": 43617808,
"author": "Scott Offen",
"author_id": 1102764,
"author_profile": "https://Stackoverflow.com/users/1102764",
"pm_score": 1,
"selected": false,
"text": "<p>I'd recommend trying <a href=\"http://www.nuget.org/packages/Grapevine/\" rel=\"nofollow noreferrer\">Grapevine</a>. It allows you embed a REST/HTTP server in your application. It includes a <code>RestCluster</code> class that will allow you to manage all of your <code>RestServer</code> instances in a single place.</p>\n\n<p>Set each instance to use a random, open port number like this:</p>\n\n<pre><code>using (var server = new RestServer())\n{\n // Grab the next open port (starts at 1)\n server.Port = PortFinder.FindNextLocalOpenPort();\n\n // Grab the next open port after 2000 (inclusive)\n server.Port = PortFinder.FindNextLocalOpenPort(2000);\n\n // Grab the next open port between 2000 and 5000 (inclusive)\n server.Port = PortFinder.FindNextLocalOpenPort(200, 5000);\n ...\n}\n</code></pre>\n\n<p>Getting started guide: <a href=\"https://sukona.github.io/Grapevine/en/getting-started.html\" rel=\"nofollow noreferrer\">https://sukona.github.io/Grapevine/en/getting-started.html</a></p>\n"
},
{
"answer_id": 46666370,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an answer, derived from <a href=\"https://stackoverflow.com/a/223188/24874\">Snooganz's answer</a>. It avoids the race condition between testing for availability, and later binding.</p>\n\n<pre><code>public static bool TryBindListenerOnFreePort(out HttpListener httpListener, out int port)\n{\n // IANA suggested range for dynamic or private ports\n const int MinPort = 49215;\n const int MaxPort = 65535;\n\n for (port = MinPort; port < MaxPort; port++)\n {\n httpListener = new HttpListener();\n httpListener.Prefixes.Add($\"http://localhost:{port}/\");\n try\n {\n httpListener.Start();\n return true;\n }\n catch\n {\n // nothing to do here -- the listener disposes itself when Start throws\n }\n }\n\n port = 0;\n httpListener = null;\n return false;\n}\n</code></pre>\n\n<p>On my machine this method takes 15ms on average, which is acceptable for my use case. Hope this helps someone else.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I would like to create an application that serves web pages internally and can be run in multiple instances on the same machine. To do so, I would like to create an `HttpListener` that listens on a port that is:
1. Randomly selected
2. Currently unused
Essentially, what I would like is something like:
```
mListener = new HttpListener();
mListener.Prefixes.Add("http://*:0/");
mListener.Start();
selectedPort = mListener.Port;
```
How can I accomplish this?
|
TcpListener will find a random un-used port to listen on if you bind to port 0.
```
public static int GetRandomUnusedPort()
{
var listener = new TcpListener(IPAddress.Any, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
```
|
223,070 |
<p>I'm looking for a database of commonly installed Windows software. At minimum I need the name of the software and the executable name, but it'd also be nice to have the publisher and the common installation path, etc. Basically, I'd like to be able to query it to find all the software by Adobe and the associated executable name, etc. </p>
<p>Basically I'm looking to be able to do </p>
<pre><code>SELECT * FROM Software WHERE Publisher = 'Microsoft'
SELECT * FROM Software WHERE Executable = 'devenv.com'
</code></pre>
<p>I came across an effort to create such a database a long time ago, but can't seem to find it now. Maybe it fizzled out. Any help would be greatly appreciated. Thanks.</p>
|
[
{
"answer_id": 223140,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>You can do some <strong>screen scraping</strong> with some website that contain <strong>list of software</strong> and build yourself a database of all software and publisher.</p>\n\n<p>Here is some website that contain some list of software:</p>\n\n<ul>\n<li><a href=\"http://www.digital-digest.com/software/index.php\" rel=\"nofollow noreferrer\">http://www.digital-digest.com/software/index.php</a></li>\n<li><a href=\"http://www.bestshareware.net/allsoftware-w.htm\" rel=\"nofollow noreferrer\">http://www.bestshareware.net/allsoftware-w.htm</a></li>\n</ul>\n"
},
{
"answer_id": 223146,
"author": "z-boss",
"author_id": 28098,
"author_profile": "https://Stackoverflow.com/users/28098",
"pm_score": 3,
"selected": false,
"text": "<p>Your best bet would be to <a href=\"http://www.developer.com/net/asp/article.php/3079381\" rel=\"noreferrer\">query</a> amazon.com, since they sell lots of software and provide public interfaces to access their database.</p>\n"
},
{
"answer_id": 276024,
"author": "sundar venugopal",
"author_id": 32670,
"author_profile": "https://Stackoverflow.com/users/32670",
"pm_score": 0,
"selected": false,
"text": "<p>here is the list of applications compatible with windows vista.</p>\n\n<p>there is a excel sheet out there at microsoft, you can find more software products.</p>\n\n<p><a href=\"http://www.iexbeta.com/wiki/index.php/Windows_Vista_Software_Compatibility_List\" rel=\"nofollow noreferrer\">http://www.iexbeta.com/wiki/index.php/Windows_Vista_Software_Compatibility_List</a></p>\n\n<p>hope this helps</p>\n"
},
{
"answer_id": 281772,
"author": "Brian Hasden",
"author_id": 28926,
"author_profile": "https://Stackoverflow.com/users/28926",
"pm_score": 2,
"selected": true,
"text": "<p>So, someone asked a question on reddit (<a href=\"http://www.reddit.com/r/programming/comments/7civs/ask_prog_where_can_i_find_lists_of_data_in_useful/\" rel=\"nofollow noreferrer\">http://www.reddit.com/r/programming/comments/7civs/ask_prog_where_can_i_find_lists_of_data_in_useful/</a>) that contained the original website I was looking for.</p>\n\n<p>Anyone looking for a database of general information (including the database of software I was looking for) can find it at <a href=\"http://www.freebase.com/\" rel=\"nofollow noreferrer\">http://www.freebase.com/</a>. </p>\n\n<p>There were also a couple other interesting open databases at <a href=\"http://infochimps.org/\" rel=\"nofollow noreferrer\">http://infochimps.org/</a>, <a href=\"http://theinfo.org/\" rel=\"nofollow noreferrer\">http://theinfo.org/</a> and <a href=\"http://www.datawrangling.com/some-datasets-available-on-the-web\" rel=\"nofollow noreferrer\">http://www.datawrangling.com/some-datasets-available-on-the-web</a></p>\n"
},
{
"answer_id": 1146995,
"author": "Colin Pickard",
"author_id": 12744,
"author_profile": "https://Stackoverflow.com/users/12744",
"pm_score": 1,
"selected": false,
"text": "<p>Secunia, the security company, has a tool called <a href=\"http://secunia.com/vulnerability_scanning/personal/\" rel=\"nofollow noreferrer\">Secunia PSI</a> that attempts to list all the software on a Windows computer and checks it against a database of known vulnerabilities, so you can keep your stuff up to date. This might have some overlap with what you are trying to do.</p>\n"
},
{
"answer_id": 47118501,
"author": "apk",
"author_id": 5104533,
"author_profile": "https://Stackoverflow.com/users/5104533",
"pm_score": 1,
"selected": false,
"text": "<p>If anyone's also looking, try <a href=\"https://wikidata.org\" rel=\"nofollow noreferrer\">wikidata.org</a> - they have a fantastic <a href=\"https://query.wikidata.org\" rel=\"nofollow noreferrer\">online query editor</a> you can use to probe around the data set.</p>\n\n<p>A quick query for a list of 13155 pieces of software along with the related programming language and operating system (with a lot of gaps and duplicates unfortunately, but still very workable):</p>\n\n<pre><code>SELECT ?monarch ?monarchLabel ?programming_language ?programming_languageLabel ?operating_system ?operating_systemLabel WHERE {\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],en\". }\n { ?monarch wdt:P31 wd:Q7397. } UNION { ?monarch wdt:P31 wd:Q40056. }\n OPTIONAL { ?monarch wdt:P277 ?programming_language. }\n OPTIONAL { ?monarch wdt:P306 ?operating_system. }\n}\n</code></pre>\n\n<p>Depending on what you're looking for you might want to include websites or other categories by adding more union cases, or add more properties (the query editor has great suggestions like <em>developer</em>, <em>license</em> and <em>use</em>).</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28926/"
] |
I'm looking for a database of commonly installed Windows software. At minimum I need the name of the software and the executable name, but it'd also be nice to have the publisher and the common installation path, etc. Basically, I'd like to be able to query it to find all the software by Adobe and the associated executable name, etc.
Basically I'm looking to be able to do
```
SELECT * FROM Software WHERE Publisher = 'Microsoft'
SELECT * FROM Software WHERE Executable = 'devenv.com'
```
I came across an effort to create such a database a long time ago, but can't seem to find it now. Maybe it fizzled out. Any help would be greatly appreciated. Thanks.
|
So, someone asked a question on reddit (<http://www.reddit.com/r/programming/comments/7civs/ask_prog_where_can_i_find_lists_of_data_in_useful/>) that contained the original website I was looking for.
Anyone looking for a database of general information (including the database of software I was looking for) can find it at <http://www.freebase.com/>.
There were also a couple other interesting open databases at <http://infochimps.org/>, <http://theinfo.org/> and <http://www.datawrangling.com/some-datasets-available-on-the-web>
|
223,096 |
<p>I'm running Oracle 10g and have columns with Type_Name </p>
<pre>TIMESTAMP(6) WITH TIME ZONE</pre>
<p>When inflated into java classes they come out as</p>
<pre>oracle.sql.TIMESTAMPTZ </pre>
<p>But DbUnit can't handle converting Oracle specific classes to Strings for writing to XML. I'm wondering if there's any easy way for me to convert (say, in my SELECT statement somehow) from these Oracle specific timestamps to something in java.sql.</p>
|
[
{
"answer_id": 224229,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 2,
"selected": false,
"text": "<p>Try messing with the device information settings, in particular the HumanReadiblePdf attribute. \n<a href=\"http://msdn.microsoft.com/en-us/library/ms154682.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms154682.aspx</a><br>\nIIRC the setting is actually the opposite of what the documentation hints at compression wise.</p>\n\n<p>Also take a look here: \n<a href=\"http://blogs.msdn.com/donovans/pages/reporting-services-pdf-renderer-faq.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/donovans/pages/reporting-services-pdf-renderer-faq.aspx</a></p>\n"
},
{
"answer_id": 21317497,
"author": "Code Maverick",
"author_id": 682480,
"author_profile": "https://Stackoverflow.com/users/682480",
"pm_score": 0,
"selected": false,
"text": "<p>It seems that this is still an issue in <strong>SSRS 2008 R2</strong>. The fix was to change my images from <strong>PNG</strong> to <strong>JPEG</strong>. <strong>@DanielAuger</strong> was heading in the right direction with his last link. I've included it again here with its title:</p>\n<h2><a href=\"http://blogs.msdn.com/b/donovans/archive/2007/07/20/reporting-services-pdf-renderer-faq.aspx\" rel=\"nofollow noreferrer\">Reporting Services: PDF Renderer FAQ</a></h2>\n<hr />\n<p>My answer was found in the following excerpt at the bottom of the aforementioned link:</p>\n<blockquote>\n<h2>I'm not using the controls in local mode and my PDFs are still big. Why?</h2>\n<p><strong>If your PDF contains charts or PNG images</strong>, those images may be translated into bitmaps before being added to the PDF file. Although this bitmap data will be recompressed, it will not be as space efficient as the original image. To avoid this translation, <strong>use JPEG images</strong> or PNG files of color type 3 (PNG color type information can be found at <a href=\"http://en.wikipedia.org/wiki/PNG\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/PNG</a>).</p>\n<p>Prior to Reporting Services 2005 SP1, PNG images of additional color types were allowed. Unfortunately, in order to fix a <strong>bug causing some PNGs to appear corrupted when rendered to PDF</strong> we needed to add the color type restriction. Even more unfortunate is the fact that charts are sent to the PDF renderer as non-color type 3 PNGs of high DPI. This is certainly a limitation we want to remove in the future but very unlikely it will be fixed in Reporting Services 2005.\n*.</p>\n<p><sub><em><strong>Note: emphasis mine.</strong></em></sub></p>\n</blockquote>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25915/"
] |
I'm running Oracle 10g and have columns with Type\_Name
```
TIMESTAMP(6) WITH TIME ZONE
```
When inflated into java classes they come out as
```
oracle.sql.TIMESTAMPTZ
```
But DbUnit can't handle converting Oracle specific classes to Strings for writing to XML. I'm wondering if there's any easy way for me to convert (say, in my SELECT statement somehow) from these Oracle specific timestamps to something in java.sql.
|
Try messing with the device information settings, in particular the HumanReadiblePdf attribute.
<http://msdn.microsoft.com/en-us/library/ms154682.aspx>
IIRC the setting is actually the opposite of what the documentation hints at compression wise.
Also take a look here:
<http://blogs.msdn.com/donovans/pages/reporting-services-pdf-renderer-faq.aspx>
|
223,115 |
<p>Having difficulty articulating this correlated subquery. I have two tables fictitious tables, foo and bar. foo has two fields of foo_id and total_count. bar has two fields, seconds and id.</p>
<p>I need to aggregate the seconds in bar for each individual id and update the total_count in foo. id is a foreign key in bar for foo_id.</p>
<p>I've tried something similar without much luck:</p>
<pre><code>UPDATE foo f1 set total_count = (SELECT SUM(seconds) from bar b1 INNER JOIN foo f2 WHERE b1.foo_id = f2.id) WHERE f1.foo_id = bar.id;
</code></pre>
|
[
{
"answer_id": 223154,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 0,
"selected": false,
"text": "<p>I hope I understood your question right.</p>\n\n<p>You have the following tables:</p>\n\n<ul>\n<li>table <code>foo</code> - columns: <code>id</code> and <code>total_count</code></li>\n<li>table <code>bar</code> - columns: <code>foo_id</code> (references <code>foo.id</code>) and <code>seconds</code></li>\n</ul>\n\n<p>The following query should work (update all <code>total_count</code> rows in table <code>foo</code>):</p>\n\n<pre><code>UPDATE foo AS f1\nSET total_count = (\n SELECT SUM(seconds) \n FROM bar INNER JOIN foo \n WHERE foo_id = f1.id\n);\n</code></pre>\n\n<p>I'm not sure what you are trying to do with your last <code>WHERE</code> clause (<code>WHERE f1.foo_id = bar.id;</code>).</p>\n"
},
{
"answer_id": 223161,
"author": "Adam",
"author_id": 30084,
"author_profile": "https://Stackoverflow.com/users/30084",
"pm_score": 2,
"selected": true,
"text": "<pre><code>UPDATE foo f1\nSET total_count = (SELECT SUM(seconds)\nFROM bar b1 WHERE b1.id = f1.foo_id)\n</code></pre>\n\n<p>You should have access to the appropriate foo id within the sub-query, so there is no need to join in the table.</p>\n"
},
{
"answer_id": 223174,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 0,
"selected": false,
"text": "<p>This really opens the door to consistency issues. You might consider creating a view rather than mutating the foo table:</p>\n\n<pre><code>CREATE VIEW foo AS\nSELECT id, sum(seconds) from bar group by id;\n</code></pre>\n"
},
{
"answer_id": 223544,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "<p>Just to offer an alternative, I like to use MySQL's nifty multi-table updates feature:</p>\n\n<pre><code>UPDATE foo SET total_count = 0;\n\nUPDATE foo JOIN bar ON (foo.foo_id = bar.id)\n SET foo.total_count = foo.total_count + bar.seconds;\n</code></pre>\n"
},
{
"answer_id": 273268,
"author": "user35593",
"author_id": 35593,
"author_profile": "https://Stackoverflow.com/users/35593",
"pm_score": 1,
"selected": false,
"text": "<p>In larger data sets, correlated subqueries can be very resource-intensive. Joining to a derived table containing the appropriate aggregates can be much more efficient: </p>\n\n<pre><code>create table foo ( foo_id int identity, total_count int default 0 )\ncreate table bar ( foo_id int, seconds int )\n\ninsert into foo default values\ninsert into foo default values\ninsert into foo default values\n\ninsert into bar values ( 1, 10 )\ninsert into bar values ( 1, 11 )\ninsert into bar values ( 1, 12 )\n /* total for foo_id 1 = 33 */\ninsert into bar values ( 2, 10 )\ninsert into bar values ( 2, 11 )\n /* total for foo_id 2 = 21 */\ninsert into bar values ( 3, 10 )\ninsert into bar values ( 3, 19 )\n /* total for foo_id 3 = 29 */\n\nselect *\nfrom foo\n\nfoo_id total_count\n----------- -----------\n1 0\n2 0\n3 0\n\nupdate f\nset total_count = sumsec\nfrom foo f\n inner join (\n select foo_id\n , sum(seconds) sumsec\n from bar\n group by foo_id\n ) a\n on f.foo_id = a.foo_id\n\nselect *\nfrom foo\n\nfoo_id total_count\n----------- -----------\n1 33\n2 21\n3 29\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Having difficulty articulating this correlated subquery. I have two tables fictitious tables, foo and bar. foo has two fields of foo\_id and total\_count. bar has two fields, seconds and id.
I need to aggregate the seconds in bar for each individual id and update the total\_count in foo. id is a foreign key in bar for foo\_id.
I've tried something similar without much luck:
```
UPDATE foo f1 set total_count = (SELECT SUM(seconds) from bar b1 INNER JOIN foo f2 WHERE b1.foo_id = f2.id) WHERE f1.foo_id = bar.id;
```
|
```
UPDATE foo f1
SET total_count = (SELECT SUM(seconds)
FROM bar b1 WHERE b1.id = f1.foo_id)
```
You should have access to the appropriate foo id within the sub-query, so there is no need to join in the table.
|
223,126 |
<p>I'm new to Rails development, and I'm trying to figure out how to use an older version of Rails with Apatana's RadRails IDE. I'm trying to help out a friend who has a site built on older version than the one that automatically gets downloaded by RadRails, and I'm pretty sure the two versions wouldn't be compatible (the site is using some pre 2.0 version, not sure of the exact number offhand).</p>
<p>Is there a way to tell RadRails to get and use a specific version of Rails? Or is there something I can do at the command line to change the installed version of Rails? I'm only vaguely familiar with the "gem" package system, but I'm assuming it would involve that.</p>
<p>Any help would be much appreciated!</p>
|
[
{
"answer_id": 226219,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 3,
"selected": true,
"text": "<p>Use the Rake task <code>rails:freeze:gems</code> in your rails project and give it the version you want to use. For example:</p>\n\n<pre><code>rake rails:freeze:gems VERSION=2.1.0\n</code></pre>\n\n<p>That will put the right version of Rails into <code>vendor/rails</code>, which is loaded by default if it exists.</p>\n"
},
{
"answer_id": 261753,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to freeze the gem into your project (using rake rails:freeze:gems), you can install the rails gem of the version you want to use:</p>\n\n<p><code>gem install rails -v 2.0.2</code></p>\n\n<p>and then specify the rails gem to use in your config/environment.rb:</p>\n\n<p><code>RAILS_GEM_VERSION = '2.0.2'</code></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
] |
I'm new to Rails development, and I'm trying to figure out how to use an older version of Rails with Apatana's RadRails IDE. I'm trying to help out a friend who has a site built on older version than the one that automatically gets downloaded by RadRails, and I'm pretty sure the two versions wouldn't be compatible (the site is using some pre 2.0 version, not sure of the exact number offhand).
Is there a way to tell RadRails to get and use a specific version of Rails? Or is there something I can do at the command line to change the installed version of Rails? I'm only vaguely familiar with the "gem" package system, but I'm assuming it would involve that.
Any help would be much appreciated!
|
Use the Rake task `rails:freeze:gems` in your rails project and give it the version you want to use. For example:
```
rake rails:freeze:gems VERSION=2.1.0
```
That will put the right version of Rails into `vendor/rails`, which is loaded by default if it exists.
|
223,149 |
<p>Say you create a form using ASP.NET MVC that has a dynamic number of form elements.</p>
<p>For instance, you need a checkbox for each product, and the number of products changes day by day.</p>
<p>How would you handle that form data being posted back to the controller? You can't set up parameters on the action method because you don't know how many form values are going to be coming back.</p>
|
[
{
"answer_id": 223158,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on your data, you could either output a 'CheckboxList' (which is not possible in the newer versions any more) and use a <code>string[]</code> parameter, or you could set up multiple forms and just modify the action.</p>\n"
},
{
"answer_id": 223168,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 4,
"selected": true,
"text": "<p>Just give each checkbox a unique name value:</p>\n\n<pre><code><input class=\"approveCheck\" id=\"<%= \"approveCheck\" + recordId %>\" \n name=\"<%= \"approveCheck\" + recordId %>\" type=\"checkbox\" />\n</code></pre>\n\n<p>Then parse the list of form values in the Action, after submit:</p>\n\n<pre><code>foreach (var key in Request.Form.Keys)\n {\n string keyString = key.ToString();\n if (keyString.StartsWith(\"approveCheck\", StringComparison.OrdinalIgnoreCase))\n {\n string recNum = keyString.Substring(12, keyString.Length - 12);\n\n string approvedKey = Request.Form[\"approveCheck\" + recNum];\n bool approved = !String.IsNullOrEmpty(approvedKey);\n // ...\n</code></pre>\n\n<p>You don't need to pass form values as arguments; you can just get them from Request.Form.</p>\n\n<p>One other option: write a model binder to change the list into a custom type for form submission.</p>\n"
},
{
"answer_id": 223202,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 2,
"selected": false,
"text": "<p>Per Craig's answer.. that is safer. There are quirks to posting multiple form elements with the same name. I would add that it would be wise to wrap the logic that makes the \"collection\" of controls in a way similar to WebForms. Web Forms prepend the container control's name and adds an index. For example, in a Repeater the form elements inside would be named (something like) RepeaterName_Element1, RepeaterName_Element2. When you go to get the elements out, you have to use FindControl or something of the sort.</p>\n"
},
{
"answer_id": 223262,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on the binders you are using, this should work:</p>\n\n<pre><code><%var i = 0;\n foreach (var product (IList<ProductSelection>)ViewData[\"products\"]) {%>\n <%=Html.Hidden(string.Format(\"products[{0}].Id\", i), product.Id)%>\n <%=Html.Checkbox(string.Format(\"products[{0}].Selected\", i))%>\n <%=product.Name%><br/>\n<%}%>\n</code></pre>\n\n<p>...which will result in HTML something like this (notice the array notation on the names):</p>\n\n<pre><code><input name=\"products[0].Id\" type=\"hidden\" value=\"123\">\n<input name=\"products[0].Selected\" type=\"checkbox\">\nWidget\n<input name=\"products[1].Id\" type=\"hidden\" value=\"987\">\n<input name=\"products[1].Selected\" type=\"checkbox\">\nGadget\n</code></pre>\n\n<p>...and the controller method that handles the post:</p>\n\n<pre><code>public ActionResult SelectProducts(IList<ProductSelection> products)\n{\n ...\n}\n</code></pre>\n\n<p>Upon binding, products parameter will contain two instances of ProductSelection. </p>\n\n<p>One caveat is that I have not used the new default binding for complex objects. Rather I am using either the NameValueDeserializer or CastleBind, both from MvcContrib. They both behave this way. I am guessing binding in the Beta will work the same way.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7837/"
] |
Say you create a form using ASP.NET MVC that has a dynamic number of form elements.
For instance, you need a checkbox for each product, and the number of products changes day by day.
How would you handle that form data being posted back to the controller? You can't set up parameters on the action method because you don't know how many form values are going to be coming back.
|
Just give each checkbox a unique name value:
```
<input class="approveCheck" id="<%= "approveCheck" + recordId %>"
name="<%= "approveCheck" + recordId %>" type="checkbox" />
```
Then parse the list of form values in the Action, after submit:
```
foreach (var key in Request.Form.Keys)
{
string keyString = key.ToString();
if (keyString.StartsWith("approveCheck", StringComparison.OrdinalIgnoreCase))
{
string recNum = keyString.Substring(12, keyString.Length - 12);
string approvedKey = Request.Form["approveCheck" + recNum];
bool approved = !String.IsNullOrEmpty(approvedKey);
// ...
```
You don't need to pass form values as arguments; you can just get them from Request.Form.
One other option: write a model binder to change the list into a custom type for form submission.
|
223,153 |
<p>I am trying to call a COM object from PHP using the COM interop extension. One function requires an OLE_COLOR as an argument? Is there any way to pass this kind of value from PHP?</p>
<p>I have tried passing a simple integer value with no success.</p>
<pre><code>$this->oBuilder->Font->Color = 255;
</code></pre>
|
[
{
"answer_id": 230602,
"author": "matt.mercieca",
"author_id": 30407,
"author_profile": "https://Stackoverflow.com/users/30407",
"pm_score": 0,
"selected": false,
"text": "<p>When I've called COM functions from PHP, I just passed them in the call. So my old code has:</p>\n\n<pre>\n$myComObject = new COM(\"MY_COM_OBJECT\");\n$myComObject->Myfunction( myVar1, myVar2, 'my string var');\n</pre>\n"
},
{
"answer_id": 432916,
"author": "Bob Fanger",
"author_id": 19165,
"author_profile": "https://Stackoverflow.com/users/19165",
"pm_score": 2,
"selected": true,
"text": "<p>PHP can define the constants the COM exposes automatic.</p>\n\n<p>set_ini('<a href=\"http://php.net/manual/en/com.configuration.php#ini.com.autoregister-typelib\" rel=\"nofollow noreferrer\">com.autoregister-typelib</a>', true);</p>\n\n<p>or by hand </p>\n\n<p><a href=\"http://php.net/manual/en/function.com-load-typelib.php\" rel=\"nofollow noreferrer\">com_load_typelib</a>($typelib_name);</p>\n\n<p>But if the OLE_COLOR is a <strong>object</strong> instead of an integer, string or other primitive<br>\nusing constants (or integers) won't work.</p>\n\n<pre><code>$Color = new COM('ColorClass');\n$Color->set_color_function($red, $green, $blue);\n</code></pre>\n\n<p>Or something similar will.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] |
I am trying to call a COM object from PHP using the COM interop extension. One function requires an OLE\_COLOR as an argument? Is there any way to pass this kind of value from PHP?
I have tried passing a simple integer value with no success.
```
$this->oBuilder->Font->Color = 255;
```
|
PHP can define the constants the COM exposes automatic.
set\_ini('[com.autoregister-typelib](http://php.net/manual/en/com.configuration.php#ini.com.autoregister-typelib)', true);
or by hand
[com\_load\_typelib](http://php.net/manual/en/function.com-load-typelib.php)($typelib\_name);
But if the OLE\_COLOR is a **object** instead of an integer, string or other primitive
using constants (or integers) won't work.
```
$Color = new COM('ColorClass');
$Color->set_color_function($red, $green, $blue);
```
Or something similar will.
|
223,162 |
<p>How do I pull out the filename from a full path using regular expressions in C#?</p>
<p>Say I have the full path <code>C:\CoolDirectory\CoolSubdirectory\CoolFile.txt</code>.</p>
<p>How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figure this one out.</p>
<p>Also, in the course of trying to solve this problem, I realized that I can just use <code>System.IO.Path.GetFileName</code>, but the fact that I couldn't figure out the regular expression is just making me unhappy and it's going to bother me until I know what the answer is.</p>
|
[
{
"answer_id": 223172,
"author": "Dour High Arch",
"author_id": 22437,
"author_profile": "https://Stackoverflow.com/users/22437",
"pm_score": 5,
"selected": false,
"text": "<p>Why must you use regular expressions? .NET has the built-in <code>Path.GetFileName()</code> method specifically for this which works across platforms and filesystems.</p>\n"
},
{
"answer_id": 223176,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": true,
"text": "<pre><code>// using System.Text.RegularExpressions;\n\n/// <summary>\n/// Regular expression built for C# on: Tue, Oct 21, 2008, 02:34:30 PM\n/// Using Expresso Version: 3.0.2766, http://www.ultrapico.com\n/// \n/// A description of the regular expression:\n/// \n/// Any character that is NOT in this class: [\\\\], any number of repetitions\n/// End of line or string\n/// \n///\n/// </summary>\npublic static Regex regex = new Regex(\n @\"[^\\\\]*$\",\n RegexOptions.IgnoreCase\n | RegexOptions.CultureInvariant\n | RegexOptions.IgnorePatternWhitespace\n | RegexOptions.Compiled\n );\n</code></pre>\n\n<p><strong>UPDATE:</strong> removed beginning slash</p>\n"
},
{
"answer_id": 223178,
"author": "Seth Petry-Johnson",
"author_id": 23632,
"author_profile": "https://Stackoverflow.com/users/23632",
"pm_score": 3,
"selected": false,
"text": "<p>Here's one approach:</p>\n\n<pre><code>string filename = Regex.Match(filename, @\".*\\\\([^\\\\]+$)\").Groups[1].Value;\n</code></pre>\n\n<p>Basically, it matches everything between the very last backslash and the end of the string. Of course, as you mentioned, using Path.GetFileName() is much easier and will handle lots of edge cases that are a pain to handle with regex.</p>\n"
},
{
"answer_id": 223180,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 1,
"selected": false,
"text": "<pre><code>\\w+:\\\\(\\w+\\\\)*(?<file>\\w*\\.\\w*)\n</code></pre>\n\n<p>This obviously would need expanding to cover all path characters, but the named group \"file\" contains your filename for the example path given.</p>\n"
},
{
"answer_id": 223214,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 3,
"selected": false,
"text": "<p>Shorter:</p>\n\n<pre><code>string filename = Regex.Match(fullpath, @\"[^\\\\]*$\").Value;\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>string filename = Regex.Match(fullpath, \"[^\\\\\"+System.IO.Path.PathSeparator+\"]*$\").Value;\n</code></pre>\n\n<p>Without <code>Regex</code>:</p>\n\n<pre><code>string[] pathparts = fullpath.Split(new []{System.IO.Path.PathSeparator});\nstring file = pathparts[pathparts.Length-1];\n</code></pre>\n\n<p>The official library support you mentioned:</p>\n\n<pre><code>string file = System.IO.Path.GetFileName(fullpath);\n</code></pre>\n"
},
{
"answer_id": 224566,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 0,
"selected": false,
"text": "<p>You should rather use the System.Path class. It will mean you will have to worry about less if you ever decide to support Mono/Linux (dlamblin's example takes the path seperator into account, but you may get a strange OS that has strange paths). The System.Path class can also combine two paths into one. So for example:</p>\n\n<pre><code>Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), \"My App Stuff\");\n</code></pre>\n\n<p>would resolve to:</p>\n\n<ul>\n<li>Windows: C:\\Documents and Settings\\[User]\\My Documents\\My App Stuff</li>\n<li>Linux: /[User]/My App Stuff</li>\n</ul>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18927/"
] |
How do I pull out the filename from a full path using regular expressions in C#?
Say I have the full path `C:\CoolDirectory\CoolSubdirectory\CoolFile.txt`.
How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figure this one out.
Also, in the course of trying to solve this problem, I realized that I can just use `System.IO.Path.GetFileName`, but the fact that I couldn't figure out the regular expression is just making me unhappy and it's going to bother me until I know what the answer is.
|
```
// using System.Text.RegularExpressions;
/// <summary>
/// Regular expression built for C# on: Tue, Oct 21, 2008, 02:34:30 PM
/// Using Expresso Version: 3.0.2766, http://www.ultrapico.com
///
/// A description of the regular expression:
///
/// Any character that is NOT in this class: [\\], any number of repetitions
/// End of line or string
///
///
/// </summary>
public static Regex regex = new Regex(
@"[^\\]*$",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
```
**UPDATE:** removed beginning slash
|
223,187 |
<pre><code>SqlConnection connection = new SqlConnection(FROM_CONFIGURATION)
SqlCommand command = new SqlCommand("SomeSQL", connection);
connection.Open();
command.ExecuteNonQuery();
command.Dispose();
connection.Dispose();
</code></pre>
<p>It is recommended that the code above should include try/catch (or using) so that if an exception is thrown, all resources are disposed properly.</p>
<p>But if you have to worry about disposing stuff manually, then what's the point of the GC?! Isn't GC there to take care of this for the coder?</p>
|
[
{
"answer_id": 223197,
"author": "zappan",
"author_id": 4723,
"author_profile": "https://Stackoverflow.com/users/4723",
"pm_score": 1,
"selected": false,
"text": "<p>the above-mentioned code releases acquired resources (although, i don't believe you should be calling the Dispose() method by yourself, by releasing the resources is meant closing streams and stuff like that). GC removes object from memory (deallocates memory used by the object), but it can be done only after resources have been freed by the object.</p>\n"
},
{
"answer_id": 223200,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>But if you have to worry about\n disposing stuff manually, then what's\n the point of the GC?! Isn't GC there\n to take care of this for the coder?</p>\n</blockquote>\n\n<p>The problem is you have no idea <strong>when</strong> the GC will run. And if your application never pressures memory, it may not run at all.</p>\n"
},
{
"answer_id": 223204,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not so sure about c#, which is what this looks like, but typically, the garbage collector manages memory. This connection, in addition to the object memory, has server resources. The database, which is in a separate process, has to maintain a connection. The close cleans those up.</p>\n"
},
{
"answer_id": 223205,
"author": "JFV",
"author_id": 1391,
"author_profile": "https://Stackoverflow.com/users/1391",
"pm_score": 0,
"selected": false,
"text": "<p>GC does take care of disposing objects, but the disposal may not happen right away. Manually disposing the objects will free up memory faster.</p>\n"
},
{
"answer_id": 223209,
"author": "Larsenal",
"author_id": 337,
"author_profile": "https://Stackoverflow.com/users/337",
"pm_score": 0,
"selected": false,
"text": "<p>The GC is limited when it comes to freeing external resources such as DB connections or file handles. However, for allocating memory within the .NET world, it takes care of a lot of the mundane memory management tasks.</p>\n"
},
{
"answer_id": 223213,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": false,
"text": "<p>Because GC isn't the most efficient - it doesn't always occur as soon as the resource is no longer used. So when you're dealing with unmanaged resources like file I/O, DB connections, etc. it's best practice to release/clean up those resources before waiting and relying on GC to take care of it. </p>\n\n<p>And look into using the <code>using</code> keyword:</p>\n\n<pre><code>using (SqlConnection connection = new SqlConnection(FROM_CONFIGURATION))\nusing (SqlCommand command = new SqlCommand(\"SomeSQL\", connection))\n{\n connection.Open(); \n command.ExecuteNonQuery(); \n command.Dispose(); \n connection.Dispose();\n}\n</code></pre>\n\n<p>Also, as a general rule, whatever can be disposed, should be in a <code>using</code> block.</p>\n"
},
{
"answer_id": 223216,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 2,
"selected": false,
"text": "<p>Objects that implement IDisposable are trying to tell you that they have linkages to structures that aren't managed memory. The garbage collector runs in batches in order to improve efficiency. But that means it may be awhile before your object is disposed of, meaning you'll be holding onto resources longer than you should be which may have negative effects on performance/reliability/scalability.</p>\n"
},
{
"answer_id": 223222,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 4,
"selected": false,
"text": "<p>As other people here said the GC is non-deterministic, so you don't know when your object will be collected. What I want to clarify is that this is not a problem with the memory, but with the system resources (opened files, database connections) which are expensive and should be released asap. Dispose lets you do that when you know you're no longer using the connection. If they are not released in time the system might run out of those resources and the GC isn't aware of that. That's why you have to do it manually.</p>\n\n<p>Also I want to add that using the 'using' statement will do it for you in a nicely way.</p>\n"
},
{
"answer_id": 223225,
"author": "IAmCodeMonkey",
"author_id": 27613,
"author_profile": "https://Stackoverflow.com/users/27613",
"pm_score": 2,
"selected": false,
"text": "<p>The GC runs occasionally and takes care of memory management keeping everything nice and tidy for you. You may think it is useless when you see fragments of code like the one you posted, but more often than not, it saves you a lot of headaches (think C/C++ manual memory management) since it greatly reduces memory leaks and lets you worry about how your application will run and not how you will manage memory. Disposing of file handles and databases connections is a way of increasing efficiency since garbage collection is not deterministic and may not happen right away, and you don't want those file handles and open database connections sapping your systems performance. Btw, your code really is ugly, I always advocate the using statement and frequently write my db code like this:</p>\n\n<pre><code>using (SqlConnection connection = new SqlConnection(...))\nusing (SqlCommand command = connection.CreateCommand())\n{\n ...\n}\n</code></pre>\n\n<p>This automatically calls dispose on the connection and command objects when they fall out of scope which is when execution leaves the block.</p>\n"
},
{
"answer_id": 223226,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>The garbage collector (GC) in .NET is a core part of the .NET Common Language Runtime (CLR) and is available to all .NET programming languages. The GC was never meant to manage resources; it was designed to manage memory allocation, and it does an excellent job at managing memory allocated directly to native .NET objects. It was not designed to deal with unmanaged memory and operating system allocated memory, so it becomes the responsibility of the developer to manage these resources.</p>\n\n<p>In the specific case of database connections, you are dealing with other resources than just memory - specifically connection pools, possible implicit transaction scopes, etc. By calling Close() and/or Dispose() you are explicitly telling the object to release those unmanaged resources immediately while the managed resources will wait for a GC cycle to occur.</p>\n"
},
{
"answer_id": 223232,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 3,
"selected": false,
"text": "<p>Garbage collection is here to take care of releasing unused <strong>memory</strong>.</p>\n\n<p>There are various reasons why extending GC to release other resources is problematic. One of them is that finalizers (methods that are executed when an object is being garbage collected) make reference cycles uncollectable, unless you strongly constrain dereferencing from finalizers, which makes them very tricky to use.</p>\n\n<p>Another reason is that most resources need to be deallocated in some sort of timely manner, which is not possible when relying on garbage collection.</p>\n\n<p>Yet another reason is that limiting GC to memory management deals with the <em>vast bulk</em> of resource management in any application, and almost all of the <em>non interesting</em> resource management. Other resources are usually interesting enough do deserve \nsome additional code to be explicit about how they are released.</p>\n\n<p>And another reason is that in some applications, GC makes the application go faster because it reduces the amount of copying done to cater for ownership semantics. Which is not a concern for other resources.</p>\n\n<p>Other people could go on like this for hours.</p>\n"
},
{
"answer_id": 223233,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 0,
"selected": false,
"text": "<p>The above provides an example of when natively allocated memory or resources wander into the managed world as a handle. In this scenario because the managed world did not allocate the memory it cannot \"auto-tidy\" it. The memory/resources has to be explicitly disposed or at the very least disposed within a finaliser.</p>\n\n<p>In the vast majority of cases though, especially when talking about the code critical to most companies core aims (yeh business logicks) you don't have to worry about this kind of thing and less code means less mistakes.</p>\n"
},
{
"answer_id": 223260,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 3,
"selected": false,
"text": "<p>Suppose I have this code:</p>\n\n<pre><code>class MonkeyGrabber : IDisposable {\n public MonkeyGrabber() { /* construction grabs a real, live monkey from the cage */\n public void Dispose() { Dispose(true); /* releases the monkey back into the cage */ }\n // the rest of the monkey grabbing is left as an exercise to grad student drones\n}\n\nclass MonkeyMonitor {\n public void CheckMonkeys() {\n if (_monkeyPool.GettingTooRowdy()) {\n MonkeyGrabber grabber = new MonkeyGrabber();\n grabber.Spank();\n }\n }\n}\n</code></pre>\n\n<p>Now, my MonkeyMonitor checks the monkeys and if they're too rowdy, it gets a valuable system resource - a single monkey grabbing claw attached to the system, and uses it to grab a monkey and spank it. Since I didn't dispose it, the monkey claw is still holding onto the monkey dangling it above the rest cage. If the rest of the monkeys continue to get rowdy, I can't make a new MonkeyGrabber as it is still help up. Oops. A contrived example, but you get the point: Objects that implement IDisposable may hold onto limited resources that should be released in a timely manner. The GC may let go eventually or not.</p>\n\n<p>In addition, some resources need to be released in a timely manner. I have a set of classes that if they are not disposed by either app or GC before the application exits will cause the app to crash hard, as the unmanaged resource manager from which they came is already gone by the time the GC gets around to it.</p>\n\n<p><a href=\"http://www.atalasoft.com/cs/blogs/stevehawley/archive/2006/09/21/10887.aspx\" rel=\"nofollow noreferrer\">More on IDisposable</a>.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/212198/what-is-the-c-using-block-and-why-should-i-use-it#212210\">using is your friend</a> - it's the closest we have so far to <a href=\"http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"nofollow noreferrer\">RAII</a>.</p>\n"
},
{
"answer_id": 223286,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>...The GC was never meant to manage resources; it was designed to manage memory allocation ...\n In the specific case of database connections, you are dealing with other resources than just memory... (Scott Dorman)</p>\n</blockquote>\n\n<p>The OP didn't tag with a specific platform, though most of the answers have been .net-specific, noting that GC is mainly for avoiding memory leaks, but extensions such as <code>using</code> expressions and <code>IDisposable</code> can help a lot.</p>\n\n<p>Other platforms offer other solutions. For example, in C++, there is no (built-in) garbage collection, but some forms of shared pointers can be used to help with memory management, and the RAII-style of coding can be extremely helpful in managing other types of resources. </p>\n\n<p>In cPython, two different garbage collection systems are used. A referencing counting implementation immediately calls destructors when the last reference is deleted. For common \"stack\" objects, this means that they get cleaned up immediately, like what happens for C++ RAII objects. The downside is that if you have a reference cycle, the reference counting collector will never dispose of the object. As a result, they have a secondary non-deterministic garbage collector that works like Java and .NET collectors. Like .NET with its using statements, cPython tries to handle the most common cases.</p>\n\n<p>So, to answer the OP, non-deterministic garbage collection helps simplify memory management, it can be used to handle other resources too as long as timeliness isn't an issue, and another mechanism (such as careful programming, reference counting GC, a using statement, or real RAII objects) are needed when timely releasing of other resources is needed.</p>\n"
},
{
"answer_id": 224394,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Ah I see now. I confused memory management with unmanaged resource management. \nThanks for the clarification!</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
SqlConnection connection = new SqlConnection(FROM_CONFIGURATION)
SqlCommand command = new SqlCommand("SomeSQL", connection);
connection.Open();
command.ExecuteNonQuery();
command.Dispose();
connection.Dispose();
```
It is recommended that the code above should include try/catch (or using) so that if an exception is thrown, all resources are disposed properly.
But if you have to worry about disposing stuff manually, then what's the point of the GC?! Isn't GC there to take care of this for the coder?
|
As other people here said the GC is non-deterministic, so you don't know when your object will be collected. What I want to clarify is that this is not a problem with the memory, but with the system resources (opened files, database connections) which are expensive and should be released asap. Dispose lets you do that when you know you're no longer using the connection. If they are not released in time the system might run out of those resources and the GC isn't aware of that. That's why you have to do it manually.
Also I want to add that using the 'using' statement will do it for you in a nicely way.
|
223,189 |
<p>How can I create a Delphi TSpeedButton or SpeedButton in C# 2.0?</p>
|
[
{
"answer_id": 224188,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 0,
"selected": false,
"text": "<p>Does <a href=\"https://stackoverflow.com/questions/148729/how-to-setchangeremove-focus-style-on-a-button-in-c\">this</a> help? Looks like you would have to handle the OnPaint event, and not take focus...</p>\n"
},
{
"answer_id": 224954,
"author": "Osama Al-Maadeed",
"author_id": 25544,
"author_profile": "https://Stackoverflow.com/users/25544",
"pm_score": 0,
"selected": false,
"text": "<p>The regular .net 2.0 button supports part of what a TSpeedbutton Does:</p>\n\n<ul>\n<li>The Glyph: <strong>Image</strong></li>\n<li>Flat : <strong>FlatStyle</strong></li>\n</ul>\n\n<p>It does not handle:</p>\n\n<ul>\n<li>Down </li>\n<li>Group </li>\n</ul>\n\n<p>These two are related, you could inherit from the button, and ownerdraw it, adding Down and Group features.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/buttons/od_buttons.aspx\" rel=\"nofollow noreferrer\">Codeproject has an example</a> of ownerdraw buttons.</p>\n"
},
{
"answer_id": 225039,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 2,
"selected": false,
"text": "<p>I'm wondering if you want to create a control like a TSpeedButton, or you just need same kind of end result ...</p>\n\n<p>Programming one from scratch is certainly possible, but I'd only tackle that as a learning exercise.</p>\n\n<p>Assuming you want to achieve a similar end result ...</p>\n\n<p>Delphi's TSpeedButton had a differences from the standard TButton that developers found useful - it was flat, didn't take focus, and it consumed fewer resources than a regular button (because it didn't have an underlying Windows Handle).</p>\n\n<p>Which of these are important to you?</p>\n\n<p>If you just want a flat button that doesn't accept focus, use a regular Button with FlatStyle=Flat (or PopUp) and TabStop=false. You can configure a glyph by setting either the Image property, or a combination of ImageList and ImageIndex/ImageKey.</p>\n\n<p>An alternative to this would be to look for an existing button component that comes close to your needs - one place to look might be the Krypton Toolkit (free to use, see <a href=\"http://www.componentfactory.com/toolkit_buttoncontrols.php\" rel=\"nofollow noreferrer\">http://www.componentfactory.com/toolkit_buttoncontrols.php</a>).</p>\n\n<p>If you're wanting to reduce the number of resources consumed by your application, it's likely you'll get a better return looking elsewhere. </p>\n\n<p>Back in the days of Windows 3.1 (Delphi 1) and Windows 95 (Delphi 2), the number of available handles was strictly limited, with a maximum number available system wide. Today, with Windows XP and Vista, the number of available handles is far far higher, and the number is per process, not system wide. Unless you're creating thousands upon thousands of buttons, you're very unlikely to come anywhere close to running out.</p>\n"
},
{
"answer_id": 2244350,
"author": "reSPAWNed",
"author_id": 71793,
"author_profile": "https://Stackoverflow.com/users/71793",
"pm_score": 3,
"selected": false,
"text": "<p>Using a Button and setting the TabStop property to false only works when tapping through the form...</p>\n\n<p>If you need (as I did) a button that does not get selected when clicking on it, there is only one way I have found to do it.</p>\n\n<p>The way I did it, was to subclass the Button class and in the constructor calling the SetStyles and thereby setting Selectable to false, like so:</p>\n\n<pre><code>public class ButtonNoFocus : Button\n{\n public ButtonNoFocus()\n : base()\n {\n base.SetStyle(ControlStyles.Selectable, false);\n }\n}\n</code></pre>\n\n<p>This worked out for me, and is perfect if you e.g. have a control-panel with buttons that perform actions to a selected object...</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I create a Delphi TSpeedButton or SpeedButton in C# 2.0?
|
Using a Button and setting the TabStop property to false only works when tapping through the form...
If you need (as I did) a button that does not get selected when clicking on it, there is only one way I have found to do it.
The way I did it, was to subclass the Button class and in the constructor calling the SetStyles and thereby setting Selectable to false, like so:
```
public class ButtonNoFocus : Button
{
public ButtonNoFocus()
: base()
{
base.SetStyle(ControlStyles.Selectable, false);
}
}
```
This worked out for me, and is perfect if you e.g. have a control-panel with buttons that perform actions to a selected object...
|
223,190 |
<p>I have a flat-file schema that has a header and detail records. It looks something like this:</p>
<pre><code>HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
</code></pre>
<p>I need to append two blank lines at the end of the message. Right now, if I have multiple records I get the following output:</p>
<pre><code>HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
</code></pre>
<p>What I want to see happen is something like this:</p>
<pre><code>HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
</code></pre>
<p>I could build a custom pipeline component to do this, but I'm wondering if there is a simpler way of getting what I need?</p>
|
[
{
"answer_id": 223827,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For anybody who cares, I finally caved in and wrote a custom pipeline component to accomplish this.</p>\n"
},
{
"answer_id": 224004,
"author": "David Hall",
"author_id": 2660,
"author_profile": "https://Stackoverflow.com/users/2660",
"pm_score": 3,
"selected": true,
"text": "<p>You should be able to accomplish what you want by using the Delimiter properties of the flat file schema.</p>\n\n<p>Based on your example file I created a schema with the following record structure:</p>\n\n<pre>\n<Schema> \n <Root> \n <HDRGroup> \n <HDR> \n <LIN> \n</pre>\n\n<p>If you click on the root node of your schema you should see a list of properties for this root node. One properties section has the header 'Flat File'. In this flat file section the first three properties you can set are Child Delimiter, Child Delimiter Type and Child Order.</p>\n\n<p>This is where you configure the schema to create the blank lines (in this case CR LF but you can set different things as you need) For your example I set the following:</p>\n\n<pre>\nChild Delimiter: 0x0D 0x0A 0x0D 0x0A \nChild Delimiter Type: Hexadecimal \nChild Order: Infix\n</pre>\n\n<p>0x0D 0x0A is a carriage return line feed, so the above simply creates two blank lines, infixed between each child of the root node.</p>\n\n<p>The <HDRGroup> then functions to make sure that each header and its lines is kept together. For its delimiter settings I set:</p>\n\n<pre>\nChild Delimiter: 0x0D 0x0A \nChild Delimiter Type: Hexadecimal \nChild Order: Postfix\n</pre>\n\n<p>The <HDR> and <LIN> records then contain the actual schema definition for your message lines, delimited with an asterisk.</p>\n\n<p>This schema works for something that looks to me like what you have asked for - this sort of flatfile schema and how it parses a file is highly dependant of the little details, however, such as what type of line breaks there are and if there are line breaks at the end of the file. </p>\n\n<p>The princples of using the delimiters will stand, you will likely find you need to tinker with the settings.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a flat-file schema that has a header and detail records. It looks something like this:
```
HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
```
I need to append two blank lines at the end of the message. Right now, if I have multiple records I get the following output:
```
HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
```
What I want to see happen is something like this:
```
HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
HDR**2401*XX0062484*22750***20081006000000*000*******
LIN**001*788-0538-001*4891-788538010*20000*EA**0000***
```
I could build a custom pipeline component to do this, but I'm wondering if there is a simpler way of getting what I need?
|
You should be able to accomplish what you want by using the Delimiter properties of the flat file schema.
Based on your example file I created a schema with the following record structure:
```
<Schema>
<Root>
<HDRGroup>
<HDR>
<LIN>
```
If you click on the root node of your schema you should see a list of properties for this root node. One properties section has the header 'Flat File'. In this flat file section the first three properties you can set are Child Delimiter, Child Delimiter Type and Child Order.
This is where you configure the schema to create the blank lines (in this case CR LF but you can set different things as you need) For your example I set the following:
```
Child Delimiter: 0x0D 0x0A 0x0D 0x0A
Child Delimiter Type: Hexadecimal
Child Order: Infix
```
0x0D 0x0A is a carriage return line feed, so the above simply creates two blank lines, infixed between each child of the root node.
The <HDRGroup> then functions to make sure that each header and its lines is kept together. For its delimiter settings I set:
```
Child Delimiter: 0x0D 0x0A
Child Delimiter Type: Hexadecimal
Child Order: Postfix
```
The <HDR> and <LIN> records then contain the actual schema definition for your message lines, delimited with an asterisk.
This schema works for something that looks to me like what you have asked for - this sort of flatfile schema and how it parses a file is highly dependant of the little details, however, such as what type of line breaks there are and if there are line breaks at the end of the file.
The princples of using the delimiters will stand, you will likely find you need to tinker with the settings.
|
223,215 |
<p>At a previous employer, we were writing binary messages that had to go "over the wire" to other computers. Each message had a standard header something like:</p>
<pre><code>class Header
{
int type;
int payloadLength;
};
</code></pre>
<p>All of the data was contiguous (header, immediately followed by data). We wanted to get to the payload given that we had a pointer to a header. Traditionally, you might say something like:</p>
<pre><code>char* Header::GetPayload()
{
return ((char*) &payloadLength) + sizeof(payloadLength);
}
</code></pre>
<p>or even:</p>
<pre><code>char* Header::GetPayload()
{
return ((char*) this) + sizeof(Header);
}
</code></pre>
<p>That seemed kind of verbose, so I came up with:</p>
<pre><code>char* Header::GetPayload()
{
return (char*) &this[1];
}
</code></pre>
<p>It seems rather disturbing at first, possibly too odd to use -- but very compact.
There was a lot of debate on whether it was brilliant or an abomination. </p>
<p>So which is it - Crime against coding, or nice solution? Have you ever had a similar trade-off?</p>
<p>-Update:</p>
<p>We did try the zero sized array, but at the time, compilers gave warnings.
We eventually went to the inhertited technique: Message derives from Header.
It works great in practice, but in priciple you are saying a message IsA Header - which seems a little awkward.</p>
|
[
{
"answer_id": 223224,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 4,
"selected": false,
"text": "<p>Personally I think that if there's a crime, it's asking the header for the payload.</p>\n\n<p>But as long as you're going to do it that way, 'this+1' is as good a way as any.</p>\n\n<p>Justification: '&this[1]' is a general-purpose piece of code that doesn't require you to go digging through class-definitions to fully comprehend, and doesn't require fixing when someone changes the name or contents of the class.</p>\n\n<p>BTW, the first example is the true crime against humanity. Add a member to the end of the class and it'll fail. Move the members around the class and it'll fail. If the compiler pads the class, it'll fail.</p>\n\n<p>Also, if you're going to assume that the compiler's layout of classes/structs matches your packet layout, then you should understand how the compiler in question works. Eg. on MSVC you'll probably want to know about <code>#pragma pack</code>.</p>\n\n<p>PS: It's a little scary how many people consider \"this+1\" or \"&this[1]\" hard to read or understand.</p>\n"
},
{
"answer_id": 223228,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": false,
"text": "<p>My vote is Coding Horror. Don't get me wrong, it's clever - but you're saving yourself one entire addition operation at the cost of making the code much more difficult to understand and read. I don't see the tradeoff as worth it.</p>\n"
},
{
"answer_id": 223230,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 6,
"selected": true,
"text": "<p>I'd go for crime against coding.</p>\n\n<p>Both methods will generate the exact same object code. The first makes it's intention clear. The second is very confusing, with the only advantage that it saves a couple keystrokes. (Just learn to freakin' type).</p>\n\n<p>Also, note that NEITHER method is guaranteed to work. The sizeof() an object includes padding for word alignment, so that if the header was:</p>\n\n<pre><code>class Header\n{\n int type;\n int payloadLength;\n char status;\n};\n</code></pre>\n\n<p>Both methods you describe would have the payload starting at Header+12, when most likely it actually starts at Header+9.</p>\n"
},
{
"answer_id": 223231,
"author": "Anthony Giorgio",
"author_id": 9816,
"author_profile": "https://Stackoverflow.com/users/9816",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you should have used a verbose method, but replaced it with a #define macro? This way you can use your shorthand when typing, but anyone needing to debug the code can follow along without issue.</p>\n"
},
{
"answer_id": 223237,
"author": "QBziZ",
"author_id": 11572,
"author_profile": "https://Stackoverflow.com/users/11572",
"pm_score": 1,
"selected": false,
"text": "<p>They're basically the same thing as far as I'm concerned. Both are forms of byte juggling, which is always risky, but not impossible to get right.\nThe first form is a bit more accepted and recognizable.\nI would personally write :</p>\n\n<pre><code>char* Header::GetPayload()\n{\n return ((char*) this) + sizeof(*this);\n}\n</code></pre>\n"
},
{
"answer_id": 223241,
"author": "ypnos",
"author_id": 21974,
"author_profile": "https://Stackoverflow.com/users/21974",
"pm_score": 3,
"selected": false,
"text": "<p>I think this is flawed from the start on if the header needs to \"return\" data which is not included in it.</p>\n\n<p>As you already put yourself on these hackish grounds, I really love what you came up with.</p>\n\n<p>But note that this is not a beauty contest. You should find an entire different solution. For alle the three versions of GetPayload() you presented, I would not understand what the hell is going on there without your further explanation.</p>\n"
},
{
"answer_id": 223261,
"author": "Kluge",
"author_id": 8752,
"author_profile": "https://Stackoverflow.com/users/8752",
"pm_score": 2,
"selected": false,
"text": "<p>If it works -- consistently -- then it's an elegant solution.</p>\n\n<p>It will normally work in memory because the compiler will deal with alignment issues and you can assume that the Payload follows the header in correctly-aligned memory space.</p>\n\n<p>I could see this falling apart when the Header/Payload objects are streamed \"over the wire\" because the streaming mechanism you use will probably not care about aligning objects on any particular boundary. Therefore, Payload may directly follow the Header with no padding to force it to a particular alignment.</p>\n\n<p>To coin a phrase, elegant is as elegant does. So, it's elegant as long as you are careful how you stream it.</p>\n"
},
{
"answer_id": 223279,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": false,
"text": "<p>You're depending on the compiler to layout your classes in a particular way. I would have defined the message as a struct (with me defining layout) and had a class that encapsulates the message and provides the interface to it. Clear code = good code. \"Cute\" code = bad (hard to maintain) code.</p>\n\n<pre><code>struct Header\n{\n int type;\n int payloadlength;\n}\nstruct MessageBuffer\n{\n struct Header header;\n char[MAXSIZE] payload;\n}\n\nclass Message\n{\n private:\n MessageBuffer m;\n\n public:\n Message( MessageBuffer buf ) { m = buf; }\n\n struct Header GetHeader( )\n {\n return m.header;\n }\n\n char* GetPayLoad( )\n {\n return &m.payload;\n }\n}\n</code></pre>\n\n<p>It's been awhile since I've written any C++, so please excuse any issues with syntax. Just trying to convey the general idea.</p>\n"
},
{
"answer_id": 223292,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 1,
"selected": false,
"text": "<p>Don't forget that VC++ may impose a padding on the <code>sizeof()</code> value on the class. Since the provided example is expected to be 8 bytes, it is automatically DWORD aligned, so should be ok. Check <a href=\"http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>#pragma pack</code></a>.</p>\n\n<p>Though, I agree, the provided examples are some degree of Coding Horror. Many Win32 data structures include a pointer placeholder in the header structure when variable length data follows. This is probably the easiest way to reference this data once it's loaded into memory. The MAPI <a href=\"http://msdn.microsoft.com/en-us/library/ms527417(EXCHG.10).aspx\" rel=\"nofollow noreferrer\"><code>SRowSet</code></a> structure is one example of this approach.</p>\n"
},
{
"answer_id": 223382,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 2,
"selected": false,
"text": "<p>First, there's an awful lot of space between \"crime against coding\" and \"nice solution,\" but I'd say this is closer to the former.</p>\n\n<p>Is the Header its Payload's keeper?</p>\n\n<p>That's the fundamental problem here -- both the header and the payload should be managed by another object that holds the entire message, and that is the proper place to ask for the payload. And it would be able to do so without pointer arithmetic or indexing.</p>\n\n<p>Given that, I would favor the second solution, since it is clearer what is going on.</p>\n\n<p>But that we're in this situation to begin with seems to indicate that the culture of your team values cleverness over clarity, so I guess all bets are off.</p>\n\n<p>If you really want to be cute, you could generalize.</p>\n\n<pre><code>template<typename T. typename RetType>\nRetType JustPast(const T* pHeader)\n{\n return reinterpret_cast<RetType>(pHeader + sizeof(T));\n}\n</code></pre>\n"
},
{
"answer_id": 223462,
"author": "Jan de Vos",
"author_id": 11215,
"author_profile": "https://Stackoverflow.com/users/11215",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered the 'empty array member' trick? I remember seeing it often, and even using it once or twice, but I can't seem to find any really good references (except, maybe, the one referenced below).</p>\n\n<p>The trick is to declare your struct as</p>\n\n<pre><code>struct bla {\n int i;\n int j;\n char data[0];\n}\n</code></pre>\n\n<p>Then, the 'data' member simply points to whatever is behind the headers. I am not sure how portable this is; I've seen it with '1' as the array size as well.</p>\n\n<p>(using the URL below as a referece, using the '[1]' syntax, seemed not to work because it is too long. Here is the link:)</p>\n\n<p><a href=\"http://developer.apple.com/documentation/DeveloperTools/gcc-4.0.1/gcc/Zero-Length.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/documentation/DeveloperTools/gcc-4.0.1/gcc/Zero-Length.html</a></p>\n"
},
{
"answer_id": 223600,
"author": "Raindog",
"author_id": 29049,
"author_profile": "https://Stackoverflow.com/users/29049",
"pm_score": 1,
"selected": false,
"text": "<p>I actually do something similar, and so does nearly every MMO or online video game ever written. Although they have a concept called a \"Packet\" and each packet has it's own layout. So you might have:</p>\n\n<pre><code>struct header\n{\n short id;\n short size;\n}\n\nstruct foo\n{\n header hd;\n short hit_points;\n}\n\n\nshort get_foo_data(char *packet)\n{\n return reinterpret_cast<foo*>(packet)->hit_points;\n}\n\nvoid handle_packet(char *packet)\n{\n header *hd = reinterpret_cast<header*>(packet);\n switch(hd->id)\n {\n case FOO_PACKET_ID:\n short val = get_foo_data(packet);\n //snip\n }\n}\n</code></pre>\n\n<p>And they do that for the majority of their packets. Some packets obviously have dynamic sizes, and for those members they use length prefixed fields and some logic to parse that data.</p>\n"
},
{
"answer_id": 223756,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 4,
"selected": false,
"text": "<p>It's a common problem, but what you actually want is this.</p>\n\n<pre><code>class Header\n{\n int type;\n int payloadLength;\n char payload[0];\n\n};\n\nchar* Header::GetPayload()\n{\n return payload;\n}\n</code></pre>\n"
},
{
"answer_id": 223959,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I vote for &this[1]. I've seen it used quite a bit when parsing files that have been loaded into memory (which can equally include received packets). It may look a tad odd the first time you see it, but I think that what it means should be immediately obvious: it's clearly the address of memory just past this object. It's nice because it's hard to get wrong.</p>\n"
},
{
"answer_id": 224076,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 1,
"selected": false,
"text": "<p>I think in this day and age, in C++, the C-style cast to char* disqualifies you from any \"brilliant design idea\" awards without getting much of a hearing.</p>\n\n<p>I might go for:</p>\n\n<pre><code>#include <stdint.h>\n#include <arpa/inet.h>\n\nclass Header {\nprivate:\n uint32_t type;\n uint32_t payloadlength;\npublic:\n uint32_t getType() { return ntohl(type); }\n uint32_t getPayloadLength() { return ntohl(payloadlength); }\n};\n\nclass Message {\nprivate:\n Header head;\n char payload[1]; /* or maybe std::vector<char>: see below */\npublic:\n uint32_t getType() { return head.getType(); }\n uint32_t getPayloadLength() { return head.getPayloadLength(); }\n const char *getPayload() { return payload; }\n};\n</code></pre>\n\n<p>This assumes C99-ish POSIX, of course: to port to non-POSIX platforms you'd have to define one or both of uint32_t and ntohl yourself, in terms of whatever the platform does offer. It's usually not hard.</p>\n\n<p>In theory you might need layout pragmas in both classes. In practice I'd be surprised given the actual fields in this case. The issue can be avoided by reading/writing the data from/to iostreams one field at a time, rather than trying to construct the bytes of the message in memory and then write it in one go. It also means you can represent the payload with something more helpful than a char[], which in turn means you won't need to have a maximum message size, or mess about with malloc and/or placement new, or whatever. Of course it introduces a bit of overhead.</p>\n"
},
{
"answer_id": 415007,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 0,
"selected": false,
"text": "<p>I don't like to use words like \"crime\". I would rather point out that &this[1] seems to make assumptions about memory layout that a compiler might disagree with. For example, any compiler might, for its own reasons (like alignment), insert dummy bytes anywhere in a structure. I would prefer a technique that has more of a guarantee of getting the correct offset if compilers or options get changed.</p>\n"
},
{
"answer_id": 506272,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the abovementioned, I'd say that this is a crime against interoperability and good wire protocol design principles. It is really surprising how many programmers are not able/willing to make a clear distinction between a wire protocol definition and its implementation.\nIf your protocol has to survive for more than two days, it most probably has to survive for more than two years/OSes/compilers/languages/endiannesses and in some point it will break, rather sooner than later. So, make other folks' life easier, write down the wire protocol specification plus write proper (de)serialization routines. Otherwise, people will keep mentioning your name in not so pleasant contexts.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17975/"
] |
At a previous employer, we were writing binary messages that had to go "over the wire" to other computers. Each message had a standard header something like:
```
class Header
{
int type;
int payloadLength;
};
```
All of the data was contiguous (header, immediately followed by data). We wanted to get to the payload given that we had a pointer to a header. Traditionally, you might say something like:
```
char* Header::GetPayload()
{
return ((char*) &payloadLength) + sizeof(payloadLength);
}
```
or even:
```
char* Header::GetPayload()
{
return ((char*) this) + sizeof(Header);
}
```
That seemed kind of verbose, so I came up with:
```
char* Header::GetPayload()
{
return (char*) &this[1];
}
```
It seems rather disturbing at first, possibly too odd to use -- but very compact.
There was a lot of debate on whether it was brilliant or an abomination.
So which is it - Crime against coding, or nice solution? Have you ever had a similar trade-off?
-Update:
We did try the zero sized array, but at the time, compilers gave warnings.
We eventually went to the inhertited technique: Message derives from Header.
It works great in practice, but in priciple you are saying a message IsA Header - which seems a little awkward.
|
I'd go for crime against coding.
Both methods will generate the exact same object code. The first makes it's intention clear. The second is very confusing, with the only advantage that it saves a couple keystrokes. (Just learn to freakin' type).
Also, note that NEITHER method is guaranteed to work. The sizeof() an object includes padding for word alignment, so that if the header was:
```
class Header
{
int type;
int payloadLength;
char status;
};
```
Both methods you describe would have the payload starting at Header+12, when most likely it actually starts at Header+9.
|
223,219 |
<p>I want to do something like </p>
<pre><code>insert into my table (select * from anothertable where id < 5)
</code></pre>
<p>What is the correct MSSQL syntax?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 223236,
"author": "Ed Altorfer",
"author_id": 26552,
"author_profile": "https://Stackoverflow.com/users/26552",
"pm_score": 4,
"selected": true,
"text": "<p>Is this what you're looking for?</p>\n\n<pre><code>INSERT INTO MyTable\nSELECT * FROM AnotherTable\nWHERE AnotherTable.ID < 5\n</code></pre>\n"
},
{
"answer_id": 223239,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 2,
"selected": false,
"text": "<p>That syntax looks correct, but you the fields have to match exactly otherwise it won't work.</p>\n\n<p>You can specify the fields eg:</p>\n\n<pre><code>INSERT INTO myTable(COL1, COL2, COL3) \nSELECT COL1, COL2, COL3 FROM anotherTable where anotherTable.id < 5\n</code></pre>\n"
},
{
"answer_id": 223244,
"author": "Aheho",
"author_id": 21155,
"author_profile": "https://Stackoverflow.com/users/21155",
"pm_score": 0,
"selected": false,
"text": "<p><code>Insert Into MyTable\n (\n Col1,\n Col2,\n Col3\n )\nSelect\n Col1,\n Col2,\n Col3\nFrom\n AnotherTable\nWhere\n ID < 5\n</code></p>\n"
},
{
"answer_id": 223411,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "<p>You can also do</p>\n\n<pre><code>select *\ninto MyTable\nfrom AnotherTable\nwhere ID < 5\n</code></pre>\n\n<p>which will create MyTable with the required columns, as well as fill the data in.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
] |
I want to do something like
```
insert into my table (select * from anothertable where id < 5)
```
What is the correct MSSQL syntax?
Thanks!
|
Is this what you're looking for?
```
INSERT INTO MyTable
SELECT * FROM AnotherTable
WHERE AnotherTable.ID < 5
```
|
223,249 |
<p>In Visual Studio, two files are created when you create a new Windows Form in your solution (e.g. if you create MyForm.cs, MyForm.Designer.cs and MyForm.resx are also created). These second two files are displayed as a subtree in the Solution Explorer.</p>
<p><strong>Is there any way to add files to the sub-tree or group for a Windows Form class?</strong></p>
|
[
{
"answer_id": 223254,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 3,
"selected": false,
"text": "<p>You need to edit the csproj directly. There is a DependentUpon tag that you have to add as a child tag of the file you want to place under MyForm.cs.</p>\n\n<p>Example:</p>\n\n<pre><code><Compile Include=\"MyForm.MyCoolSubFile.cs\">\n <DependentUpon>MyForm.cs</DependentUpon>\n</Compile>\n</code></pre>\n"
},
{
"answer_id": 223259,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 5,
"selected": true,
"text": "<p>Open .csproj in edit mode, look for the file you want to be under another one, and add the DependentUpon element, like this:</p>\n\n<pre><code><Compile Include=\"AlertDialog.xaml.cs\">\n <DependentUpon>AlertDialog.xaml</DependentUpon>\n</Compile>\n</code></pre>\n"
},
{
"answer_id": 223264,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, but it's a bit of a hassle - basically you need to edit the project file by hand.</p>\n\n<p>Here's an example from a project that Marc Gravell and I both work on:</p>\n\n<pre><code><Compile Include=\"Linq\\Extensions\\DataProducerExt.cs\" />\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.SingleReturn.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.Grouping.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.Pipeline.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.Conversion.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.Math.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n</code></pre>\n\n<p>Note the \"DependentUpon\" element in each of the dependencies. This displays appropriately in VS, with DataProducerExt.cs as the parent.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5692/"
] |
In Visual Studio, two files are created when you create a new Windows Form in your solution (e.g. if you create MyForm.cs, MyForm.Designer.cs and MyForm.resx are also created). These second two files are displayed as a subtree in the Solution Explorer.
**Is there any way to add files to the sub-tree or group for a Windows Form class?**
|
Open .csproj in edit mode, look for the file you want to be under another one, and add the DependentUpon element, like this:
```
<Compile Include="AlertDialog.xaml.cs">
<DependentUpon>AlertDialog.xaml</DependentUpon>
</Compile>
```
|
223,253 |
<p>I have a requirement to install multiple web setup projects (using VS2005 and ASP.Net/C#) into the same virtual folder. The projects share some assembly references (the file systems are all structured to use the same 'bin' folder), making deployment of changes to those assemblies problematic since the MS installer will only overwrite assemblies if the currently installed version is older than the one in the MSI.</p>
<p>I'm not suggesting that the pessimistic installation scheme is wrong - only that it creates a problem in the environment I've been given to work with. Since there are a sizable number of common assemblies and a significant number of developers who might change a common assembly but forget to update its version number, trying to manage versioning manually will eventually lead to massive confusion at install time.</p>
<p>On the flip side of this issue, it's also important not to spontaneously update version numbers and replace <em>all</em> common assemblies with <em>every</em> install, since that could (temporarily at least) obscure cases where actual changes were made.</p>
<p>That said, what I'm looking for is a means to update assembly version information (preferably using MSBuild) only in cases where the assembly constituents (code modules, resources etc) has/have actually changed.</p>
<p>I've found a few references that are at least partially pertinent <a href="http://code.msdn.microsoft.com/AssemblyInfoTaskvers/Release/ProjectReleases.aspx?ReleaseId=232" rel="noreferrer" title="here">here </a> (AssemblyInfo task on MSDN) and <a href="http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/94054d89-ba19-4658-9e4e-ce7d8ff4dea3/" rel="noreferrer" title="here">here</a> (looks similar to what I need, but more than two years old and without a clear solution).</p>
<p>My team also uses TFS version control, so an automated solution should probably include a means by which the AssebmlyInfo can be checked out/in during the build.</p>
<p>Any help would be much appreciated.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 224116,
"author": "David White",
"author_id": 30183,
"author_profile": "https://Stackoverflow.com/users/30183",
"pm_score": 3,
"selected": false,
"text": "<p>I cannot answer all your questions, as I don't have experience with TFS.</p>\n\n<p>But I can recommend a better approach to use for updating your AssemblyInfo.cs files than using the AssemblyInfo task. That task appears to just recreate a standard AssemblyInfo file from scratch, and loses any custom portions you may have added.</p>\n\n<p>For that reason, I suggest you look into the FileUpdate task, from the MSBuild Community Tasks project. It can look for specific content in a file and replace it, like this:</p>\n\n<pre><code><FileUpdate \nFiles=\"$(WebDir)\\Properties\\AssemblyInfo.cs\"\nRegex=\"(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\"\nReplacementText=\"$(Major).$(ServicePack).$(Build).$(Revision)\" \nCondition=\"'$(Configuration)' == 'Release'\"\n/>\n</code></pre>\n\n<p>There are several ways you can control the incrementing of the build number. Because I only want the build number to increment if the build is completely successful, I use a 2-step method:</p>\n\n<ul>\n<li>read a number from a text file (the only thing in the file is the number) and add 1 without changing the file;</li>\n<li>as a final step in the build process, if everything succeeded, save the incremented number back to the text file.</li>\n</ul>\n\n<p>There are tasks such as ReadLinesFromFile, that can help you with this, but I found it easiest to write a small custom task:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing Microsoft.Build.Framework;\nusing Microsoft.Build.Utilities;\n\nnamespace CredibleCustomBuildTasks\n{\n public class IncrementTask : Task\n {\n [Required]\n public bool SaveChange { get; set; }\n\n [Required]\n public string IncrementFileName { get; set; }\n\n [Output]\n public int Increment { get; set; }\n\n public override bool Execute()\n {\n if (File.Exists(IncrementFileName))\n {\n string lines = File.ReadAllText(IncrementFileName);\n int result;\n if(Int32.TryParse(lines, out result))\n {\n Increment = result + 1;\n }\n else\n {\n Log.LogError(\"Unable to parse integer in '{0}' (contents of {1})\");\n return false;\n }\n }\n else\n {\n Increment = 1;\n }\n\n if (SaveChange)\n {\n File.Delete(IncrementFileName);\n File.WriteAllText(IncrementFileName, Increment.ToString());\n }\n return true;\n }\n }\n}\n</code></pre>\n\n<p>I use this before the FileUpdateTask to get the next build number:</p>\n\n<pre><code><IncrementTask \nIncrementFileName=\"$(BuildNumberFile)\" \nSaveChange=\"false\">\n <Output TaskParameter=\"Increment\" PropertyName=\"Build\" />\n</IncrementTask>\n</code></pre>\n\n<p>and as my final step (before notifying others) in the build:</p>\n\n<pre><code><IncrementTask \nIncrementFileName=\"$(BuildNumberFile)\" \nSaveChange=\"true\"\nCondition=\"'$(Configuration)' == 'Release'\" />\n</code></pre>\n\n<p>Your other question of how to update the version number only when source code has changed is highly dependent on your how your build process interacts with your source control. Normally, checking in source file changes should initiate a Continuous Integration build. That is the one to use to update the relevant version number.</p>\n"
},
{
"answer_id": 1042306,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have written one custome task you can refer the code below. It will create an utility to which you can pass assemblyinfo path Major,minor and build number. you can modify it to get revision number. Since in my case this task was done by developer i used to search it and again replace whole string.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nnamespace UpdateVersion\n{\n class SetVersion\n {\n static void Main(string[] args)\n {\n String FilePath = args[0];\n String MajVersion=args[1];\n String MinVersion = args[2];\n String BuildNumber = args[3];\n string RevisionNumber = null;\n\n StreamReader Reader = File.OpenText(FilePath);\n string contents = Reader.ReadToEnd();\n Reader.Close();\n\n MatchCollection match = Regex.Matches(contents, @\"\\[assembly: AssemblyVersion\\(\"\".*\"\"\\)\\]\", RegexOptions.IgnoreCase);\n if (match[0].Value != null)\n {\n string strRevisionNumber = match[0].Value;\n\n RevisionNumber = strRevisionNumber.Substring(strRevisionNumber.LastIndexOf(\".\") + 1, (strRevisionNumber.LastIndexOf(\"\\\"\")-1) - strRevisionNumber.LastIndexOf(\".\"));\n\n String replaceWithText = String.Format(\"[assembly: AssemblyVersion(\\\"{0}.{1}.{2}.{3}\\\")]\", MajVersion, MinVersion, BuildNumber, RevisionNumber);\n string newText = Regex.Replace(contents, @\"\\[assembly: AssemblyVersion\\(\"\".*\"\"\\)\\]\", replaceWithText);\n\n StreamWriter writer = new StreamWriter(FilePath, false);\n writer.Write(newText);\n writer.Close();\n }\n else\n {\n Console.WriteLine(\"No matching values found\");\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32459847,
"author": "sorin",
"author_id": 99834,
"author_profile": "https://Stackoverflow.com/users/99834",
"pm_score": 0,
"selected": false,
"text": "<p>I hate to say this but it seems that you may be doing it wrongly. Is much easier if you do generate the assembly versions on the fly instead of trying to patch them.</p>\n\n<p>Take a look at <a href=\"https://sbarnea.com/articles/easy-windows-build-versioning/\" rel=\"nofollow\">https://sbarnea.com/articles/easy-windows-build-versioning/</a></p>\n\n<p>Why I do think you are doing it wrong?\n* A build should not modify the version number \n* if you build the same changeset twice you should get the same build numbers\n* if you put build number inside what microsoft calls build number (proper naming would be PATCH level) you will eventually reach the 65535 limitation. </p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7388/"
] |
I have a requirement to install multiple web setup projects (using VS2005 and ASP.Net/C#) into the same virtual folder. The projects share some assembly references (the file systems are all structured to use the same 'bin' folder), making deployment of changes to those assemblies problematic since the MS installer will only overwrite assemblies if the currently installed version is older than the one in the MSI.
I'm not suggesting that the pessimistic installation scheme is wrong - only that it creates a problem in the environment I've been given to work with. Since there are a sizable number of common assemblies and a significant number of developers who might change a common assembly but forget to update its version number, trying to manage versioning manually will eventually lead to massive confusion at install time.
On the flip side of this issue, it's also important not to spontaneously update version numbers and replace *all* common assemblies with *every* install, since that could (temporarily at least) obscure cases where actual changes were made.
That said, what I'm looking for is a means to update assembly version information (preferably using MSBuild) only in cases where the assembly constituents (code modules, resources etc) has/have actually changed.
I've found a few references that are at least partially pertinent [here](http://code.msdn.microsoft.com/AssemblyInfoTaskvers/Release/ProjectReleases.aspx?ReleaseId=232 "here") (AssemblyInfo task on MSDN) and [here](http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/94054d89-ba19-4658-9e4e-ce7d8ff4dea3/ "here") (looks similar to what I need, but more than two years old and without a clear solution).
My team also uses TFS version control, so an automated solution should probably include a means by which the AssebmlyInfo can be checked out/in during the build.
Any help would be much appreciated.
Thanks in advance.
|
I cannot answer all your questions, as I don't have experience with TFS.
But I can recommend a better approach to use for updating your AssemblyInfo.cs files than using the AssemblyInfo task. That task appears to just recreate a standard AssemblyInfo file from scratch, and loses any custom portions you may have added.
For that reason, I suggest you look into the FileUpdate task, from the MSBuild Community Tasks project. It can look for specific content in a file and replace it, like this:
```
<FileUpdate
Files="$(WebDir)\Properties\AssemblyInfo.cs"
Regex="(\d+)\.(\d+)\.(\d+)\.(\d+)"
ReplacementText="$(Major).$(ServicePack).$(Build).$(Revision)"
Condition="'$(Configuration)' == 'Release'"
/>
```
There are several ways you can control the incrementing of the build number. Because I only want the build number to increment if the build is completely successful, I use a 2-step method:
* read a number from a text file (the only thing in the file is the number) and add 1 without changing the file;
* as a final step in the build process, if everything succeeded, save the incremented number back to the text file.
There are tasks such as ReadLinesFromFile, that can help you with this, but I found it easiest to write a small custom task:
```
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace CredibleCustomBuildTasks
{
public class IncrementTask : Task
{
[Required]
public bool SaveChange { get; set; }
[Required]
public string IncrementFileName { get; set; }
[Output]
public int Increment { get; set; }
public override bool Execute()
{
if (File.Exists(IncrementFileName))
{
string lines = File.ReadAllText(IncrementFileName);
int result;
if(Int32.TryParse(lines, out result))
{
Increment = result + 1;
}
else
{
Log.LogError("Unable to parse integer in '{0}' (contents of {1})");
return false;
}
}
else
{
Increment = 1;
}
if (SaveChange)
{
File.Delete(IncrementFileName);
File.WriteAllText(IncrementFileName, Increment.ToString());
}
return true;
}
}
}
```
I use this before the FileUpdateTask to get the next build number:
```
<IncrementTask
IncrementFileName="$(BuildNumberFile)"
SaveChange="false">
<Output TaskParameter="Increment" PropertyName="Build" />
</IncrementTask>
```
and as my final step (before notifying others) in the build:
```
<IncrementTask
IncrementFileName="$(BuildNumberFile)"
SaveChange="true"
Condition="'$(Configuration)' == 'Release'" />
```
Your other question of how to update the version number only when source code has changed is highly dependent on your how your build process interacts with your source control. Normally, checking in source file changes should initiate a Continuous Integration build. That is the one to use to update the relevant version number.
|
223,268 |
<p>I know there is built-in Internet explorer, but what I'm looking for is to open Firefox/Mozilla window (run the application) with specified URL. Anyone can tell me how to do that in C# (.nET) ?</p>
|
[
{
"answer_id": 223290,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 0,
"selected": false,
"text": "<p>Use the Process class (System.Diagnostics) using the URL as the process name. This will use the system default browser to open the URL. If you specify a browser, you run the risk that the browser doesn't exist.</p>\n"
},
{
"answer_id": 223291,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 1,
"selected": false,
"text": "<p>See ProcessInfo.UseShellExecute</p>\n"
},
{
"answer_id": 223294,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 0,
"selected": false,
"text": "<p>In Visual Studio click the File -> Browse With... on the menus and then select the browser that you want to use. You can also change the browser there. If the Browse With... menu option doesn't appear then you need to select a project from your solution that that can be launched in a browser.</p>\n"
},
{
"answer_id": 223307,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 0,
"selected": false,
"text": "<p>If you explicitly do not want to use the User's default browser, you can run the browser with the URL as the first argument. </p>\n\n<blockquote>\n<pre><code>C:\\Program Files\\Mozilla Firefox>firefox.exe http://google.com\n</code></pre>\n</blockquote>\n\n<p>launches Firefox with google for me. But as people have said, you run the risk of it not being installed, or being installed to a different place, etc.</p>\n"
},
{
"answer_id": 223320,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 5,
"selected": true,
"text": "<p>This will launch the system defined default browser:</p>\n\n<pre><code>string url = \"http://stackoverflow.com/\";\nSystem.Diagnostics.Process.Start(url); \n</code></pre>\n\n<p>Remember that Process.Start(url) might throw exceptions if the browser is not configured correctly.</p>\n"
},
{
"answer_id": 5402343,
"author": "Bruno Le Duic",
"author_id": 629672,
"author_profile": "https://Stackoverflow.com/users/629672",
"pm_score": 4,
"selected": false,
"text": "<p>You can do this: </p>\n\n<pre><code>System.Diagnostics.Process.Start(\"firefox.exe\", \"http://www.google.com\");\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21209/"
] |
I know there is built-in Internet explorer, but what I'm looking for is to open Firefox/Mozilla window (run the application) with specified URL. Anyone can tell me how to do that in C# (.nET) ?
|
This will launch the system defined default browser:
```
string url = "http://stackoverflow.com/";
System.Diagnostics.Process.Start(url);
```
Remember that Process.Start(url) might throw exceptions if the browser is not configured correctly.
|
223,272 |
<p>I have a simple query like this:</p>
<pre><code>select * from mytable where id > 8
</code></pre>
<p>I want to make the 8 a variable. There's some syntax like </p>
<pre><code>declare @myvar int
myvar = 8
</code></pre>
<p>but I don't know the exact syntax.</p>
<p>What is it?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 223280,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 1,
"selected": false,
"text": "<pre><code>declare @myvar int\n\nselect @myvar = 8\n</code></pre>\n"
},
{
"answer_id": 223281,
"author": "Ed Altorfer",
"author_id": 26552,
"author_profile": "https://Stackoverflow.com/users/26552",
"pm_score": 5,
"selected": true,
"text": "<p>It's:</p>\n\n<pre><code>DECLARE @MyVariable INT\nSET @MyVariable = 8\n</code></pre>\n"
},
{
"answer_id": 223289,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 3,
"selected": false,
"text": "<pre><code>declare @myvar int\n\nSet @myvar = 8\n\nselect * from mytable where id > @myvar\n</code></pre>\n"
},
{
"answer_id": 223807,
"author": "JasonFruit",
"author_id": 21778,
"author_profile": "https://Stackoverflow.com/users/21778",
"pm_score": 2,
"selected": false,
"text": "<p>To clarify: both SET and SELECT work, but SET is the ANSI standard. However, if you're setting multiple values at once, then</p>\n\n<pre><code>SET @one = 1\nSET @two = 2\n</code></pre>\n\n<p>will be very slightly slower than</p>\n\n<pre><code>SELECT @one = 1, @two = 2\n</code></pre>\n\n<p>What you gain in speed may well be offset by readability and clarity, however.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
] |
I have a simple query like this:
```
select * from mytable where id > 8
```
I want to make the 8 a variable. There's some syntax like
```
declare @myvar int
myvar = 8
```
but I don't know the exact syntax.
What is it?
Thanks!
|
It's:
```
DECLARE @MyVariable INT
SET @MyVariable = 8
```
|
223,283 |
<p>Even a simple <a href="http://en.wikipedia.org/wiki/Notepad_%28software%29" rel="noreferrer">Notepad</a> application in C# consumes megabytes of RAM as seen in the task manager. On minimizing the application the memory size in the task manager goes down considerably and is back up when the application is maximized.</p>
<p>I read somewhere that the .NET process reserves a lot of memory for runtime allocation in advance. That's why .NET applications have a larger memory footprint to start with. But this memory can be released using Win32 API calls. A trade-off is that runtime allocation becomes slow - is that true?</p>
|
[
{
"answer_id": 223300,
"author": "Ed Altorfer",
"author_id": 26552,
"author_profile": "https://Stackoverflow.com/users/26552",
"pm_score": 6,
"selected": true,
"text": "<p>The reason for the large memory footprint is that the JIT compiler and <a href=\"http://en.wikipedia.org/wiki/Windows_Forms\" rel=\"noreferrer\">Windows Forms</a> engine are being loaded with your process. To reduce this, you can do the following:</p>\n\n<pre><code>[DllImport(\"psapi.dll\")]\nstatic extern int EmptyWorkingSet(IntPtr hwProc);\n\nstatic void MinimizeFootprint()\n{\n EmptyWorkingSet(Process.GetCurrentProcess().Handle);\n}\n</code></pre>\n\n<p>This should remove as much as possible from your memory footprint. There may be a way that you can also reduce the amount of memory that is set aside for runtime memory allocation.</p>\n"
},
{
"answer_id": 223301,
"author": "Joshua Hudson",
"author_id": 6232,
"author_profile": "https://Stackoverflow.com/users/6232",
"pm_score": 2,
"selected": false,
"text": "<p>The task manager does not show real life usage of memory for a .NET app. To see that you almost have to put a performance counter on the app or use a profiler.</p>\n\n<p>What you see in the Task Manager is the working memory of an app which includes a bunch of overhead for the framework itself which must also load when your app loads.</p>\n"
},
{
"answer_id": 223347,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 5,
"selected": false,
"text": "<p>TaskManager should not be used to measure the memory footprint of a .NET application.</p>\n\n<p>When a .NET application starts, it asks the OS for a chunk of memory which it then segments to become the managed heap, stack, and large object heap. It is this total chunk of memory that TaskManager is reporting, which may or may not be completely used by .NET. Once a .NET application is given a chunk of memory, it will not release it until asked by the OS, which will only happen with the OS determines a need for more memory resources.</p>\n\n<p>If you want to measure memory allocations, you need to look at the various performance monitor (PerfMon) counters.</p>\n\n<p>You can use interop code to call Win32 APIs to trim your working set size, but the next time your application requests memory from the OS the working set will go back up and there will be a performance hit while the OS allocates and hands out the additional memory and the .NET runtime \"configures\" it.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29443/"
] |
Even a simple [Notepad](http://en.wikipedia.org/wiki/Notepad_%28software%29) application in C# consumes megabytes of RAM as seen in the task manager. On minimizing the application the memory size in the task manager goes down considerably and is back up when the application is maximized.
I read somewhere that the .NET process reserves a lot of memory for runtime allocation in advance. That's why .NET applications have a larger memory footprint to start with. But this memory can be released using Win32 API calls. A trade-off is that runtime allocation becomes slow - is that true?
|
The reason for the large memory footprint is that the JIT compiler and [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) engine are being loaded with your process. To reduce this, you can do the following:
```
[DllImport("psapi.dll")]
static extern int EmptyWorkingSet(IntPtr hwProc);
static void MinimizeFootprint()
{
EmptyWorkingSet(Process.GetCurrentProcess().Handle);
}
```
This should remove as much as possible from your memory footprint. There may be a way that you can also reduce the amount of memory that is set aside for runtime memory allocation.
|
223,285 |
<p>I am using the following code:</p>
<pre><code><?php
$stock = $_GET[s]; //returns stock ticker symbol eg GOOG or YHOO
$first = $stock[0];
$url = "http://biz.yahoo.com/research/earncal/".$first."/".$stock.".html";
$data = file_get_contents($url);
$r_header = '/Prev. Week(.+?)Next Week/';
$r_date = '/\<b\>(.+?)\<\/b\>/';
preg_match($r_header,$data,$header);
preg_match($r_date, $header[1], $date);
echo $date[1];
?>
</code></pre>
<p>I've checked the regular expressions <a href="http://www.quanetic.com/regex.php" rel="nofollow noreferrer">here</a> and they appear to be valid. If I check just $url or $data they come out correctly and if I print $data and check the source the code that I'm looking for to use in the regex is in there. If you're interested in checking anything, an example of a proper URL would be <a href="http://biz.yahoo.com/research/earncal/g/goog.html" rel="nofollow noreferrer">http://biz.yahoo.com/research/earncal/g/goog.html</a></p>
<p>I've tried everything I could think of, including both var_dump($header) and var_dump($date), both of which return empty arrays.</p>
<p>I have been able to create other regular expressions that works. For instance, the following correctly returns "Earnings":</p>
<pre><code>$r_header = '/Company (.+?) Calendar/';
preg_match($r_header,$data,$header);
echo $header[1];
</code></pre>
<p>I am going nuts trying to figure out why this isn't working. Any help would be awesome. Thanks.</p>
|
[
{
"answer_id": 223358,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 0,
"selected": false,
"text": "<p>I think this is because you're applying the values to the regex as if it's plain text. However, it's HTML. For example, your regex should be modified to parse: </p>\n\n<p><code><a href=\"...\">Prev. Week</a> ...</code> </p>\n\n<p>Not to parse regular plain text like: \"Prev. Week ....\"</p>\n"
},
{
"answer_id": 223366,
"author": "J.T. Grimes",
"author_id": 1676,
"author_profile": "https://Stackoverflow.com/users/1676",
"pm_score": 2,
"selected": false,
"text": "<p>Your regex doesn't allow for the line breaks in the HTML Try:</p>\n\n<pre><code>$r_header = '/Prev\\. Week((?s:.*))Next Week/';\n</code></pre>\n\n<p>The <code>s</code> tells it to match the newline characters in the <code>.</code> (match any).</p>\n"
},
{
"answer_id": 223377,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Dot does not match newlines by default. Use <code>/your-regex/s</code></li>\n<li><code>$r_header</code> should probably be <code>/Prev\\. Week(.+?)Next Week/s</code></li>\n<li>FYI: You don't need to escape <code><</code> and <code>></code> in a regex.</li>\n</ol>\n"
},
{
"answer_id": 223380,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>Problem is that the HTML has newlines in it, which you need to incorporate with the s regex modifier, as below</p>\n\n<pre><code><?php\n$stock = \"goog\";//$_GET[s]; //returns stock ticker symbol eg GOOG or YHOO\n$first = $stock[0];\n\n$url = \"http://biz.yahoo.com/research/earncal/\".$first.\"/\".$stock.\".html\";\n$data = file_get_contents($url);\n\n$r_header = '/Prev. Week(.+?)Next Week/s';\n$r_date = '/\\<b\\>(.+?)\\<\\/b\\>/s';\n\n\npreg_match($r_header,$data,$header);\npreg_match($r_date, $header[1], $date);\n\nvar_dump($header);\n?>\n</code></pre>\n"
},
{
"answer_id": 223390,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>You want to add the <code>s (PCRE_DOTALL)</code> modifier. By default <code>.</code> doesn't match newline, and I see the page has them between the two parts you look for.</p>\n\n<p><strong>Side note:</strong> although they don't hurt (except readability), you don't need a backslash before <code><</code> and <code>></code>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30098/"
] |
I am using the following code:
```
<?php
$stock = $_GET[s]; //returns stock ticker symbol eg GOOG or YHOO
$first = $stock[0];
$url = "http://biz.yahoo.com/research/earncal/".$first."/".$stock.".html";
$data = file_get_contents($url);
$r_header = '/Prev. Week(.+?)Next Week/';
$r_date = '/\<b\>(.+?)\<\/b\>/';
preg_match($r_header,$data,$header);
preg_match($r_date, $header[1], $date);
echo $date[1];
?>
```
I've checked the regular expressions [here](http://www.quanetic.com/regex.php) and they appear to be valid. If I check just $url or $data they come out correctly and if I print $data and check the source the code that I'm looking for to use in the regex is in there. If you're interested in checking anything, an example of a proper URL would be <http://biz.yahoo.com/research/earncal/g/goog.html>
I've tried everything I could think of, including both var\_dump($header) and var\_dump($date), both of which return empty arrays.
I have been able to create other regular expressions that works. For instance, the following correctly returns "Earnings":
```
$r_header = '/Company (.+?) Calendar/';
preg_match($r_header,$data,$header);
echo $header[1];
```
I am going nuts trying to figure out why this isn't working. Any help would be awesome. Thanks.
|
Problem is that the HTML has newlines in it, which you need to incorporate with the s regex modifier, as below
```
<?php
$stock = "goog";//$_GET[s]; //returns stock ticker symbol eg GOOG or YHOO
$first = $stock[0];
$url = "http://biz.yahoo.com/research/earncal/".$first."/".$stock.".html";
$data = file_get_contents($url);
$r_header = '/Prev. Week(.+?)Next Week/s';
$r_date = '/\<b\>(.+?)\<\/b\>/s';
preg_match($r_header,$data,$header);
preg_match($r_date, $header[1], $date);
var_dump($header);
?>
```
|
223,308 |
<p>I am trying to use page methods in my asp.net page. I have enable page methods set to true on the script manager, the webmethod attribute defined on the method, the function is public static string, I know the function works because when I run it from my code behind it generates the expected result, but when I call it via page method in my result function the result is always alerted as undefined. If I use fiddler it doesn't even look like there is additional traffic or a new request created. I'm running the site on port 82 if that makes a difference. I'm at a loss here. Can someone give me some pointers?</p>
|
[
{
"answer_id": 223464,
"author": "Chris Westbrook",
"author_id": 16891,
"author_profile": "https://Stackoverflow.com/users/16891",
"pm_score": 0,
"selected": false,
"text": "<p>OK, stupid me. Here is some code. </p>\n\n<pre><code> function getName()\n {\n var ddlAdCodes=$get('<%=ddlAdCodes.ClientID %>');\n var value=ddlAdCodes.options[ddlAdCodes.selectedIndex].value;\n //alert(value);\n PageMethods.getAdCodeInfo(value,onSuccess(),onError());\n }\n\n function onSuccess(result)\n {\n alert(result);\n }\n\n function onError(error)\n {\n alert(\"error \"+error);\n }\n</code></pre>\n"
},
{
"answer_id": 223513,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": true,
"text": "<p>In your PagesMethods call, remove the parentheses from the callback and error functions:</p>\n\n<pre><code>PageMethods.getAdCodeInfo(value, onSuccess, onError)\n</code></pre>\n\n<p><code>onSuccess</code> and <code>onError</code> are basically variables that point to the functions. So you don't need parentheses for variable names.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16891/"
] |
I am trying to use page methods in my asp.net page. I have enable page methods set to true on the script manager, the webmethod attribute defined on the method, the function is public static string, I know the function works because when I run it from my code behind it generates the expected result, but when I call it via page method in my result function the result is always alerted as undefined. If I use fiddler it doesn't even look like there is additional traffic or a new request created. I'm running the site on port 82 if that makes a difference. I'm at a loss here. Can someone give me some pointers?
|
In your PagesMethods call, remove the parentheses from the callback and error functions:
```
PageMethods.getAdCodeInfo(value, onSuccess, onError)
```
`onSuccess` and `onError` are basically variables that point to the functions. So you don't need parentheses for variable names.
|
223,312 |
<p>Quite simple really:</p>
<pre><code>var req:URLRequest=new URLRequest();
req.url="http://somesite.com";
var header:URLRequestHeader=new URLRequestHeader("my-bespoke-header","1");
req.requestHeaders.push(header);
req.method=URLRequestMethod.GET;
stream.load(req);
</code></pre>
<p>Yet, if I inspect the traffic with WireShark, the <code>my-bespoke-header</code> is not being sent. If I change to <code>URLRequestMethod.POST</code> and append some data to <code>req.data</code>, then the header is sent, but the receiving application requires a GET not a POST. </p>
<p>The documentation mentions a blacklist of headers that will not get sent. <code>my-bespoke-header</code> is not one of these. It's possibly worth mentioning that the originating request is from a different port on the same domain. Nothing is reported in the policyfile log, so it seems unlikely, but is this something that can be remedied by force loading a crossdomain.xml with a <code>allow-http-request-headers-from</code> despite the fact that this is not a crossdomain issue? Or is it simply an undocumented feature of the Flash Player that it can only send custom headers with a POST request?</p>
|
[
{
"answer_id": 223464,
"author": "Chris Westbrook",
"author_id": 16891,
"author_profile": "https://Stackoverflow.com/users/16891",
"pm_score": 0,
"selected": false,
"text": "<p>OK, stupid me. Here is some code. </p>\n\n<pre><code> function getName()\n {\n var ddlAdCodes=$get('<%=ddlAdCodes.ClientID %>');\n var value=ddlAdCodes.options[ddlAdCodes.selectedIndex].value;\n //alert(value);\n PageMethods.getAdCodeInfo(value,onSuccess(),onError());\n }\n\n function onSuccess(result)\n {\n alert(result);\n }\n\n function onError(error)\n {\n alert(\"error \"+error);\n }\n</code></pre>\n"
},
{
"answer_id": 223513,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": true,
"text": "<p>In your PagesMethods call, remove the parentheses from the callback and error functions:</p>\n\n<pre><code>PageMethods.getAdCodeInfo(value, onSuccess, onError)\n</code></pre>\n\n<p><code>onSuccess</code> and <code>onError</code> are basically variables that point to the functions. So you don't need parentheses for variable names.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14357/"
] |
Quite simple really:
```
var req:URLRequest=new URLRequest();
req.url="http://somesite.com";
var header:URLRequestHeader=new URLRequestHeader("my-bespoke-header","1");
req.requestHeaders.push(header);
req.method=URLRequestMethod.GET;
stream.load(req);
```
Yet, if I inspect the traffic with WireShark, the `my-bespoke-header` is not being sent. If I change to `URLRequestMethod.POST` and append some data to `req.data`, then the header is sent, but the receiving application requires a GET not a POST.
The documentation mentions a blacklist of headers that will not get sent. `my-bespoke-header` is not one of these. It's possibly worth mentioning that the originating request is from a different port on the same domain. Nothing is reported in the policyfile log, so it seems unlikely, but is this something that can be remedied by force loading a crossdomain.xml with a `allow-http-request-headers-from` despite the fact that this is not a crossdomain issue? Or is it simply an undocumented feature of the Flash Player that it can only send custom headers with a POST request?
|
In your PagesMethods call, remove the parentheses from the callback and error functions:
```
PageMethods.getAdCodeInfo(value, onSuccess, onError)
```
`onSuccess` and `onError` are basically variables that point to the functions. So you don't need parentheses for variable names.
|
223,313 |
<p>What is MySQL equivalent of the <code>Nz</code> Function in Microsoft Access? Is <code>Nz</code> a SQL standard?</p>
<p>In Access, the <code>Nz</code> function lets you return a value when a variant is null. <a href="http://www.techonthenet.com/access/functions/advanced/nz.php" rel="nofollow noreferrer">Source</a></p>
<p>The syntax for the <code>Nz</code> function is:</p>
<pre><code>Nz ( variant, [ value_if_null ] )
</code></pre>
|
[
{
"answer_id": 223329,
"author": "Mike Wills",
"author_id": 2535,
"author_profile": "https://Stackoverflow.com/users/2535",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to look at <code>IFNULL</code> or <code>COALESCE</code>. If I recall correctly, <code>IFNULL</code> works for MySQL.</p>\n"
},
{
"answer_id": 223560,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "<p>The <a href=\"https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_coalesce\" rel=\"nofollow noreferrer\"><code>COALESCE()</code></a> function does what you describe. It's standard SQL and it should be supported in all SQL databases.</p>\n<p>The <a href=\"https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_ifnull\" rel=\"nofollow noreferrer\"><code>IFNULL()</code></a> function is not standard SQL. Only some brands of databases support this function.</p>\n"
},
{
"answer_id": 7262793,
"author": "Dan Tupper",
"author_id": 922380,
"author_profile": "https://Stackoverflow.com/users/922380",
"pm_score": -1,
"selected": false,
"text": "<p>Perhaps Knowing what MS Access NZ() Function actually does would be helpful (prior to answering with completely invalid suggestions). The NZ() Function test for Null and Replaces the Null with an empty string, a Zero or optionally a value that the user enters.</p>\n\n<p>COALESCE doesn't even come close, in fact it returns a Null if no none Null values in a 'List???' </p>\n\n<p>IFNULL() Function is what you're looking for.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html</a></p>\n"
},
{
"answer_id": 16490031,
"author": "diamondsea",
"author_id": 2209980,
"author_profile": "https://Stackoverflow.com/users/2209980",
"pm_score": 2,
"selected": false,
"text": "<p>COALESCE does just what the OP is asking for, as does IFNULL:</p>\n\n<pre><code>SELECT Nz(MightBeNullVar, 0) FROM ... (MS Access version)\nSELECT COALESCE(MightBeNullVar, 0) FROM ... (MySQL version)\nSELECT IFNULL(MightBeNullVar, 0) FROM ... (MySQL version)\n</code></pre>\n\n<p>The difference is the COALESCE can search through multiple variables and return the first non-null one:</p>\n\n<pre><code>SELECT COALESCE(MightBeNullVar, MightAlsoBeNullVar, CouldBeNullVar, 0) FROM ... (MySQL version)\n</code></pre>\n\n<p>each of these will return a 0 (zero) if none of the values have a set value (are null).</p>\n\n<p>The IFNULL is (pretty meaninglessly) faster. There's probably other better things to optimize in your query before bothering with IFNULL vs COALESCE issues. If you have multiple things to check, use COALESCE. If you only have a single value to check, use IFNULL.</p>\n"
},
{
"answer_id": 20267608,
"author": "minalud",
"author_id": 3046116,
"author_profile": "https://Stackoverflow.com/users/3046116",
"pm_score": 0,
"selected": false,
"text": "<p>Have look to the null safe operator <=></p>\n\n<p>Maybe it could help :\n<a href=\"http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_equal-to\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_equal-to</a></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30076/"
] |
What is MySQL equivalent of the `Nz` Function in Microsoft Access? Is `Nz` a SQL standard?
In Access, the `Nz` function lets you return a value when a variant is null. [Source](http://www.techonthenet.com/access/functions/advanced/nz.php)
The syntax for the `Nz` function is:
```
Nz ( variant, [ value_if_null ] )
```
|
The [`COALESCE()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_coalesce) function does what you describe. It's standard SQL and it should be supported in all SQL databases.
The [`IFNULL()`](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_ifnull) function is not standard SQL. Only some brands of databases support this function.
|
223,317 |
<p>This may not be the correct way to use controllers, but I did notice this problem and hadn't figured out a way to correct it. </p>
<pre><code>public JsonResult SomeControllerAction() {
//The current method has the HttpContext just fine
bool currentIsNotNull = (this.HttpContext == null); //which is false
//creating a new instance of another controller
SomeOtherController controller = new SomeOtherController();
bool isNull = (controller.HttpContext == null); // which is true
//The actual HttpContext is fine in both
bool notNull = (System.Web.HttpContext.Current == null); // which is false
}
</code></pre>
<p>I've noticed that the HttpContext on a Controller isn't the "actual" HttpContext that you would find in System.Web.HttpContext.Current. </p>
<p>Is there some way to manually populate the HttpContextBase on a Controller? Or a better way to create an instance of a Controller?</p>
|
[
{
"answer_id": 223334,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": 0,
"selected": false,
"text": "<p>Is it that you want to use some functionality from the controller? Or have the controller perform an action?</p>\n\n<p>If it's the former, maybe that's some code that should be split out into another class. If it's the latter, you can do this to simply have that controller do a specific action:</p>\n\n<pre>\n<code>\nreturn RedirectToAction(\"SomeAction\", \"SomeOtherController\", new {param1 = \"Something\" });\n</code>\n</pre>\n"
},
{
"answer_id": 223824,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 3,
"selected": false,
"text": "<p>The HttpContext, in the ControllerContext is null because it is not set when the controller is created. The contructor of the controller does not assign this property, so it will be null. Normally, the HttpContext is set to the HttpContext of the ControllerBuilder class. Controllers are created by the ControllerBuilder class, followed by the DefaultControllerFactory. When you want to create your own instance of a controller, you can use the ExecuteMethod of the controller with your own ControllerContext. You don't want to do that is a real application. When you get some more experience with the framework you will find the appropriate method to do want you want. When you need ControllerContext in Unit test, you can use a mocking framework to mock the ControllerContext or you can class faking it.</p>\n\n<p>You can find a model of the request flow in asp.net mvc on <a href=\"http://www.codethinked.com/post/2008/09/27/ASPNET-MVC-Request-Flow.aspx\" rel=\"noreferrer\">this blog</a>.</p>\n\n<p>When your new to Asp.net mvc, it's worth the effort to download the source code and read an trace the route how a request is processed.</p>\n"
},
{
"answer_id": 225798,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using a controller factory? If so, how are you registering components?</p>\n\n<p>I ran into this problem where I had inadvertently added an HttpContext-based dependency as a Singleton, rather than Transient in Windsor.</p>\n\n<p>HttpContext was null for all but the first request. It took me a while to track down that one.</p>\n"
},
{
"answer_id": 225912,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 6,
"selected": false,
"text": "<p>For now I'm going to do the following. This seems to be an acceptable fix...</p>\n\n<pre><code>public new HttpContextBase HttpContext {\n get {\n HttpContextWrapper context = \n new HttpContextWrapper(System.Web.HttpContext.Current);\n return (HttpContextBase)context; \n }\n}\n</code></pre>\n\n<p>Where this is added to a Controller class these Controllers are inheriting from.</p>\n\n<p>I'm not sure if the HttpContext being null is the desired behavior, but this will fix it in the meantime for me.</p>\n"
},
{
"answer_id": 225940,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 6,
"selected": true,
"text": "<p>Controllers are not designed to be created manually like you're doing. It sounds like what you really should be doing is putting whatever reusable logic you have into a helper class instead.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17091/"
] |
This may not be the correct way to use controllers, but I did notice this problem and hadn't figured out a way to correct it.
```
public JsonResult SomeControllerAction() {
//The current method has the HttpContext just fine
bool currentIsNotNull = (this.HttpContext == null); //which is false
//creating a new instance of another controller
SomeOtherController controller = new SomeOtherController();
bool isNull = (controller.HttpContext == null); // which is true
//The actual HttpContext is fine in both
bool notNull = (System.Web.HttpContext.Current == null); // which is false
}
```
I've noticed that the HttpContext on a Controller isn't the "actual" HttpContext that you would find in System.Web.HttpContext.Current.
Is there some way to manually populate the HttpContextBase on a Controller? Or a better way to create an instance of a Controller?
|
Controllers are not designed to be created manually like you're doing. It sounds like what you really should be doing is putting whatever reusable logic you have into a helper class instead.
|
223,322 |
<p>I'm trying to have a new layer appear above existing content on my site when a link/button is clicked. I am using jquery - but the code I have doesn't seem to work as expected.</p>
<p>Here is what I have:</p>
<pre><code> $(document).ready(function(){
$("#button").click(function () {
$("#showme").insertAfter("#bodytag")
$("#showme").fadeIn(2000);
});
</code></pre>
<p>});</p>
<p>The effect I'm after is to have <code><div id="showme">...</div></code> appear directly after the #bodytag. <code><div id="showme">...</div></code> has a z-index higher than anything else on the site, so it should just appear above the content directly after the #bodytag.</p>
<p>Thanks for the assistance.</p>
|
[
{
"answer_id": 223330,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure <code>#showme</code> has a <code>position</code> other than <code>static</code>.</p>\n"
},
{
"answer_id": 223379,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 3,
"selected": true,
"text": "<p>It would appear to me that to get the desired effect, the div you are inserting #showme into needs to be position: relative, and #showme should be position: absolute. Absolute positioning will take the element out of the document flow, allowing it to sit above the content.</p>\n\n<p>Also, two tips - $() is a shortcut for $(document), and you can chain jQuery commands:</p>\n\n<pre><code>$().ready(function(){\n $(\"#button\").click(function () {\n $(\"#showme\").insertAfter(\"#bodytag\").fadeIn(2000);\n });\n});\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to have a new layer appear above existing content on my site when a link/button is clicked. I am using jquery - but the code I have doesn't seem to work as expected.
Here is what I have:
```
$(document).ready(function(){
$("#button").click(function () {
$("#showme").insertAfter("#bodytag")
$("#showme").fadeIn(2000);
});
```
});
The effect I'm after is to have `<div id="showme">...</div>` appear directly after the #bodytag. `<div id="showme">...</div>` has a z-index higher than anything else on the site, so it should just appear above the content directly after the #bodytag.
Thanks for the assistance.
|
It would appear to me that to get the desired effect, the div you are inserting #showme into needs to be position: relative, and #showme should be position: absolute. Absolute positioning will take the element out of the document flow, allowing it to sit above the content.
Also, two tips - $() is a shortcut for $(document), and you can chain jQuery commands:
```
$().ready(function(){
$("#button").click(function () {
$("#showme").insertAfter("#bodytag").fadeIn(2000);
});
});
```
|
223,324 |
<p><strong>Goal:</strong>
Allow the user to delete a record by dragging a row from an AdvancedDataGrid, dropping it onto a trash-can icon and verify the user meant to do that via a popup alert with "OK" and "Cancel" buttons. </p>
<p><strong>What is working:</strong>
<ul>
<li>Dragging/Dropping a row onto the trash icon.</li>
<li>If the user clicks the "OK" button, the record is deleted.</li>
<li>If the user clicks the "Cancel" button, the operation is canceled.</li>
</ul> </p>
<p><strong>Problem:</strong>
After the user clicks the "Cancel" button and the popup alert closes, no rows in the ADG can be dragged. I've discovered that after sorting the ADG, by clicking on a column header, the user can begin dragging rows again. </p>
<p><strong>Code:</strong> (changed from original post) </p>
<pre><code><mx:Image source="{trashImage}" buttonMode="true"
toolTip="drag a participant here to delete them from the project"
dragDrop="deleteParticipantDrop(event)" dragEnter="deleteParticipantEnter(event)"
dragExit="deleteParticipantDragExit(event)" top="4" right="122" id="image2" />
// trashImage Event Handlers:
private function deleteParticipantEnter(event:DragEvent):void
{
var component:IUIComponent = IUIComponent(event.currentTarget);
dragComponent = component;
DragManager.acceptDragDrop(component);
DragManager.showFeedback(DragManager.MOVE);
deleteParticipantDragEvent = event;
}
private function deleteParticipantDrop(event:DragEvent):void
{
var selectedKitNum:String = memberRpt.selectedItem.KitNum;
var selectedName:String = memberRpt.selectedItem.ParticipantName;
var component:IUIComponent = IUIComponent(event.currentTarget);
dragComponent = component;
DragManager.acceptDragDrop(component);
isEditingParticipantInfo = false;
isDeletingParticipant = true;
deleteParticipantDropEvent = event;
event.stopImmediatePropagation(); // Added as per mrm
alert.confirm("Are you sure you want to delete this participant, Kit #" + memberRpt.selectedItem.KitNum + " (" +
memberRpt.selectedItem.ParticipantName + ") from the project? This cannot be reversed!! An email will be " +
"sent to notify this participant and you will receive a copy of it for your records.", confirmRemoveParticipant);
}
private function deleteParticipantDragExit(event:DragEvent):void
{
var component:IUIComponent = IUIComponent(event.currentTarget);
dragComponent = component;
DragManager.acceptDragDrop(component);
DragManager.showFeedback(DragManager.NONE);
}
private function confirmRemoveParticipant(event:CloseEvent):void
{
if (event.detail == Alert.YES)
{
deleteReason = DeleteParticipantTitleWindow(PopUpManager.createPopUp( this, DeleteParticipantTitleWindow , true));
dispatchEvent(deleteParticipantDropEvent); // Added as per mrm
PopUpManager.centerPopUp(deleteReason);
deleteReason.showCloseButton = true;
deleteReason.title = "Reason for removal from project";
deleteReason.addEventListener("close", cleanupRemoveParticipant);
deleteReason["cancelButton"].addEventListener("click", cleanupRemoveParticipant);
deleteReason["okButton"].addEventListener("click", finalizeDeleteParticipant);
isDeletingParticipant = false;
}
else
{
cleanupRemoveParticipant();
}
}
private function cleanupRemoveParticipant(event:Event = null):void
{
memberRpt.invalidateDisplayList();
memberRpt.executeBindings();
if (deleteReason != null)
{
PopUpManager.removePopUp(deleteReason);
deleteReason = null;
}
}
public function finalizeDeleteParticipant(event:Event):void
{
if (deleteReason.reason.text != null)
{
selectedReportItem = memberRpt.selectedItem;
selectedReportItemIndex = memberRpt.selectedIndex;
memberReportData.removeItemAt(selectedReportItemIndex);
}
else
{
alert.info("You must provide a reason for removing a participant from your project!!");
}
cleanupRemoveParticipant();
}
</code></pre>
<p>Thanks in advance for all helpful suggestions. </p>
|
[
{
"answer_id": 223388,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 0,
"selected": false,
"text": "<p>Try refreshing the data bindings on the datagrid using executeBindings and/or invalidateDisplayList in the enclosing control. </p>\n\n<p>To be honest this sounds a bit like a bug. Have you posted this on <a href=\"http://tech.groups.yahoo.com/group/flexcoders/messages\" rel=\"nofollow noreferrer\">flexcoders</a>? The Adobe guys hang out on there (probably here too, but definitely there)</p>\n"
},
{
"answer_id": 223428,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 0,
"selected": false,
"text": "<p>Hang on... just spotted that between the drop event and the cancel button of the popup there is an asynchronous web service call which appears to be handled by GetParticipantOrderInformation. Is that correct? </p>\n\n<p>If yes, then have you tried offering a simpler dialog for Cancel before you do that? I wonder whether the combination of layers of events is causing a problem.</p>\n"
},
{
"answer_id": 223879,
"author": "Sean Staats",
"author_id": 30072,
"author_profile": "https://Stackoverflow.com/users/30072",
"pm_score": 0,
"selected": false,
"text": "<p>I didn't have any success with refreshing the data bindings on the datagrid via the executeBindings and invalidateDisplayList methods. I also didn't have any luck by showing the confirmation alert before making the webservice call. In fact, I discovered that making the webservice call was completely unnecessary and removed it. So now the code flows like this:</p>\n\n<ol>\n<li>Drag/drop ADG row onto trash icon.</li>\n<li>Display confirmation Alert box.</li>\n<li>If user clicked \"Cancel\" button, redisplay the ADG. </li>\n</ol>\n\n<p>But the same problem persists. I'll update the <strong>Code</strong> section with the latest code.</p>\n"
},
{
"answer_id": 224167,
"author": "mrm",
"author_id": 30191,
"author_profile": "https://Stackoverflow.com/users/30191",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an idea:\n- Just before you create the alert window, stop the DragEvent</p>\n\n<pre>event.stopImmediatePropagation();</pre>\n\n<ul>\n<li>store the event so we can resume if the user clicks the Yes button</li>\n</ul>\n\n<pre>queuedEvent = event as DragEvent;</pre>\n\n<ul>\n<li>show the alert window</li>\n<li>if the user clicks the yes button, resume the queued event</li>\n</ul>\n\n<pre>dispatchEvent(queuedEvent);</pre>\n"
},
{
"answer_id": 236974,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried running the validateNow() method on the ADG after the cancel event?</p>\n\n<p>Here is some more information on the validateNow() method. </p>\n\n<p><a href=\"http://www.judahfrangipane.com/blog/?p=220\" rel=\"nofollow noreferrer\">Why you need to know about validateNow...</a></p>\n\n<p>I really do think this is what you're looking for! Please let us know if that is the case...</p>\n"
},
{
"answer_id": 461276,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>DragManager.showFeedback(DragManager.NONE); </p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30072/"
] |
**Goal:**
Allow the user to delete a record by dragging a row from an AdvancedDataGrid, dropping it onto a trash-can icon and verify the user meant to do that via a popup alert with "OK" and "Cancel" buttons.
**What is working:**
* Dragging/Dropping a row onto the trash icon.
* If the user clicks the "OK" button, the record is deleted.
* If the user clicks the "Cancel" button, the operation is canceled.
**Problem:**
After the user clicks the "Cancel" button and the popup alert closes, no rows in the ADG can be dragged. I've discovered that after sorting the ADG, by clicking on a column header, the user can begin dragging rows again.
**Code:** (changed from original post)
```
<mx:Image source="{trashImage}" buttonMode="true"
toolTip="drag a participant here to delete them from the project"
dragDrop="deleteParticipantDrop(event)" dragEnter="deleteParticipantEnter(event)"
dragExit="deleteParticipantDragExit(event)" top="4" right="122" id="image2" />
// trashImage Event Handlers:
private function deleteParticipantEnter(event:DragEvent):void
{
var component:IUIComponent = IUIComponent(event.currentTarget);
dragComponent = component;
DragManager.acceptDragDrop(component);
DragManager.showFeedback(DragManager.MOVE);
deleteParticipantDragEvent = event;
}
private function deleteParticipantDrop(event:DragEvent):void
{
var selectedKitNum:String = memberRpt.selectedItem.KitNum;
var selectedName:String = memberRpt.selectedItem.ParticipantName;
var component:IUIComponent = IUIComponent(event.currentTarget);
dragComponent = component;
DragManager.acceptDragDrop(component);
isEditingParticipantInfo = false;
isDeletingParticipant = true;
deleteParticipantDropEvent = event;
event.stopImmediatePropagation(); // Added as per mrm
alert.confirm("Are you sure you want to delete this participant, Kit #" + memberRpt.selectedItem.KitNum + " (" +
memberRpt.selectedItem.ParticipantName + ") from the project? This cannot be reversed!! An email will be " +
"sent to notify this participant and you will receive a copy of it for your records.", confirmRemoveParticipant);
}
private function deleteParticipantDragExit(event:DragEvent):void
{
var component:IUIComponent = IUIComponent(event.currentTarget);
dragComponent = component;
DragManager.acceptDragDrop(component);
DragManager.showFeedback(DragManager.NONE);
}
private function confirmRemoveParticipant(event:CloseEvent):void
{
if (event.detail == Alert.YES)
{
deleteReason = DeleteParticipantTitleWindow(PopUpManager.createPopUp( this, DeleteParticipantTitleWindow , true));
dispatchEvent(deleteParticipantDropEvent); // Added as per mrm
PopUpManager.centerPopUp(deleteReason);
deleteReason.showCloseButton = true;
deleteReason.title = "Reason for removal from project";
deleteReason.addEventListener("close", cleanupRemoveParticipant);
deleteReason["cancelButton"].addEventListener("click", cleanupRemoveParticipant);
deleteReason["okButton"].addEventListener("click", finalizeDeleteParticipant);
isDeletingParticipant = false;
}
else
{
cleanupRemoveParticipant();
}
}
private function cleanupRemoveParticipant(event:Event = null):void
{
memberRpt.invalidateDisplayList();
memberRpt.executeBindings();
if (deleteReason != null)
{
PopUpManager.removePopUp(deleteReason);
deleteReason = null;
}
}
public function finalizeDeleteParticipant(event:Event):void
{
if (deleteReason.reason.text != null)
{
selectedReportItem = memberRpt.selectedItem;
selectedReportItemIndex = memberRpt.selectedIndex;
memberReportData.removeItemAt(selectedReportItemIndex);
}
else
{
alert.info("You must provide a reason for removing a participant from your project!!");
}
cleanupRemoveParticipant();
}
```
Thanks in advance for all helpful suggestions.
|
Have you tried running the validateNow() method on the ADG after the cancel event?
Here is some more information on the validateNow() method.
[Why you need to know about validateNow...](http://www.judahfrangipane.com/blog/?p=220)
I really do think this is what you're looking for! Please let us know if that is the case...
|
223,328 |
<p>I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell':</p>
<p>here is my HTML snippet:</p>
<p>headerRows[0][10].contents</p>
<pre><code> [<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3">
</font></font></font>]
</code></pre>
<p>Note that this is a list item from Python [].</p>
<p>I need the value Apples Produced but can't get to it.</p>
<p>Any suggestions would be appreciated</p>
<p>Suggestions on a good book that explains this would earn my eternal gratitude</p>
<hr>
<p>Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute</p>
<p>say it is:</p>
<pre><code> [<font size="+0"><font face="serif" size="1"><I>Apples Produced</I><font size="3">
</font></font></font>]
</code></pre>
<p><I>Apples Produced</I><br>
</p>
<p>I am trying to learn to read/understand the documentation and your response will help</p>
<p>I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and now I am learning python and I am amazed at its power - BeautifulSoup is an example. Making a coherent whole of the documentation is tough for me.</p>
<p>Cheers</p>
|
[
{
"answer_id": 223534,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html\" rel=\"nofollow noreferrer\">BeautifulSoup documentation</a> should cover everything you need - in this case it looks like you want to use <code>findNext</code>:</p>\n\n<pre><code>headerRows[0][10].findNext('b').string\n</code></pre>\n\n<p>A more generic solution which doesn't rely on the <code><b></code> tag would be to use the <a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text\" rel=\"nofollow noreferrer\">text</a> argument to <code>findAll</code>, which allows you to search only for <code>NavigableString</code> objects:</p>\n\n<pre><code>>>> s = BeautifulSoup(u'<p>Test 1 <span>More</span> Test 2</p>')\n>>> u''.join([s.string for s in s.findAll(text=True)])\nu'Test 1 More Test 2'\n</code></pre>\n"
},
{
"answer_id": 223994,
"author": "ThePants",
"author_id": 29260,
"author_profile": "https://Stackoverflow.com/users/29260",
"pm_score": 0,
"selected": false,
"text": "<p>I have a base class that I extend all Beautiful Soup classes with a bunch of methods that help me get at text within a group of elements that I don't necessarily want to rely on the structure of. One of those methods is the following:</p>\n\n<pre><code> def clean(self, val):\n if type(val) is not StringType: val = str(val)\n val = re.sub(r'<.*?>', '', s) #remove tags\n val = re.sub(\"\\s+\" , \" \", val) #collapse internal whitespace\n return val.strip() #remove leading & trailing whitespace\n</code></pre>\n"
},
{
"answer_id": 629326,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<pre><code>headerRows[0][10].contents[0].find('b').string\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30105/"
] |
I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell':
here is my HTML snippet:
headerRows[0][10].contents
```
[<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3">
</font></font></font>]
```
Note that this is a list item from Python [].
I need the value Apples Produced but can't get to it.
Any suggestions would be appreciated
Suggestions on a good book that explains this would earn my eternal gratitude
---
Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute
say it is:
```
[<font size="+0"><font face="serif" size="1"><I>Apples Produced</I><font size="3">
</font></font></font>]
```
*Apples Produced*
I am trying to learn to read/understand the documentation and your response will help
I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and now I am learning python and I am amazed at its power - BeautifulSoup is an example. Making a coherent whole of the documentation is tough for me.
Cheers
|
```
headerRows[0][10].contents[0].find('b').string
```
|
223,352 |
<p>I'm trying to determine the reason for a stalled process on Linux. It's a telecom application, running under fairly heavy load. There is a separate process for each of 8 T1 spans. Every so often, one of the processes will get very unresponsive - up to maybe 50 seconds before an event is noted in the normally very busy process's log.</p>
<p>It is likely some system resource that runs short. The obvious thing - CPU usage - looks to be OK. </p>
<p>Which linux utilities might be best for catching and analyzing this sort of thing, and be as unobtrusive about it as possible, as this is a highly loaded system? It would need to be processes rather than system oriented, it would seem. Maybe ongoing monitoring of /proc/pid/XX? Top wouldn't seem to be too useful here.</p>
|
[
{
"answer_id": 223364,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>You can strace the program in question and see what system calls it's making.</p>\n"
},
{
"answer_id": 223592,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 3,
"selected": false,
"text": "<p>If you are able to spot this \"moment of unresponsiveness\", then you might use strace to attach to the process in question during that time and try to figure out where it \"sleeps\":</p>\n\n<pre><code>strace -f -o LOG -p <pid>\n</code></pre>\n\n<p>More lightweight, but less reliable method:</p>\n\n<ol>\n<li><p>When process hangs, use top/ps/gdp/strace/ltrace to find out the state of the process (e.g. whether it waits in \"select\" or consumes 100% cpu in some library call)</p></li>\n<li><p>Knowing the general nature of the call in question, tailor the invocation of strace to log specific syscalls or groups of syscall. For example, to log only file access-related syscalls, use:</p>\n\n<pre><code>strace -e file -f -o LOG ....\n</code></pre></li>\n</ol>\n\n<p>If the strace is too heavy a tool for you, try monitoring:</p>\n\n<ol>\n<li><p>Memory usage with \"vmstat 1 > /some/log\" - maybe process is being swapped in (or out) during that time</p></li>\n<li><p>IO usage with vmstat/iotop - maybe some other process is thrashing the disks</p></li>\n<li><p>/proc/interrupts - maybe driver for your T1 card is experiencing problems?</p></li>\n</ol>\n"
},
{
"answer_id": 223687,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks - strace sounds useful. Catching the process at the right time will be part of the fun. I came up with a scheme to periodically write a time stamp into shared memory, then monitor with another process. Sending a SIGSTOP would then let me at least examine the application stack with gdb. I don't know if strace on a paused process will tell me much, but I could maybe then turn on strace and see what it will say. Or turn on strace and hit the process with a SIGCONT.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to determine the reason for a stalled process on Linux. It's a telecom application, running under fairly heavy load. There is a separate process for each of 8 T1 spans. Every so often, one of the processes will get very unresponsive - up to maybe 50 seconds before an event is noted in the normally very busy process's log.
It is likely some system resource that runs short. The obvious thing - CPU usage - looks to be OK.
Which linux utilities might be best for catching and analyzing this sort of thing, and be as unobtrusive about it as possible, as this is a highly loaded system? It would need to be processes rather than system oriented, it would seem. Maybe ongoing monitoring of /proc/pid/XX? Top wouldn't seem to be too useful here.
|
If you are able to spot this "moment of unresponsiveness", then you might use strace to attach to the process in question during that time and try to figure out where it "sleeps":
```
strace -f -o LOG -p <pid>
```
More lightweight, but less reliable method:
1. When process hangs, use top/ps/gdp/strace/ltrace to find out the state of the process (e.g. whether it waits in "select" or consumes 100% cpu in some library call)
2. Knowing the general nature of the call in question, tailor the invocation of strace to log specific syscalls or groups of syscall. For example, to log only file access-related syscalls, use:
```
strace -e file -f -o LOG ....
```
If the strace is too heavy a tool for you, try monitoring:
1. Memory usage with "vmstat 1 > /some/log" - maybe process is being swapped in (or out) during that time
2. IO usage with vmstat/iotop - maybe some other process is thrashing the disks
3. /proc/interrupts - maybe driver for your T1 card is experiencing problems?
|
223,354 |
<p>I've got a really simple rails question here but I can't seem to find the answer anywhere. I guess some of the problems stem from me following a tutorial for Rails 1.2 with Rails 2.1. Anyway..</p>
<p>I'm writing a blog system and I'm implementing the comments bit. I have comments displaying fine once I've created them using script/console, but getting the comment form itself working is the hard bit.</p>
<p>In posts_controller.rb I have</p>
<pre><code> def comment
Post.find(params[:id]).comments.create(params[:comment])
flash[:notice] = "Added comment"
#render :action => show
redirect_to :action => show
end
</code></pre>
<p>and in show.html.erb (the view) I have</p>
<pre><code><%= form_tag :action => "comment", :id => @post %>
<%= text_area "comment", "body" %><br>
<%= submit_tag "Post Comment" %>
</code></pre>
<p>When I submit the form it tries to go to the urb /posts/comment/1 which is obviously incorrect, and it complains that it can't find a template. Obviously I don't want a template there because I've told it to redirect to the show action because I want it to just re-display the post's show page, with the new comment there.</p>
<p>I've tried both the commented out line (render :action => show) and the redirect_to line, and neither seem to do anything at all.</p>
<p>I'm sure I'm missing something simple, but what is it?</p>
|
[
{
"answer_id": 223515,
"author": "Vitalie",
"author_id": 27913,
"author_profile": "https://Stackoverflow.com/users/27913",
"pm_score": -1,
"selected": false,
"text": "<p>yes, you use old rails style.</p>\n\n<p>Something new: </p>\n\n<pre><code> form_for :comment, :url => { :post_id => @post } do |f|\n f.text_area :body\n submit_tag \"Post\"\n end\n</code></pre>\n\n<p>you can use resources for posts and comments, search google for better tutorial or install rails 1.2.6: </p>\n\n<pre><code>gem install -v 1.2.6 rails\n</code></pre>\n"
},
{
"answer_id": 223555,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 0,
"selected": false,
"text": "<p>Rails 2.1 embraces \"RESTful resources\". <code>show</code> just happens to be the name of one of the predefined REST actions that all rails controllers use.</p>\n\n<p>Rails does some magic behind the scenes, and :show is equivalent to \"display this one specific element with a specific given ID\". Sounds like it's getting mixed up with that. The ID is probably defaulting to \"1\". Hence the generated URL you're seeing from the render call</p>\n\n<p>The Rails 2.1 way of doing it would use the following actions and templates:</p>\n\n<ul>\n<li><code>index</code> - displays the full list of comments</li>\n<li><code>create</code> - add a new comment</li>\n<li><code>show</code> - display a specific comment only (not the full list). Doesn't sound like this is what you want, but the \"magic\" inside rails will default to this.</li>\n</ul>\n\n<p>There are also actions for <code>new</code> (show view to enter a new comment) <code>edit</code> (show view to do an edit of an existing comment) <code>update</code> (handle update submission) and <code>destroy</code> (duh), but it doesn't look like you'd use them in this example.</p>\n\n<p>Do you have a link to the tutorial? Wouldn't be too hard to port it to Rails 2.1 style.</p>\n"
},
{
"answer_id": 223580,
"author": "RichH",
"author_id": 16779,
"author_profile": "https://Stackoverflow.com/users/16779",
"pm_score": 4,
"selected": true,
"text": "<p>Does <code>redirect_to :action => 'show', :id => params[:id]</code> with quotes around show work?</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912/"
] |
I've got a really simple rails question here but I can't seem to find the answer anywhere. I guess some of the problems stem from me following a tutorial for Rails 1.2 with Rails 2.1. Anyway..
I'm writing a blog system and I'm implementing the comments bit. I have comments displaying fine once I've created them using script/console, but getting the comment form itself working is the hard bit.
In posts\_controller.rb I have
```
def comment
Post.find(params[:id]).comments.create(params[:comment])
flash[:notice] = "Added comment"
#render :action => show
redirect_to :action => show
end
```
and in show.html.erb (the view) I have
```
<%= form_tag :action => "comment", :id => @post %>
<%= text_area "comment", "body" %><br>
<%= submit_tag "Post Comment" %>
```
When I submit the form it tries to go to the urb /posts/comment/1 which is obviously incorrect, and it complains that it can't find a template. Obviously I don't want a template there because I've told it to redirect to the show action because I want it to just re-display the post's show page, with the new comment there.
I've tried both the commented out line (render :action => show) and the redirect\_to line, and neither seem to do anything at all.
I'm sure I'm missing something simple, but what is it?
|
Does `redirect_to :action => 'show', :id => params[:id]` with quotes around show work?
|
223,355 |
<p>I had a problem with committing changes after merging two branches of my project using TortoiseSVN.</p>
<p>Here are details:</p>
<p>I did a merge branch to trunk of <em>project</em> which I am working on. </p>
<p><em>Project</em> includes main repository and libraries joint to main repository as <em>svn external</em> (libraries are also branched) as subdirectory of <em>project</em>.</p>
<p>When I was trying to commit changes TortoiseSVN said:</p>
<pre><code>Commit A
re all the targets part of the same working copy?
Unable to lock 'D:\websites\project\lib'
Please execute the "Cleanup" command.
</code></pre>
<p>Of course <em>Cleanup</em> didn't help.</p>
<p><em>svn:external</em> keyword for <em>project</em> directory was well defined, also <em>lib</em> folder still contained proper version of libraries (trunk version).</p>
<p>Both SVN server and client are in 1.5.x version (TortoiseSVN is 1.5.3.x).</p>
<p>From technical point of view both <em>project</em> and <em>libraries</em> are projects in the same SVN repository.</p>
<p>Any idea what went wrong?</p>
<p>I had been googling a bit for the solution, but didn't find anything useful, so I tried to commit my changes in two steps:</p>
<ol>
<li>commit changes from project folder</li>
<li>commit changes from libraries folder</li>
</ol>
<p>Which went without any problems.</p>
<p>But I am still wondering why I couldn't commit everything in one commit.</p>
<p>EDITS:</p>
<ul>
<li>(After Ken G answer) Fixed version of TortoiseSVN 1.3.x -> 1.5.3.x.</li>
</ul>
|
[
{
"answer_id": 223374,
"author": "Josh Kodroff",
"author_id": 549,
"author_profile": "https://Stackoverflow.com/users/549",
"pm_score": 2,
"selected": false,
"text": "<p>I think I remember reading about a bug relating to this in TortoiseSVN that's been fixed in the latest release. Check the latest <a href=\"http://tortoisesvn.tigris.org/tsvn_1.5_releasenotes.html\" rel=\"nofollow noreferrer\">release notes</a>.</p>\n"
},
{
"answer_id": 223562,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "<p>1.3 of TortoiseSVN is <strong>very old</strong>, the latest revision being 1.5.x. There have been numerous changes in both Subversion and TortoiseSVN since 1.3, so upgrading your client is probably your best bet.</p>\n\n<p>Having said that, 1.5 TortoiseSVN is going to create/update Working Copies to a version 1.5 format. BE VERY CAREFUL when using TortoiseSVN (or any SVN client) against a previous Subversion's working copy.</p>\n"
},
{
"answer_id": 226244,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": true,
"text": "<p><strong><em>svn:external</em></strong> will cause Subversion to combine different repository paths on check-out, but ultimately those paths are still 'disjoint', so you have to do two commits to get the changes applied.</p>\n\n<p>Here's the relevant quote from <a href=\"http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.externals\" rel=\"nofollow noreferrer\">Version Control with Subversion</a></p>\n\n<blockquote>\n <p>And Subversion still truly operates\n only on nondisjoint working copies.\n So, for example, if you want to commit\n changes that you've made in one or\n more of those external working copies,\n you must run svn commit explicitly on\n those working copies—committing on the\n primary working copy will not recurse\n into any external ones.</p>\n</blockquote>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483/"
] |
I had a problem with committing changes after merging two branches of my project using TortoiseSVN.
Here are details:
I did a merge branch to trunk of *project* which I am working on.
*Project* includes main repository and libraries joint to main repository as *svn external* (libraries are also branched) as subdirectory of *project*.
When I was trying to commit changes TortoiseSVN said:
```
Commit A
re all the targets part of the same working copy?
Unable to lock 'D:\websites\project\lib'
Please execute the "Cleanup" command.
```
Of course *Cleanup* didn't help.
*svn:external* keyword for *project* directory was well defined, also *lib* folder still contained proper version of libraries (trunk version).
Both SVN server and client are in 1.5.x version (TortoiseSVN is 1.5.3.x).
From technical point of view both *project* and *libraries* are projects in the same SVN repository.
Any idea what went wrong?
I had been googling a bit for the solution, but didn't find anything useful, so I tried to commit my changes in two steps:
1. commit changes from project folder
2. commit changes from libraries folder
Which went without any problems.
But I am still wondering why I couldn't commit everything in one commit.
EDITS:
* (After Ken G answer) Fixed version of TortoiseSVN 1.3.x -> 1.5.3.x.
|
***svn:external*** will cause Subversion to combine different repository paths on check-out, but ultimately those paths are still 'disjoint', so you have to do two commits to get the changes applied.
Here's the relevant quote from [Version Control with Subversion](http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.externals)
>
> And Subversion still truly operates
> only on nondisjoint working copies.
> So, for example, if you want to commit
> changes that you've made in one or
> more of those external working copies,
> you must run svn commit explicitly on
> those working copies—committing on the
> primary working copy will not recurse
> into any external ones.
>
>
>
|
223,356 |
<pre><code>url = "http://example.com/file.xml"
data = urllib2.urlopen(url)
data.read()
</code></pre>
<p>The question is, when exactly will the file be downloaded from the internet? When i do urlopen or .read()? On my network interface I see high traffic both times. </p>
|
[
{
"answer_id": 223374,
"author": "Josh Kodroff",
"author_id": 549,
"author_profile": "https://Stackoverflow.com/users/549",
"pm_score": 2,
"selected": false,
"text": "<p>I think I remember reading about a bug relating to this in TortoiseSVN that's been fixed in the latest release. Check the latest <a href=\"http://tortoisesvn.tigris.org/tsvn_1.5_releasenotes.html\" rel=\"nofollow noreferrer\">release notes</a>.</p>\n"
},
{
"answer_id": 223562,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "<p>1.3 of TortoiseSVN is <strong>very old</strong>, the latest revision being 1.5.x. There have been numerous changes in both Subversion and TortoiseSVN since 1.3, so upgrading your client is probably your best bet.</p>\n\n<p>Having said that, 1.5 TortoiseSVN is going to create/update Working Copies to a version 1.5 format. BE VERY CAREFUL when using TortoiseSVN (or any SVN client) against a previous Subversion's working copy.</p>\n"
},
{
"answer_id": 226244,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": true,
"text": "<p><strong><em>svn:external</em></strong> will cause Subversion to combine different repository paths on check-out, but ultimately those paths are still 'disjoint', so you have to do two commits to get the changes applied.</p>\n\n<p>Here's the relevant quote from <a href=\"http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.externals\" rel=\"nofollow noreferrer\">Version Control with Subversion</a></p>\n\n<blockquote>\n <p>And Subversion still truly operates\n only on nondisjoint working copies.\n So, for example, if you want to commit\n changes that you've made in one or\n more of those external working copies,\n you must run svn commit explicitly on\n those working copies—committing on the\n primary working copy will not recurse\n into any external ones.</p>\n</blockquote>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20955/"
] |
```
url = "http://example.com/file.xml"
data = urllib2.urlopen(url)
data.read()
```
The question is, when exactly will the file be downloaded from the internet? When i do urlopen or .read()? On my network interface I see high traffic both times.
|
***svn:external*** will cause Subversion to combine different repository paths on check-out, but ultimately those paths are still 'disjoint', so you have to do two commits to get the changes applied.
Here's the relevant quote from [Version Control with Subversion](http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.externals)
>
> And Subversion still truly operates
> only on nondisjoint working copies.
> So, for example, if you want to commit
> changes that you've made in one or
> more of those external working copies,
> you must run svn commit explicitly on
> those working copies—committing on the
> primary working copy will not recurse
> into any external ones.
>
>
>
|
223,393 |
<p>What is the Perl equivalent of <code>strlen()</code>?</p>
|
[
{
"answer_id": 223401,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 7,
"selected": true,
"text": "<p><code>length($string)</code></p>\n<pre>perldoc -f length\n\n length EXPR\n length Returns the length in characters of the value of EXPR. If EXPR is\n omitted, returns length of $_. Note that this cannot be used on an\n entire array or hash to find out how many elements these have. For\n that, use \"scalar @array\" and \"scalar keys %hash\" respectively.\n\n Note the characters: if the EXPR is in Unicode, you will get the num-\n ber of characters, not the number of bytes. To get the length in\n bytes, use \"do { use bytes; length(EXPR) }\", see bytes.\n</pre>\n"
},
{
"answer_id": 224035,
"author": "JDrago",
"author_id": 29060,
"author_profile": "https://Stackoverflow.com/users/29060",
"pm_score": 5,
"selected": false,
"text": "<pre><code>length($string)\n</code></pre>\n"
},
{
"answer_id": 225944,
"author": "Yanick",
"author_id": 10356,
"author_profile": "https://Stackoverflow.com/users/10356",
"pm_score": 5,
"selected": false,
"text": "<p>Although 'length()' is the correct answer that should be used in any sane code, <a href=\"https://web.archive.org/web/20071024192714/http://www.perlfoundation.org/perl5/index.cgi?abigail_s_length_horror\" rel=\"noreferrer\">Abigail's length horror</a> should be mentioned, if only for the sake of Perl lore. </p>\n\n<p>Basically, the trick consists of using the return value of the catch-all transliteration operator:</p>\n\n<pre><code>print \"foo\" =~ y===c; # prints 3\n</code></pre>\n\n<p>y///c replaces all characters with themselves (thanks to the complement option 'c'), and returns the number of character replaced (so, effectively, the length of the string).</p>\n"
},
{
"answer_id": 48983029,
"author": "RANA DINESH",
"author_id": 8556604,
"author_profile": "https://Stackoverflow.com/users/8556604",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>length()</code> function:</p>\n\n<pre><code>$string ='String Name';\n$size=length($string);\n</code></pre>\n"
},
{
"answer_id": 56991682,
"author": "pslessard",
"author_id": 11631864,
"author_profile": "https://Stackoverflow.com/users/11631864",
"pm_score": 0,
"selected": false,
"text": "<p>You shouldn't use this, since length($string) is simpler and more readable, but I came across some of these while looking through code and was confused, so in case anyone else does, these also get the length of a string:</p>\n\n<pre><code>my $length = map $_, $str =~ /(.)/gs;\nmy $length = () = $str =~ /(.)/gs;\nmy $length = split '', $str;\n</code></pre>\n\n<p>The first two work by using the global flag to match each character in the string, then using the returned list of matches in a scalar context to get the number of characters. The third works similarly by splitting on each character instead of regex-matching and using the resulting list in scalar context</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
What is the Perl equivalent of `strlen()`?
|
`length($string)`
```
perldoc -f length
length EXPR
length Returns the length in characters of the value of EXPR. If EXPR is
omitted, returns length of $_. Note that this cannot be used on an
entire array or hash to find out how many elements these have. For
that, use "scalar @array" and "scalar keys %hash" respectively.
Note the characters: if the EXPR is in Unicode, you will get the num-
ber of characters, not the number of bytes. To get the length in
bytes, use "do { use bytes; length(EXPR) }", see bytes.
```
|
223,400 |
<p>I've just started learning linq and lambda expressions, and they seem to be a good fit for finding duplicates in a complex object collection, but I'm getting a little confused and hope someone can help put me back on the path to happy coding.</p>
<p>My object is structured like list.list.uniqueCustomerIdentifier</p>
<p>I need to ensure there are no duplicate uniqueCustomerIdentifier with in the entire complex object. If there are duplicates, I need to identify which are duplicated and return a list of the duplicates.</p>
|
[
{
"answer_id": 223414,
"author": "smaclell",
"author_id": 22914,
"author_profile": "https://Stackoverflow.com/users/22914",
"pm_score": 2,
"selected": false,
"text": "<p>There is a linq operator Distinct( ), that allows you to filter down to a distinct set of records if you only want the ids. If you have setup your class to override equals you or have an <a href=\"http://msdn.microsoft.com/en-us/library/ms132151.aspx\" rel=\"nofollow noreferrer\">IEqualityComparer</a> you can directly call the Distinct extension method to return the unique results from the list. As an added bonus you can also use the Union and Intersect methods to merge or filter between two lists.</p>\n\n<p>Another option would be to group by the id and then select the first element. </p>\n\n<pre><code>var results = from item in list\n group item by item.id into g\n select g.First();\n</code></pre>\n"
},
{
"answer_id": 223479,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to flatten the two list hierarchies, use the <code>SelectMany</code> method to flatten an <code>IEnumerable<IEnumerable<T>></code> into <code>IEnumerable<T></code>.</p>\n"
},
{
"answer_id": 224013,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "<ul>\n<li>Unpack the hierarchy</li>\n<li>Project each element to its uniqueID property</li>\n<li>Group these ID's up</li>\n<li>Filter the groups by groups that have more than 1 element</li>\n<li>Project each group to the group's key (back to uniqueID)</li>\n<li>Enumerate the query and store the result in a list.</li>\n</ul>\n\n<hr>\n\n<pre><code>var result = \n myList\n .SelectMany(x => x.InnerList)\n .Select(y => y.uniqueCustomerIdentifier)\n .GroupBy(id => id)\n .Where(g => g.Skip(1).Any())\n .Select(g => g.Key)\n .ToList()\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22706/"
] |
I've just started learning linq and lambda expressions, and they seem to be a good fit for finding duplicates in a complex object collection, but I'm getting a little confused and hope someone can help put me back on the path to happy coding.
My object is structured like list.list.uniqueCustomerIdentifier
I need to ensure there are no duplicate uniqueCustomerIdentifier with in the entire complex object. If there are duplicates, I need to identify which are duplicated and return a list of the duplicates.
|
* Unpack the hierarchy
* Project each element to its uniqueID property
* Group these ID's up
* Filter the groups by groups that have more than 1 element
* Project each group to the group's key (back to uniqueID)
* Enumerate the query and store the result in a list.
---
```
var result =
myList
.SelectMany(x => x.InnerList)
.Select(y => y.uniqueCustomerIdentifier)
.GroupBy(id => id)
.Where(g => g.Skip(1).Any())
.Select(g => g.Key)
.ToList()
```
|
223,433 |
<p>I get to dust off my VBScript hat and write some classic ASP to query a SQL Server 2000 database.</p>
<p>Here's the scenario:</p>
<ul>
<li>I have two <em>datetime</em> fields called <strong>fieldA</strong> and <strong>fieldB</strong>.</li>
<li><strong>fieldB</strong> will never have a year value that's greater than the year of <strong>fieldA</strong></li>
<li>It <strong>is</strong> possible the that two fields will have the same year.</li>
</ul>
<p>What I want is all records where <strong>fieldA</strong> >= <strong>fieldB</strong>, <em>independent of the year</em>. Just pretend that each field is just a month & day.</p>
<p>How can I get this? My knowledge of T-SQL date/time functions is spotty at best.</p>
|
[
{
"answer_id": 223446,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<pre><code>select *\nfrom t\nwhere datepart(month,t.fieldA) >= datepart(month,t.fieldB)\n or (datepart(month,t.fieldA) = datepart(month,t.fieldB)\n and datepart(day,t.fieldA) >= datepart(day,t.fieldB))\n</code></pre>\n\n<p>If you care about hours, minutes, seconds, you'll need to extend this to cover the cases, although it may be faster to cast to a suitable string, remove the year and compare.</p>\n\n<pre><code>select *\nfrom t\nwhere substring(convert(varchar,t.fieldA,21),5,20)\n >= substring(convert(varchar,t.fieldB,21),5,20)\n</code></pre>\n"
},
{
"answer_id": 223448,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 5,
"selected": true,
"text": "<p>You may want to use the built in time functions such as DAY and MONTH. e.g.</p>\n\n<pre><code>SELECT * from table where\nMONTH(fieldA) > MONTH(fieldB) OR(\nMONTH(fieldA) = MONTH(fieldB) AND DAY(fieldA) >= DAY(fieldB))\n</code></pre>\n\n<p>Selecting all rows where either the fieldA's month is greater or the months are the same and fieldA's day is greater.</p>\n"
},
{
"answer_id": 223463,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT *\nFROM SOME_TABLE\nWHERE MONTH(fieldA) > MONTH(fieldB)\nOR ( MONTH(fieldA) = MONTH(fieldB) AND DAY(fieldA) >= DAY(fieldB) )\n</code></pre>\n"
},
{
"answer_id": 223471,
"author": "Dave_H",
"author_id": 17109,
"author_profile": "https://Stackoverflow.com/users/17109",
"pm_score": 0,
"selected": false,
"text": "<p>I would approach this from a Julian date perspective, convert each field into the Julian date (number of days after the first of year), then compare those values. </p>\n\n<p>This may or may not produce desired results with respect to leap years.</p>\n\n<p>If you were worried about hours, minutes, seconds, etc., you could adjust the DateDiff functions to calculate the number of hours (or minutes or seconds) since the beginning of the year.</p>\n\n<pre>\nSELECT *\nFROM SOME_Table\nWHERE DateDiff(d, '1/01/' + Cast(DatePart(yy, fieldA) AS VarChar(5)), fieldA) >=\n DateDiff(d, '1/01/' + Cast(DatePart(yy, fieldB) AS VarChar(5)), fieldB)\n</pre>\n"
},
{
"answer_id": 23343503,
"author": "user3065891",
"author_id": 3065891,
"author_profile": "https://Stackoverflow.com/users/3065891",
"pm_score": 0,
"selected": false,
"text": "<p>Temp table for testing</p>\n\n<pre><code>Create table #t (calDate date)\nDeclare @curDate date = '2010-01-01'\nwhile @curDate < '2021-01-01'\nbegin\n insert into #t values (@curDate)\n Set @curDate = dateadd(dd,1,@curDate)\nend \n</code></pre>\n\n<p>Example of any date greater than or equal to today</p>\n\n<pre><code>Declare @testDate date = getdate()\nSELECT *\nFROM #t\nWHERE datediff(dd,dateadd(yy,1900 - year(@testDate),@testDate),dateadd(yy,1900 - year(calDate),calDate)) >= 0\n</code></pre>\n\n<p>One more example with any day less than today</p>\n\n<pre><code>Declare @testDate date = getdate()\nSELECT *\nFROM #t\nWHERE datediff(dd,dateadd(yy,1900 - year(@testDate),@testDate),dateadd(yy,1900 - year(calDate),calDate)) < 0\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
I get to dust off my VBScript hat and write some classic ASP to query a SQL Server 2000 database.
Here's the scenario:
* I have two *datetime* fields called **fieldA** and **fieldB**.
* **fieldB** will never have a year value that's greater than the year of **fieldA**
* It **is** possible the that two fields will have the same year.
What I want is all records where **fieldA** >= **fieldB**, *independent of the year*. Just pretend that each field is just a month & day.
How can I get this? My knowledge of T-SQL date/time functions is spotty at best.
|
You may want to use the built in time functions such as DAY and MONTH. e.g.
```
SELECT * from table where
MONTH(fieldA) > MONTH(fieldB) OR(
MONTH(fieldA) = MONTH(fieldB) AND DAY(fieldA) >= DAY(fieldB))
```
Selecting all rows where either the fieldA's month is greater or the months are the same and fieldA's day is greater.
|
223,436 |
<p>Consider the following SQL:</p>
<pre>
BEGIN TRAN
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
INSERT Bands
( Name )
SELECT 'Depeche Mode'
UNION
SELECT 'Arcade Fire'
-- I've indented the inner transaction to make it clearer.
BEGIN TRAN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT *
FROM Bands
COMMIT
-- What is the isolation level right here?
UPDATE Bands
SET Name = 'Modest Mouse'
WHERE Name = 'Oddest House'
COMMIT
</pre>
<p>In sum, we start a transaction and set its isolation level to <code>READ COMMITTED</code>. We then do some random SQL and start another, nested transaction. In this transaction we change the isolation level to <code>READ UNCOMMITTED</code>. We then commit that transaction and return to the other.</p>
<p>Now, my guess is that after the inner commit, the isolation level returns to <code>READ COMMITTED</code>. Is this correct?</p>
|
[
{
"answer_id": 223530,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 4,
"selected": true,
"text": "<p>I don't think that is correct.</p>\n\n<p>Refer to the remarks here: <a href=\"http://msdn.microsoft.com/en-us/library/ms173763(SQL.90).aspx\" rel=\"noreferrer\">Set Transaction</a></p>\n\n<blockquote>\n <p>Only one of the isolation level\n options can be set at a time, and it\n remains set for that connection until\n it is explicitly changed.</p>\n</blockquote>\n"
},
{
"answer_id": 224762,
"author": "Gregory Higley",
"author_id": 27779,
"author_profile": "https://Stackoverflow.com/users/27779",
"pm_score": 4,
"selected": false,
"text": "<p>You [Bob Probst] are correct. Interestingly, according to the <a href=\"http://msdn.microsoft.com/en-us/library/ms173763(SQL.90).aspx\" rel=\"noreferrer\">documentation</a> you linked:</p>\n\n<blockquote>\n <p>If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.</p>\n</blockquote>\n\n<p>So, the bottom line here is that SET TRANSACTION ISOLATION LEVEL has <em>procedure affinity</em>, not <em>transaction affinity</em> (as I had thought).</p>\n\n<p>Awesome!</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27779/"
] |
Consider the following SQL:
```
BEGIN TRAN
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
INSERT Bands
( Name )
SELECT 'Depeche Mode'
UNION
SELECT 'Arcade Fire'
-- I've indented the inner transaction to make it clearer.
BEGIN TRAN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT *
FROM Bands
COMMIT
-- What is the isolation level right here?
UPDATE Bands
SET Name = 'Modest Mouse'
WHERE Name = 'Oddest House'
COMMIT
```
In sum, we start a transaction and set its isolation level to `READ COMMITTED`. We then do some random SQL and start another, nested transaction. In this transaction we change the isolation level to `READ UNCOMMITTED`. We then commit that transaction and return to the other.
Now, my guess is that after the inner commit, the isolation level returns to `READ COMMITTED`. Is this correct?
|
I don't think that is correct.
Refer to the remarks here: [Set Transaction](http://msdn.microsoft.com/en-us/library/ms173763(SQL.90).aspx)
>
> Only one of the isolation level
> options can be set at a time, and it
> remains set for that connection until
> it is explicitly changed.
>
>
>
|
223,468 |
<p>Question: </p>
<pre><code>((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3))
</code></pre>
<p>This was #1 on the midterm, I put "81 9" he thought I forgot to cross one out lawl, so I cross out 81, and he goes aww. Anyways, I dont understand why it's 81.</p>
<p>I understand why <code>(lambda (x) (* x x)) (* 3 3) = 81</code>, but the first lambda I dont understand what the x and y values are there, and what the <code>[body] (x y)</code> does.</p>
<p>So I was hoping someone could explain to me why the first part doesn't seem like it does anything.</p>
|
[
{
"answer_id": 223484,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 4,
"selected": true,
"text": "<p>This needs some indentation to clarify</p>\n\n<pre><code>((lambda (x y) (x y))\n (lambda (x) (* x x))\n (* 3 3))\n</code></pre>\n\n<ul>\n<li><code>(lambda (x y) (x y))</code>; call <code>x</code> with <code>y</code> as only parameter.</li>\n<li><code>(lambda (x) (* x x))</code>; evaluate to the square of its parameter.</li>\n<li><code>(* 3 3)</code>; evaluate to 9</li>\n</ul>\n\n<p>So the whole thing means: \"call the square function with the 9 as parameter\".</p>\n\n<p>EDIT: The same thing could be written as</p>\n\n<pre><code>((lambda (x) (* x x))\n (* 3 3))\n</code></pre>\n\n<p>I guess the intent of the exercise is to highlight how evaluating a scheme form involves an implicit function application.</p>\n"
},
{
"answer_id": 223609,
"author": "Michał Kwiatkowski",
"author_id": 21998,
"author_profile": "https://Stackoverflow.com/users/21998",
"pm_score": 3,
"selected": false,
"text": "<p>Let's look at this again...</p>\n\n<pre><code>((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3))\n</code></pre>\n\n<p>To evaluate a form we evaluate each part of it in turn. We have three elements in our form. This one is on the first (function) position:</p>\n\n<pre><code>(lambda (x y) (x y))\n</code></pre>\n\n<p>This is a second element of a form and a first argument to the function:</p>\n\n<pre><code>(lambda (x) (* x x))\n</code></pre>\n\n<p>Last element of the form, so a second argument to the function.</p>\n\n<pre><code>(* 3 3)\n</code></pre>\n\n<p>Order of evaluation doesn't matter in this case, so let's just start from the left.</p>\n\n<pre><code>(lambda (x y) (x y))\n</code></pre>\n\n<p>Lambda creates a function, so this evaluates to a function that takes two arguments, x and y, and then applies x to y (in other words, calls x with a single argument y). Let's call this <strong>call-1</strong>.</p>\n\n<pre><code>(lambda (x) (* x x))\n</code></pre>\n\n<p>This evaluates to a function that takes a single argument and returns a square of this argument. So we can just call this <strong>square</strong>.</p>\n\n<pre><code>(* 3 3)\n</code></pre>\n\n<p>This obviously evaluates to <strong>9</strong>.</p>\n\n<p>OK, so after this first run of evaluation we have:</p>\n\n<pre><code>(call-1 square 9)\n</code></pre>\n\n<p>To evaluate this, we call <strong>call-1</strong> with two arguments, <strong>square</strong> and <strong>9</strong>. Applying <strong>call-1</strong> gives us:</p>\n\n<pre><code>(square 9)\n</code></pre>\n\n<p>Since that's what <strong>call-1</strong> does - it calls its first argument with its second argument. Now, square of <strong>9</strong> is <strong>81</strong>, which is the value of the whole expression.</p>\n"
},
{
"answer_id": 223917,
"author": "Luís Oliveira",
"author_id": 2967,
"author_profile": "https://Stackoverflow.com/users/2967",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps translating that code to Common Lisp helps clarify its behaviour:</p>\n\n<pre><code>((lambda (x y) (funcall x y)) (lambda (x) (* x x)) (* 3 3))\n</code></pre>\n\n<p>Or even more explicitly:</p>\n\n<pre><code>(funcall (lambda (x y) (funcall x y))\n (lambda (x) (* x x))\n (* 3 3))\n</code></pre>\n\n<p>Indeed, that first lambda doesn't do anything useful, since it boils down to:</p>\n\n<pre><code>(funcall (lambda (x) (* x x)) (* 3 3))\n</code></pre>\n\n<p>which equals</p>\n\n<pre><code>(let ((x (* 3 3)))\n (* x x))\n</code></pre>\n\n<p>equals</p>\n\n<pre><code>(let ((x 9))\n (* x x))\n</code></pre>\n\n<p>equals</p>\n\n<pre><code>(* 9 9)\n</code></pre>\n\n<p>equals 81.</p>\n"
},
{
"answer_id": 224319,
"author": "grettke",
"author_id": 121526,
"author_profile": "https://Stackoverflow.com/users/121526",
"pm_score": 1,
"selected": false,
"text": "<p>The answers posted so far are good, so rather than duplicating what they already said, perhaps here is another way you could look at the program:</p>\n\n<pre><code>(define (square x) (* x x))\n\n(define (call-with arg fun) (fun arg))\n\n(call-with (* 3 3) square)\n</code></pre>\n\n<p>Does it still look strange?</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18431/"
] |
Question:
```
((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3))
```
This was #1 on the midterm, I put "81 9" he thought I forgot to cross one out lawl, so I cross out 81, and he goes aww. Anyways, I dont understand why it's 81.
I understand why `(lambda (x) (* x x)) (* 3 3) = 81`, but the first lambda I dont understand what the x and y values are there, and what the `[body] (x y)` does.
So I was hoping someone could explain to me why the first part doesn't seem like it does anything.
|
This needs some indentation to clarify
```
((lambda (x y) (x y))
(lambda (x) (* x x))
(* 3 3))
```
* `(lambda (x y) (x y))`; call `x` with `y` as only parameter.
* `(lambda (x) (* x x))`; evaluate to the square of its parameter.
* `(* 3 3)`; evaluate to 9
So the whole thing means: "call the square function with the 9 as parameter".
EDIT: The same thing could be written as
```
((lambda (x) (* x x))
(* 3 3))
```
I guess the intent of the exercise is to highlight how evaluating a scheme form involves an implicit function application.
|
223,472 |
<p>Aspell-net is a port of the GNU Aspell for .Net Framework. The library itself is open source, and is under the LGPL license, but the english dictionary for aspell is mentioned as copyrighted on the sourceforge.net project home page at <a href="http://aspell-net.sourceforge.net/" rel="nofollow noreferrer">http://aspell-net.sourceforge.net/</a></p>
<p>Did any of you guys use aspell-net before? and what license did you release your software under? The project I work on is a commercial one, and do you guys forsee any problem? Should I pay for the aspell english dictionary?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 223484,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 4,
"selected": true,
"text": "<p>This needs some indentation to clarify</p>\n\n<pre><code>((lambda (x y) (x y))\n (lambda (x) (* x x))\n (* 3 3))\n</code></pre>\n\n<ul>\n<li><code>(lambda (x y) (x y))</code>; call <code>x</code> with <code>y</code> as only parameter.</li>\n<li><code>(lambda (x) (* x x))</code>; evaluate to the square of its parameter.</li>\n<li><code>(* 3 3)</code>; evaluate to 9</li>\n</ul>\n\n<p>So the whole thing means: \"call the square function with the 9 as parameter\".</p>\n\n<p>EDIT: The same thing could be written as</p>\n\n<pre><code>((lambda (x) (* x x))\n (* 3 3))\n</code></pre>\n\n<p>I guess the intent of the exercise is to highlight how evaluating a scheme form involves an implicit function application.</p>\n"
},
{
"answer_id": 223609,
"author": "Michał Kwiatkowski",
"author_id": 21998,
"author_profile": "https://Stackoverflow.com/users/21998",
"pm_score": 3,
"selected": false,
"text": "<p>Let's look at this again...</p>\n\n<pre><code>((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3))\n</code></pre>\n\n<p>To evaluate a form we evaluate each part of it in turn. We have three elements in our form. This one is on the first (function) position:</p>\n\n<pre><code>(lambda (x y) (x y))\n</code></pre>\n\n<p>This is a second element of a form and a first argument to the function:</p>\n\n<pre><code>(lambda (x) (* x x))\n</code></pre>\n\n<p>Last element of the form, so a second argument to the function.</p>\n\n<pre><code>(* 3 3)\n</code></pre>\n\n<p>Order of evaluation doesn't matter in this case, so let's just start from the left.</p>\n\n<pre><code>(lambda (x y) (x y))\n</code></pre>\n\n<p>Lambda creates a function, so this evaluates to a function that takes two arguments, x and y, and then applies x to y (in other words, calls x with a single argument y). Let's call this <strong>call-1</strong>.</p>\n\n<pre><code>(lambda (x) (* x x))\n</code></pre>\n\n<p>This evaluates to a function that takes a single argument and returns a square of this argument. So we can just call this <strong>square</strong>.</p>\n\n<pre><code>(* 3 3)\n</code></pre>\n\n<p>This obviously evaluates to <strong>9</strong>.</p>\n\n<p>OK, so after this first run of evaluation we have:</p>\n\n<pre><code>(call-1 square 9)\n</code></pre>\n\n<p>To evaluate this, we call <strong>call-1</strong> with two arguments, <strong>square</strong> and <strong>9</strong>. Applying <strong>call-1</strong> gives us:</p>\n\n<pre><code>(square 9)\n</code></pre>\n\n<p>Since that's what <strong>call-1</strong> does - it calls its first argument with its second argument. Now, square of <strong>9</strong> is <strong>81</strong>, which is the value of the whole expression.</p>\n"
},
{
"answer_id": 223917,
"author": "Luís Oliveira",
"author_id": 2967,
"author_profile": "https://Stackoverflow.com/users/2967",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps translating that code to Common Lisp helps clarify its behaviour:</p>\n\n<pre><code>((lambda (x y) (funcall x y)) (lambda (x) (* x x)) (* 3 3))\n</code></pre>\n\n<p>Or even more explicitly:</p>\n\n<pre><code>(funcall (lambda (x y) (funcall x y))\n (lambda (x) (* x x))\n (* 3 3))\n</code></pre>\n\n<p>Indeed, that first lambda doesn't do anything useful, since it boils down to:</p>\n\n<pre><code>(funcall (lambda (x) (* x x)) (* 3 3))\n</code></pre>\n\n<p>which equals</p>\n\n<pre><code>(let ((x (* 3 3)))\n (* x x))\n</code></pre>\n\n<p>equals</p>\n\n<pre><code>(let ((x 9))\n (* x x))\n</code></pre>\n\n<p>equals</p>\n\n<pre><code>(* 9 9)\n</code></pre>\n\n<p>equals 81.</p>\n"
},
{
"answer_id": 224319,
"author": "grettke",
"author_id": 121526,
"author_profile": "https://Stackoverflow.com/users/121526",
"pm_score": 1,
"selected": false,
"text": "<p>The answers posted so far are good, so rather than duplicating what they already said, perhaps here is another way you could look at the program:</p>\n\n<pre><code>(define (square x) (* x x))\n\n(define (call-with arg fun) (fun arg))\n\n(call-with (* 3 3) square)\n</code></pre>\n\n<p>Does it still look strange?</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Aspell-net is a port of the GNU Aspell for .Net Framework. The library itself is open source, and is under the LGPL license, but the english dictionary for aspell is mentioned as copyrighted on the sourceforge.net project home page at <http://aspell-net.sourceforge.net/>
Did any of you guys use aspell-net before? and what license did you release your software under? The project I work on is a commercial one, and do you guys forsee any problem? Should I pay for the aspell english dictionary?
Thanks.
|
This needs some indentation to clarify
```
((lambda (x y) (x y))
(lambda (x) (* x x))
(* 3 3))
```
* `(lambda (x y) (x y))`; call `x` with `y` as only parameter.
* `(lambda (x) (* x x))`; evaluate to the square of its parameter.
* `(* 3 3)`; evaluate to 9
So the whole thing means: "call the square function with the 9 as parameter".
EDIT: The same thing could be written as
```
((lambda (x) (* x x))
(* 3 3))
```
I guess the intent of the exercise is to highlight how evaluating a scheme form involves an implicit function application.
|
223,480 |
<p>Simple question that keeps bugging me.</p>
<p>Should I HTML encode user input right away and store the encoded contents in the database, or should I store the raw values and HTML encode when displaying?</p>
<p>Storing encoded data greatly reduces the risk of a developer forgetting to encode the data when it's being displayed. However, storing the encoded data will make datamining somewhat more cumbersome and it will take up a bit more space, even though that's usually a non-issue.</p>
|
[
{
"answer_id": 223494,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 6,
"selected": true,
"text": "<p>i'd strongly suggest encoding information on the way out. storing raw data in the database is useful if you wish to change the way it's viewed at a certain point. the flow should be something similar to:</p>\n\n<pre><code>sanitize user input -> protect against sql injection -> db -> encode for display\n</code></pre>\n\n<p>think about a situation where you might want to display the information as an RSS feed instead. having to redo any HTML specific encoding before you re-display seems a bit silly. any development should always follow the \"don't trust input\" meme, whether that input is from a user or from the database.</p>\n"
},
{
"answer_id": 223499,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 3,
"selected": false,
"text": "<p>Keep in mind that you may need to access the database with something that doesn't understand HTML encoded text (e.g., a reporting tool). I agree that space is a non-issue, but IMHO, putting HTML encoding in the database moves knowledge of your view/front end into the lowest tier in the application, and that is a design mistake.</p>\n"
},
{
"answer_id": 223509,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 3,
"selected": false,
"text": "<p>The encoding should only only only be done in the display. Without exception.</p>\n"
},
{
"answer_id": 223518,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Output.</strong> </p>\n\n<p>With HTML you can't simply check length of a string (<code>&amp;</code> is 1 character, but <code>strlen()</code> will tell you 5), you can easily crop it (it could break entities).</p>\n\n<p>You may need to mix strings from database with strings from another source, or read and write them back. Doing this application-wide without missing any escaping and avoiding double escaping is a nightmare.</p>\n\n<p>PHP tried to do similar thing with <code>magic_quotes</code> and it turned out to be a huge failure. Don't take <code>magic_entities</code> route! :)</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12469/"
] |
Simple question that keeps bugging me.
Should I HTML encode user input right away and store the encoded contents in the database, or should I store the raw values and HTML encode when displaying?
Storing encoded data greatly reduces the risk of a developer forgetting to encode the data when it's being displayed. However, storing the encoded data will make datamining somewhat more cumbersome and it will take up a bit more space, even though that's usually a non-issue.
|
i'd strongly suggest encoding information on the way out. storing raw data in the database is useful if you wish to change the way it's viewed at a certain point. the flow should be something similar to:
```
sanitize user input -> protect against sql injection -> db -> encode for display
```
think about a situation where you might want to display the information as an RSS feed instead. having to redo any HTML specific encoding before you re-display seems a bit silly. any development should always follow the "don't trust input" meme, whether that input is from a user or from the database.
|
223,490 |
<p>My company requires me to use Outlook for my E-mail. Outlook does virtually nothing the way I want to do it and it frustrates me greatly. (I'm not trying to start a flame war here, it must do exactly what thousands of CEO's want it to do, but I'm not a CEO.)</p>
<p>I would like to be able to automatically extract the thousands of E-mails and attachments currently in my Outlook account and save them in my own alternative storage format where I can easily search them and organize them the way I want. (I'm not requesting suggestions for the new format.)</p>
<p>Maybe some nice open source program already can do this... that would be great. Please let me know.</p>
<p>Otherwise, <b>how can I obtain the message content and the attachments without going through the huge collection manually?</b> Even if I could only get the message content and the names of the attachments, that would be sufficient. Is there documentation of the Outlook mail storage format? Is there a way to query Outlook for the data?</p>
<p>Maybe there is an alternative approach I haven't considered?</p>
<p>My preferred language to do this is C#, but I can use others if needed.</p>
|
[
{
"answer_id": 223542,
"author": "StubbornMule",
"author_id": 13341,
"author_profile": "https://Stackoverflow.com/users/13341",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://www.dimastr.com/redemption/\" rel=\"noreferrer\">Outlook Redemption</a> is the best thing currently to use that I have found. It will allow you to get into the messages and extract the attachments and the message bodies. i am using it now to do just that.</p>\n\n<p>Here is some code I use in a class. I included the constructor and the processing function I use to save off the attachments. I cut out the code that is specific to my needs but you can get an idea of what to use here.</p>\n\n<pre><code> private RDOSession _MailSession = new RDOSession();\n private RDOFolder _IncommingInbox;\n private RDOFolder _ArchiveFolder;\n private string _SaveAttachmentPath;\n\n public MailBox(string Logon_Profile, string IncommingMailPath, \n string ArchiveMailPath, string SaveAttPath)\n {\n _MailSession.Logon(Logon_Profile, null, null, true, null, null);\n _IncommingInbox = _MailSession.GetFolderFromPath(IncommingMailPath);\n _ArchiveFolder = _MailSession.GetFolderFromPath(ArchiveMailPath);\n _SaveAttachmentPath = SaveAttPath;\n }\npublic void ProcessMail()\n {\n\n foreach (RDOMail msg in _IncommingInbox.Items)\n {\n foreach (RDOAttachment attachment in msg.Attachments)\n {\n attachment.SaveAsFile(_SaveAttachmentPath + attachment.FileName);\n }\n }\n if (msg.Body != null)\n {\n ProcessBody(msg.Body);\n }\n\n }\n\n }\n</code></pre>\n\n<p><strong>edit:</strong>\nThis is how I call it and what is passed</p>\n\n<pre><code>MailBox pwaMail = new MailBox(\"Self Email User\", @\"\\\\Mailbox - Someone\\Inbox\",\n @\"\\\\EMail - Incomming\\Backup\", @\"\\\\SomePath\");\n</code></pre>\n"
},
{
"answer_id": 717609,
"author": "Rob",
"author_id": 18735,
"author_profile": "https://Stackoverflow.com/users/18735",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to extract your e-mails take a look at \nOutlook Email Extractor\nat codeproject\n<a href=\"http://69.10.233.10/KB/dotnet/OutlookEmailExtractor.aspx\" rel=\"nofollow noreferrer\">http://69.10.233.10/KB/dotnet/OutlookEmailExtractor.aspx</a></p>\n\n<p>rob\nwww.filefriendly.com</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722/"
] |
My company requires me to use Outlook for my E-mail. Outlook does virtually nothing the way I want to do it and it frustrates me greatly. (I'm not trying to start a flame war here, it must do exactly what thousands of CEO's want it to do, but I'm not a CEO.)
I would like to be able to automatically extract the thousands of E-mails and attachments currently in my Outlook account and save them in my own alternative storage format where I can easily search them and organize them the way I want. (I'm not requesting suggestions for the new format.)
Maybe some nice open source program already can do this... that would be great. Please let me know.
Otherwise, **how can I obtain the message content and the attachments without going through the huge collection manually?** Even if I could only get the message content and the names of the attachments, that would be sufficient. Is there documentation of the Outlook mail storage format? Is there a way to query Outlook for the data?
Maybe there is an alternative approach I haven't considered?
My preferred language to do this is C#, but I can use others if needed.
|
[Outlook Redemption](http://www.dimastr.com/redemption/) is the best thing currently to use that I have found. It will allow you to get into the messages and extract the attachments and the message bodies. i am using it now to do just that.
Here is some code I use in a class. I included the constructor and the processing function I use to save off the attachments. I cut out the code that is specific to my needs but you can get an idea of what to use here.
```
private RDOSession _MailSession = new RDOSession();
private RDOFolder _IncommingInbox;
private RDOFolder _ArchiveFolder;
private string _SaveAttachmentPath;
public MailBox(string Logon_Profile, string IncommingMailPath,
string ArchiveMailPath, string SaveAttPath)
{
_MailSession.Logon(Logon_Profile, null, null, true, null, null);
_IncommingInbox = _MailSession.GetFolderFromPath(IncommingMailPath);
_ArchiveFolder = _MailSession.GetFolderFromPath(ArchiveMailPath);
_SaveAttachmentPath = SaveAttPath;
}
public void ProcessMail()
{
foreach (RDOMail msg in _IncommingInbox.Items)
{
foreach (RDOAttachment attachment in msg.Attachments)
{
attachment.SaveAsFile(_SaveAttachmentPath + attachment.FileName);
}
}
if (msg.Body != null)
{
ProcessBody(msg.Body);
}
}
}
```
**edit:**
This is how I call it and what is passed
```
MailBox pwaMail = new MailBox("Self Email User", @"\\Mailbox - Someone\Inbox",
@"\\EMail - Incomming\Backup", @"\\SomePath");
```
|
223,495 |
<p>Is there a way to Invoke an overloaded method using reflection in .NET (2.0). I have an application that dynamically instantiates classes that have been derived from a common base class. For compatibility purposes, this base class contains 2 methods of the same name, one with parameters, and one without. I need to call the parameterless method via the Invoke method. Right now, all I get is an error telling me that I'm trying to call an ambiguous method.</p>
<p>Yes, I <em>could</em> just cast the object as an instance of my base class and call the method I need. Eventually that <em>will</em> happen, but right now, internal complications will not allow it.</p>
<p>Any help would be great! Thanks.</p>
|
[
{
"answer_id": 223505,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>Yes. When you invoke the method pass the parameters that match the overload that you want.</p>\n\n<p>For instance:</p>\n\n<pre><code>Type tp = myInstance.GetType();\n\n//call parameter-free overload\ntp.InvokeMember( \"methodName\", BindingFlags.InvokeMethod, \n Type.DefaultBinder, myInstance, new object[0] );\n\n//call parameter-ed overload\ntp.InvokeMember( \"methodName\", BindingFlags.InvokeMethod, \n Type.DefaultBinder, myInstance, new { param1, param2 } );\n</code></pre>\n\n<p>If you do this the other way round(i.e. by finding the MemberInfo and calling Invoke) be careful that you get the right one - the parameter-free overload could be the first found.</p>\n"
},
{
"answer_id": 223521,
"author": "baretta",
"author_id": 30052,
"author_profile": "https://Stackoverflow.com/users/30052",
"pm_score": 3,
"selected": false,
"text": "<p>Use the GetMethod overload that takes a System.Type[], and pass an empty Type[];</p>\n\n<pre><code>typeof ( Class ).GetMethod ( \"Method\", new Type [ 0 ] { } ).Invoke ( instance, null );\n</code></pre>\n"
},
{
"answer_id": 223525,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 8,
"selected": true,
"text": "<p>You have to specify which method you want: </p>\n\n<pre><code>class SomeType \n{\n void Foo(int size, string bar) { }\n void Foo() { }\n}\n\nSomeType obj = new SomeType();\n// call with int and string arguments\nobj.GetType()\n .GetMethod(\"Foo\", new Type[] { typeof(int), typeof(string) })\n .Invoke(obj, new object[] { 42, \"Hello\" });\n// call without arguments\nobj.GetType()\n .GetMethod(\"Foo\", new Type[0])\n .Invoke(obj, new object[0]);\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
Is there a way to Invoke an overloaded method using reflection in .NET (2.0). I have an application that dynamically instantiates classes that have been derived from a common base class. For compatibility purposes, this base class contains 2 methods of the same name, one with parameters, and one without. I need to call the parameterless method via the Invoke method. Right now, all I get is an error telling me that I'm trying to call an ambiguous method.
Yes, I *could* just cast the object as an instance of my base class and call the method I need. Eventually that *will* happen, but right now, internal complications will not allow it.
Any help would be great! Thanks.
|
You have to specify which method you want:
```
class SomeType
{
void Foo(int size, string bar) { }
void Foo() { }
}
SomeType obj = new SomeType();
// call with int and string arguments
obj.GetType()
.GetMethod("Foo", new Type[] { typeof(int), typeof(string) })
.Invoke(obj, new object[] { 42, "Hello" });
// call without arguments
obj.GetType()
.GetMethod("Foo", new Type[0])
.Invoke(obj, new object[0]);
```
|
223,526 |
<p>I'm writing a small application in VB.NET and I would like some of the classes to be able to write themselves out to XML to serve as a "save" feature. I have seen XSD files used to generate VB classes that can serialize themselves into and out of XML very easily. How would I do this if I do have any pre-existing XML format that I need to conform to as I'm just creating the classes myself?</p>
|
[
{
"answer_id": 223543,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Since you asked about making it 'easy', then there are three rules to follow that will help keeps things very simple:</p>\n\n<ol>\n<li>Only use property types that are serializable</li>\n<li>Don't use collections or arrays as properties that need to be serialized</li>\n<li>Don't have properties with \"bad\" side-effects. By 'bad', I mostly mean two public properties that are backed by the same underlying private field.</li>\n</ol>\n\n<p>Note that if you break these rules you can probably still serialize your class, but it's likely to be a lot more work.</p>\n\n<p>For item #2, a quick fix is using a datatable or dataset, since those are serializable.</p>\n"
},
{
"answer_id": 223563,
"author": "Adam Straughan",
"author_id": 14019,
"author_profile": "https://Stackoverflow.com/users/14019",
"pm_score": 0,
"selected": false,
"text": "<p>To go with a simple 'save' feature either use the .net xml serialization [1] or create yourself a n in memory DateSet to persist the 'state of the world' in as many DateTables as your see fit. It rather depends how complext your object model that you are trying to persist is.</p>\n\n<p>[1] simplest example I could find quickly (C#, sorry but you'll get the gist) <a href=\"http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm\" rel=\"nofollow noreferrer\">http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm</a></p>\n"
},
{
"answer_id": 223567,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 4,
"selected": true,
"text": "<p>Use the System.Xml and System.Xml.Serialization namespaces. They describe classes that you can use to annotate your classes' members with the corresponding tag.</p>\n\n<p>For example (in C#):</p>\n\n<pre><code>[XmlRoot(\"foo\")]\npublic class Foo\n{\n [XmlAttribute(\"bar\")] \n public string bar;\n [XmlAttribute(\"baz\")] \n public double baz;\n}\n</code></pre>\n\n<p>Or in VB.NET (might not be completely syntactically correct):</p>\n\n<pre><code><XmlRoot (\"foo\")> _\nPublic Class Foo\n <XmlAttribute (\"bar\")>_\n Public bar As String\n <XmlAttribute (\"baz\")>_\n Public baz As String\nEnd Class\n</code></pre>\n\n<p>You can then use the XmlSerializer class to output XML.</p>\n\n<p>In C#:</p>\n\n<pre><code>using(XmlSerializer xmls = new XmlSerializer(typeof(Foo)){\n TextWriter tw = new StreamWriter( \"foo.xml\" );\n //use it!\n}\n</code></pre>\n\n<p>Or VB:</p>\n\n<pre><code>Using xmls As New XmlSerializer(gettype(Foo)), _\n tw As TextWriter = New StreamWriter(\"foo.xml\")\n\n ''//use it!\nEnd Using\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.aspx\" rel=\"noreferrer\">Reference</a>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5904/"
] |
I'm writing a small application in VB.NET and I would like some of the classes to be able to write themselves out to XML to serve as a "save" feature. I have seen XSD files used to generate VB classes that can serialize themselves into and out of XML very easily. How would I do this if I do have any pre-existing XML format that I need to conform to as I'm just creating the classes myself?
|
Use the System.Xml and System.Xml.Serialization namespaces. They describe classes that you can use to annotate your classes' members with the corresponding tag.
For example (in C#):
```
[XmlRoot("foo")]
public class Foo
{
[XmlAttribute("bar")]
public string bar;
[XmlAttribute("baz")]
public double baz;
}
```
Or in VB.NET (might not be completely syntactically correct):
```
<XmlRoot ("foo")> _
Public Class Foo
<XmlAttribute ("bar")>_
Public bar As String
<XmlAttribute ("baz")>_
Public baz As String
End Class
```
You can then use the XmlSerializer class to output XML.
In C#:
```
using(XmlSerializer xmls = new XmlSerializer(typeof(Foo)){
TextWriter tw = new StreamWriter( "foo.xml" );
//use it!
}
```
Or VB:
```
Using xmls As New XmlSerializer(gettype(Foo)), _
tw As TextWriter = New StreamWriter("foo.xml")
''//use it!
End Using
```
[Reference](http://msdn.microsoft.com/en-us/library/system.xml.serialization.aspx).
|
223,533 |
<p>I am looking for a solution or recommendation to a problem I am having. I have a bunch of ASPX pages that will be localized and have a bunch of text that needs to be supported in 6 languages.</p>
<p>The people doing the translation will not have access to Visual Studio and the likely easiest tool is Excel. If we use Excel or even export to CSV, we need to be able to import to move to .resx files. So, what is the best method for this?</p>
<p>I am aware of this question, <a href="https://stackoverflow.com/questions/198772/convert-a-visual-studio-resource-file-to-a-text-file">Convert a Visual Studio resource file to a text file?</a> already and the use of Resx Editor but an easier solution would be preferred.</p>
|
[
{
"answer_id": 224214,
"author": "Jared",
"author_id": 7388,
"author_profile": "https://Stackoverflow.com/users/7388",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure how comprehensive an answer you're looking for, but if you're really just using [string, string] pairs for your localization, and you're just looking for a quick way to load resource (.resx) files with the results of your translations, then the following will work as a fairly quick, low-tech solution.</p>\n\n<p>The thing to remember is that .resx files are just XML documents, so it should be possible to manually load your data into the resource from an external piece of code. The following example worked for me in VS2005 and VS2008:</p>\n\n<pre><code>namespace SampleResourceImport\n{\n class Program\n {\n static void Main(string[] args)\n {\n\n XmlDocument doc = new XmlDocument();\n string filePath = @\"[file path to your resx file]\";\n doc.Load(filePath);\n XmlElement root = doc.DocumentElement;\n\n XmlElement datum = null;\n XmlElement value = null;\n XmlAttribute datumName = null;\n XmlAttribute datumSpace = doc.CreateAttribute(\"xml:space\");\n datumSpace.Value = \"preserve\";\n\n // The following mocks the actual retrieval of your localized text\n // from a CSV or ?? document...\n // CSV parsers are common enough that it shouldn't be too difficult\n // to find one if that's the direction you go.\n Dictionary<string, string> d = new Dictionary<string, string>();\n d.Add(\"Label1\", \"First Name\");\n d.Add(\"Label2\", \"Last Name\");\n d.Add(\"Label3\", \"Date of Birth\");\n\n foreach (KeyValuePair<string, string> pair in d)\n {\n datum = doc.CreateElement(\"data\");\n datumName = doc.CreateAttribute(\"name\");\n datumName.Value = pair.Key;\n value = doc.CreateElement(\"value\");\n value.InnerText = pair.Value;\n\n datum.Attributes.Append(datumName);\n datum.Attributes.Append(datumSpace);\n datum.AppendChild(value);\n root.AppendChild(datum);\n }\n\n doc.Save(filePath);\n }\n }\n}\n</code></pre>\n\n<p>Obviously, the preceding method won't generate the code-behind for your resource, however opening the resource file in Visual Studio and toggling the accessibility modifier for the resource will (re)generate the static properties for you.</p>\n\n<p>If you're looking for a completely XML-based solution (vs. CSV or Excel interop), you could also instruct your translators to store their translated content in Excel, saved as XML, then use XPath to retrieve your localization info. The only caveat being the file sizes tend to become pretty bloated.</p>\n\n<p>Best of luck.</p>\n"
},
{
"answer_id": 13387693,
"author": "CSC",
"author_id": 393097,
"author_profile": "https://Stackoverflow.com/users/393097",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into similar problem and realized that the simplest way to create a .resx file from excel file is using a concatenate function of excel to generate \"<\"data\">\"..\"<\"/data\">\" node for the .resx file and then manually copying the generated rows to the .resx file in any text editor. So lets say that you have \"Name\" in column A of an excel document and \"value\" in Column B of the excel document. Using following formula in Column C</p>\n\n<pre><code>=CONCATENATE(\"<data name=\",\"\"\"\",A14,\"\"\" xml:space=\"\"preserve\"\">\",\"<value>\", B14, \"</value>\", \"</data>\")\n</code></pre>\n\n<p>you will get the data node for resource. You can then copy this formula to all the rows and then copy the contents of Column C in your .resx file. </p>\n"
},
{
"answer_id": 19037147,
"author": "Andy Gaskell",
"author_id": 30697,
"author_profile": "https://Stackoverflow.com/users/30697",
"pm_score": 0,
"selected": false,
"text": "<p>If it's in csv here's a quick Ruby script to generate the data elements.</p>\n\n<pre><code>require 'csv'\nrequire 'builder'\n\nfile = ARGV[0]\n\nbuilder = Builder::XmlMarkup.new(:indent => 2)\n\nCSV.foreach(file) do |row|\n builder.data(:name => row[0], \"xml:space\" => :preserve) {|d| d.value(row[1]) }\nend\n\nFile.open(file + \".xml\", 'w') { |f| f.write(builder.target!) }\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2305/"
] |
I am looking for a solution or recommendation to a problem I am having. I have a bunch of ASPX pages that will be localized and have a bunch of text that needs to be supported in 6 languages.
The people doing the translation will not have access to Visual Studio and the likely easiest tool is Excel. If we use Excel or even export to CSV, we need to be able to import to move to .resx files. So, what is the best method for this?
I am aware of this question, [Convert a Visual Studio resource file to a text file?](https://stackoverflow.com/questions/198772/convert-a-visual-studio-resource-file-to-a-text-file) already and the use of Resx Editor but an easier solution would be preferred.
|
I'm not sure how comprehensive an answer you're looking for, but if you're really just using [string, string] pairs for your localization, and you're just looking for a quick way to load resource (.resx) files with the results of your translations, then the following will work as a fairly quick, low-tech solution.
The thing to remember is that .resx files are just XML documents, so it should be possible to manually load your data into the resource from an external piece of code. The following example worked for me in VS2005 and VS2008:
```
namespace SampleResourceImport
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
string filePath = @"[file path to your resx file]";
doc.Load(filePath);
XmlElement root = doc.DocumentElement;
XmlElement datum = null;
XmlElement value = null;
XmlAttribute datumName = null;
XmlAttribute datumSpace = doc.CreateAttribute("xml:space");
datumSpace.Value = "preserve";
// The following mocks the actual retrieval of your localized text
// from a CSV or ?? document...
// CSV parsers are common enough that it shouldn't be too difficult
// to find one if that's the direction you go.
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Label1", "First Name");
d.Add("Label2", "Last Name");
d.Add("Label3", "Date of Birth");
foreach (KeyValuePair<string, string> pair in d)
{
datum = doc.CreateElement("data");
datumName = doc.CreateAttribute("name");
datumName.Value = pair.Key;
value = doc.CreateElement("value");
value.InnerText = pair.Value;
datum.Attributes.Append(datumName);
datum.Attributes.Append(datumSpace);
datum.AppendChild(value);
root.AppendChild(datum);
}
doc.Save(filePath);
}
}
}
```
Obviously, the preceding method won't generate the code-behind for your resource, however opening the resource file in Visual Studio and toggling the accessibility modifier for the resource will (re)generate the static properties for you.
If you're looking for a completely XML-based solution (vs. CSV or Excel interop), you could also instruct your translators to store their translated content in Excel, saved as XML, then use XPath to retrieve your localization info. The only caveat being the file sizes tend to become pretty bloated.
Best of luck.
|
223,535 |
<p>Is there a way to manually increase / decrease the timeout of a specific aspx page?</p>
|
[
{
"answer_id": 223551,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 4,
"selected": true,
"text": "<p>In the web.config:</p>\n\n<pre><code> <configuration>\n <location path=\"~/Default.aspx\">\n <system.web>\n <httpRuntime executionTimeout=\"1000\"/> \n </system.web> \n </location>\n </configuration>\n</code></pre>\n"
},
{
"answer_id": 223554,
"author": "schmoopy",
"author_id": 26685,
"author_profile": "https://Stackoverflow.com/users/26685",
"pm_score": 0,
"selected": false,
"text": "<p>If you are talking about the amount of time it takes before the page returns a timeout, then mnour's example - you may want to look at the machine.config file as well. If you talking about a session timing out, then you will need to use a JS timer that posts back when it reaches 0.</p>\n"
},
{
"answer_id": 223578,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p>The one thing to remember with this is that the timeout feature here will only invalidate the Session Timeout, but the user will still remain on whatever page they are on. This may cause issues with the flow of the application. As a rememdy, I keep the following in my Web.config file:</p>\n\n<pre><code><appSettings>\n <!-- Application Timeout is 10 minutes -->\n <add key=\"SessionTimeoutMilliseconds\" value=\"600000\"/> \n</appSettings>\n</code></pre>\n\n<p>In addition, my master page has the following code in my code behind file:</p>\n\n<pre><code>' Register Javascript timeout event to redirect to the login page after inactivity\nPage.ClientScript.RegisterStartupScript(Me.GetType, \"TimeoutScript\", _\n \"setTimeout(\"\"top.location.href = '/EAF/Login.aspx'\"\",\" & _\n ConfigurationManager.AppSettings(\"SessionTimeoutMilliseconds\") & \");\", True)\n</code></pre>\n\n<p>and you should be all set on both ends.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
Is there a way to manually increase / decrease the timeout of a specific aspx page?
|
In the web.config:
```
<configuration>
<location path="~/Default.aspx">
<system.web>
<httpRuntime executionTimeout="1000"/>
</system.web>
</location>
</configuration>
```
|
223,548 |
<p>I have been reading the <a href="http://msdn.microsoft.com/en-us/library/ms997565.aspx" rel="nofollow noreferrer">MSDN</a> documentation on subclassing and I have been successful in handling events in a subclass</p>
<p>My issue is with passing messages back to the original WndProc.</p>
<p>As an example, if I have a window, with a sub-classed groupbox control and a button as a child of that groupbox, I want to handle the button event in the original window procedure, not the subclassed groupbox procedure.</p>
<p>Essentially, I want an empty subclass procedure:</p>
<pre><code>LRESULT FAR PASCAL SubClassFunc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
return CallWindowProc(oldProc, hwnd, uMsg, wParam, lParam);
}
</code></pre>
<p>Where oldProc is:</p>
<pre><code>FARPROC oldProc = (FARPROC)SetClassLong(group_box, GCL_WDPROC, (DWORD)SubCLassFunc);
</code></pre>
<p>And where the window and groupbox and button are:</p>
<pre><code>HWND window = CreateWindowEx(
WS_EX_WINDOWEDGE,
appname,
TEXT("Subclass Test"),
WS_VISIBLE |WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
300,
400,
NULL,
NULL,
hInstance,
0);
HWND group_box = CreateWindowEx(
0,
TEXT("BUTTON"),
TEXT("Group Box"),
WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
8,
8,
275,
350,
window,
NULL,
hInstance,
0);
HWND push_button = CreateWindowEx(
0,
TEXT("BUTTON"),
TEXT("Push Button"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_VCENTER,
50,
100,
100,
25,
group_box,
(HMENU)PUSH_BUTTON,
hInstance,
0);
</code></pre>
<p>I can handle the button events in the SubClassFunc, but what I want to do is pass them back to the window WndProc. It seems that CallWindowProc isn't doing this, or I may be totally wrong in how CallWindowProc works.</p>
|
[
{
"answer_id": 223858,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 3,
"selected": true,
"text": "<p>The button notifications are sent to the button's parent, which is the group box. Because you've subclassed the group box, your <code>SubClassFunc</code> receives these messages, which then passes them to the group box's original window procedure using <code>CallWindowProc</code>.</p>\n\n<p>If you want the button notifications to go to the parent window (i.e, <code>window</code> in your code), you could either set the button's parent to <code>window</code> instead of <code>group_box</code>, or use <code>PostMessage</code> from within <code>SubClassFunc</code> to post the message (<code>WM_COMMAND</code> or <code>WM_NOTIFY</code> as appropriate) to <code>window</code>.</p>\n\n<p>Also, I see that you're using <code>SetClassLong</code> to set the window procedure. What this does is replace the window procedure for the entire <code>BUTTON</code> class, but only for windows that are subsequently created. Any <code>BUTTON</code> windows created before calling <code>SetClassLong</code> will not be subclassed. You may want to consider using <code>SetWindowLong</code> instead, to subclass individual windows rather than the entire class. </p>\n\n<p>Edit: The group box's original window procedure doesn't send <code>WM_COMMAND</code> messages to its parent. This is explained in Charles Petzold's <a href=\"http://www.charlespetzold.com/pw5/\" rel=\"nofollow noreferrer\">Programming Windows</a> book:</p>\n\n<blockquote>\n <p>The group box, which has the <code>BS_GROUPBOX</code> style, is an oddity in the button class. It neither processes mouse or keyboard input, nor sends <code>WM_COMMAND</code> messages to its parent.</p>\n</blockquote>\n\n<p>You should find that button notifications don't get through to <code>window</code> even if you don't subclass the group box.</p>\n\n<p>I hope this helps!</p>\n"
},
{
"answer_id": 223910,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect if you remove the subclass all together the button events will still not reach the original window procedure as you expect.</p>\n\n<p>Since you have an subclass procedure doing nothing more than calling <strong>CallWindowProc</strong> the window is effectively not subclasses.</p>\n\n<p>My suggestion would be to use the <strong>Spy++</strong> tool to see which window is getting the button event messages.</p>\n\n<p>One of the more difficult aspects of Win32 programming is determining which window gets which message and <strong>Spy++</strong> is invaluable when it comes to figuring out this information.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067/"
] |
I have been reading the [MSDN](http://msdn.microsoft.com/en-us/library/ms997565.aspx) documentation on subclassing and I have been successful in handling events in a subclass
My issue is with passing messages back to the original WndProc.
As an example, if I have a window, with a sub-classed groupbox control and a button as a child of that groupbox, I want to handle the button event in the original window procedure, not the subclassed groupbox procedure.
Essentially, I want an empty subclass procedure:
```
LRESULT FAR PASCAL SubClassFunc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
return CallWindowProc(oldProc, hwnd, uMsg, wParam, lParam);
}
```
Where oldProc is:
```
FARPROC oldProc = (FARPROC)SetClassLong(group_box, GCL_WDPROC, (DWORD)SubCLassFunc);
```
And where the window and groupbox and button are:
```
HWND window = CreateWindowEx(
WS_EX_WINDOWEDGE,
appname,
TEXT("Subclass Test"),
WS_VISIBLE |WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
300,
400,
NULL,
NULL,
hInstance,
0);
HWND group_box = CreateWindowEx(
0,
TEXT("BUTTON"),
TEXT("Group Box"),
WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
8,
8,
275,
350,
window,
NULL,
hInstance,
0);
HWND push_button = CreateWindowEx(
0,
TEXT("BUTTON"),
TEXT("Push Button"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_VCENTER,
50,
100,
100,
25,
group_box,
(HMENU)PUSH_BUTTON,
hInstance,
0);
```
I can handle the button events in the SubClassFunc, but what I want to do is pass them back to the window WndProc. It seems that CallWindowProc isn't doing this, or I may be totally wrong in how CallWindowProc works.
|
The button notifications are sent to the button's parent, which is the group box. Because you've subclassed the group box, your `SubClassFunc` receives these messages, which then passes them to the group box's original window procedure using `CallWindowProc`.
If you want the button notifications to go to the parent window (i.e, `window` in your code), you could either set the button's parent to `window` instead of `group_box`, or use `PostMessage` from within `SubClassFunc` to post the message (`WM_COMMAND` or `WM_NOTIFY` as appropriate) to `window`.
Also, I see that you're using `SetClassLong` to set the window procedure. What this does is replace the window procedure for the entire `BUTTON` class, but only for windows that are subsequently created. Any `BUTTON` windows created before calling `SetClassLong` will not be subclassed. You may want to consider using `SetWindowLong` instead, to subclass individual windows rather than the entire class.
Edit: The group box's original window procedure doesn't send `WM_COMMAND` messages to its parent. This is explained in Charles Petzold's [Programming Windows](http://www.charlespetzold.com/pw5/) book:
>
> The group box, which has the `BS_GROUPBOX` style, is an oddity in the button class. It neither processes mouse or keyboard input, nor sends `WM_COMMAND` messages to its parent.
>
>
>
You should find that button notifications don't get through to `window` even if you don't subclass the group box.
I hope this helps!
|
223,549 |
<p>We have a product but we are doing some rebranding so we need to be able to build and maintain two versions. I used resource files combined with some #if stuff to solve the strings, images, and whatever else, but the program icon is giving me trouble. I couldn't figure it out from msdn or a google search. Thanks!</p>
|
[
{
"answer_id": 223590,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>Set the icon in normal code, and you should be able to use the same techniques as you have elsewhere. You'll need both icons in the resources file (at least so I suspect) but it should work.</p>\n\n<p>Alternatively, set a prebuild step to copy the appropriate icon into a common filename - e.g. copying debug.ico or release.ico into app.ico. A bit hacky, but I think it would work. That way you only end up with one icon in the finished binaries.</p>\n\n<p>Yet another option: look into the build file and see how the icon is built in, then conditionalise it. Marc Gravell did this for references in <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"nofollow noreferrer\">MiscUtil</a> - the project can be built targeting either .NET 2.0 or 3.5, depending on configuration. I suspect that resources could be conditionalised in a very similar way.</p>\n"
},
{
"answer_id": 223597,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 2,
"selected": false,
"text": "<p>Create icon files named after your config. (E.g. DebugOld.app.ico DebugBranded.app.ico, ReleaseBranded.app.ico)</p>\n\n<p>Create a pre-build step:</p>\n\n<pre><code>copy \"$(ProjectDir)$(ConfigurationName).app.ico\" \"$(ProjectDir)app.ico\"\n</code></pre>\n"
},
{
"answer_id": 223599,
"author": "Daniel Plaisted",
"author_id": 1509,
"author_profile": "https://Stackoverflow.com/users/1509",
"pm_score": 2,
"selected": false,
"text": "<p>Are you referring to the application icon? You can edit your project file manually and put in code similar to the following:</p>\n\n<pre><code><PropertyGroup>\n <ApplicationIcon Condition=\" '$(Configuration)' == 'Version1' \">Icon1.ico</ApplicationIcon>\n <ApplicationIcon Condition=\" '$(Configuration)' == 'Version2' \">Icon2.ico</ApplicationIcon>\n</PropertyGroup>\n<ItemGroup Condition=\" '$(Configuration)' == 'Version1' \">\n <Content Include=\"Icon1.ico\" />\n</ItemGroup>\n<ItemGroup Condition=\" '$(Configuration)' == 'Version2' \">\n <Content Include=\"Icon2.ico\" />\n</ItemGroup>\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
We have a product but we are doing some rebranding so we need to be able to build and maintain two versions. I used resource files combined with some #if stuff to solve the strings, images, and whatever else, but the program icon is giving me trouble. I couldn't figure it out from msdn or a google search. Thanks!
|
Create icon files named after your config. (E.g. DebugOld.app.ico DebugBranded.app.ico, ReleaseBranded.app.ico)
Create a pre-build step:
```
copy "$(ProjectDir)$(ConfigurationName).app.ico" "$(ProjectDir)app.ico"
```
|
223,556 |
<p>Say I need some very special multiplication operator. It may be implemented in following macro:</p>
<pre><code>macro @<<!(op1, op2)
{
<[ ( $op1 * $op2 ) ]>
}
</code></pre>
<p>And I can use it like</p>
<pre><code>def val = 2 <<! 3
</code></pre>
<p>And its work.</p>
<p>But what I really want is some 'english'-like operator for the DSL Im developing now:</p>
<pre><code>macro @multiply(op1, op2)
{
<[ ( $op1 * $op2 ) ]>
}
</code></pre>
<p>and if I try to use it like</p>
<pre><code>def val = 2 multiply 3
</code></pre>
<p>compiler fails with 'expected ;' error</p>
<p>What is the problem? How can I implement this infix-format macro?</p>
|
[
{
"answer_id": 223626,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 4,
"selected": true,
"text": "<p>Straight from the compiler source code:</p>\n\n<pre><code>namespace Nemerle.English\n{\n [assembly: Nemerle.Internal.OperatorAttribute (\"Nemerle.English\", \"and\", false, 160, 161)]\n [assembly: Nemerle.Internal.OperatorAttribute (\"Nemerle.English\", \"or\", false, 150, 151)]\n [assembly: Nemerle.Internal.OperatorAttribute (\"Nemerle.English\", \"not\", true, 181, 180)] \n\n macro @and (e1, e2) {\n <[ $e1 && $e2 ]>\n }\n\n macro @or (e1, e2) {\n <[ $e1 || $e2 ]>\n }\n\n macro @not (e) {\n <[ ! $e ]>\n }\n</code></pre>\n\n<p>You need to sprinkle OperatorAttributes around and it will work. Btw, OperatorAttribute is defined as follows:</p>\n\n<pre><code>public class OperatorAttribute : NemerleAttribute\n{\n public mutable env : string;\n public mutable name : string;\n public mutable IsUnary : bool;\n public mutable left : int;\n public mutable right : int;\n}\n</code></pre>\n"
},
{
"answer_id": 223630,
"author": "noetic",
"author_id": 9198,
"author_profile": "https://Stackoverflow.com/users/9198",
"pm_score": 1,
"selected": false,
"text": "<p>As usually, I found answer sooner than comunity respond :)\nSo, solution is to simply use special assemply level attribute which specifies the macro as binary operator:</p>\n\n<pre><code>namespace TestMacroLib\n{\n [assembly: Nemerle.Internal.OperatorAttribute (\"TestMacroLib\", \"multiply\", false, 160, 161)]\n public macro multiply(op1, op2)\n {\n <[ ( $op1 * $op2 ) ]>\n }\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9198/"
] |
Say I need some very special multiplication operator. It may be implemented in following macro:
```
macro @<<!(op1, op2)
{
<[ ( $op1 * $op2 ) ]>
}
```
And I can use it like
```
def val = 2 <<! 3
```
And its work.
But what I really want is some 'english'-like operator for the DSL Im developing now:
```
macro @multiply(op1, op2)
{
<[ ( $op1 * $op2 ) ]>
}
```
and if I try to use it like
```
def val = 2 multiply 3
```
compiler fails with 'expected ;' error
What is the problem? How can I implement this infix-format macro?
|
Straight from the compiler source code:
```
namespace Nemerle.English
{
[assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "and", false, 160, 161)]
[assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "or", false, 150, 151)]
[assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "not", true, 181, 180)]
macro @and (e1, e2) {
<[ $e1 && $e2 ]>
}
macro @or (e1, e2) {
<[ $e1 || $e2 ]>
}
macro @not (e) {
<[ ! $e ]>
}
```
You need to sprinkle OperatorAttributes around and it will work. Btw, OperatorAttribute is defined as follows:
```
public class OperatorAttribute : NemerleAttribute
{
public mutable env : string;
public mutable name : string;
public mutable IsUnary : bool;
public mutable left : int;
public mutable right : int;
}
```
|
223,559 |
<p>I want to know how to use variables for objects and function names in Python. In PHP, you can do this:</p>
<pre><code>$className = "MyClass";
$newObject = new $className();
</code></pre>
<p>How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?</p>
|
[
{
"answer_id": 223566,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "<p>In Python,</p>\n\n<pre><code>className = MyClass\nnewObject = className()\n</code></pre>\n\n<p>The first line makes the variable <code>className</code> refer to the same thing as <code>MyClass</code>. Then the next line calls the <code>MyClass</code> constructor through the <code>className</code> variable.</p>\n\n<p>As a concrete example:</p>\n\n<pre><code>>>> className = list\n>>> newObject = className()\n>>> newObject\n[]\n</code></pre>\n\n<p>(In Python, <code>list</code> is the constructor for the <code>list</code> class.)</p>\n\n<p>The difference is that in PHP, you represent the name of the class you want to refer to as a string, while in Python you can reference the same class directly. If you <em>must</em> use a string (for example if the name of the class is created dynamically), then you will need to use other techniques.</p>\n"
},
{
"answer_id": 223584,
"author": "TimB",
"author_id": 4193,
"author_profile": "https://Stackoverflow.com/users/4193",
"pm_score": 3,
"selected": false,
"text": "<p>If you have this:</p>\n\n<pre><code>class MyClass:\n def __init__(self):\n print \"MyClass\"\n</code></pre>\n\n<p>Then you usually do this:</p>\n\n<pre><code>>>> x = MyClass()\nMyClass\n</code></pre>\n\n<p>But you could also do this, which is what I think you're asking:</p>\n\n<pre><code>>>> a = \"MyClass\"\n>>> y = eval(a)()\nMyClass\n</code></pre>\n\n<p>But, be very careful about where you get the string that you use \"eval()\" on -- if it's come from the user, you're essentially creating an enormous security hole.</p>\n\n<p>Update: Using <code>type()</code> as shown in coleifer's answer is far superior to this solution.</p>\n"
},
{
"answer_id": 223586,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 6,
"selected": false,
"text": "<p>Assuming that some_module has a class named \"class_name\":</p>\n\n<pre><code>import some_module\nklass = getattr(some_module, \"class_name\")\nsome_object = klass()\n</code></pre>\n\n<p>I should note that you should be careful here: turning strings into code can be dangerous if the string came from the user, so you should keep security in mind in this situation. :)</p>\n\n<p>One other method (assuming that we still are using \"class_name\"):</p>\n\n<pre><code>class_lookup = { 'class_name' : class_name }\nsome_object = class_lookup['class_name']() #call the object once we've pulled it out of the dict\n</code></pre>\n\n<p>The latter method is probably the most secure way of doing this, so it's probably what you should use if at all possible.</p>\n"
},
{
"answer_id": 2875113,
"author": "coleifer",
"author_id": 254346,
"author_profile": "https://Stackoverflow.com/users/254346",
"pm_score": 5,
"selected": false,
"text": "<p>If you need to create a dynamic class in Python (i.e. one whose name is a variable) you can use type() which takes 3 params:\nname, bases, attrs</p>\n\n<pre><code>>>> class_name = 'MyClass'\n>>> klass = type(class_name, (object,), {'msg': 'foobarbaz'})\n\n<class '__main__.MyClass'>\n\n>>> inst = klass()\n>>> inst.msg\nfoobarbaz\n</code></pre>\n\n<ul>\n<li>Note however, that this does not 'instantiate' the object (i.e. does not call constructors etc. It creates a new(!) class with the same name.</li>\n</ul>\n"
},
{
"answer_id": 59900521,
"author": "Yanone",
"author_id": 1209986,
"author_profile": "https://Stackoverflow.com/users/1209986",
"pm_score": 1,
"selected": false,
"text": "<p>I use:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>newObject = globals()[className]()\n</code></pre>\n"
},
{
"answer_id": 71837153,
"author": "Akash Ranjan",
"author_id": 3606723,
"author_profile": "https://Stackoverflow.com/users/3606723",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer using dictionary to store the class to string mapping.</p>\n<pre><code>>>> class AB:\n... def __init__(self, tt):\n... print(tt, "from class AB")\n... \n>>> class BC:\n... def __init__(self, tt):\n... print(tt, "from class BC")\n... \n>>> x = { "ab": AB, "bc": BC}\n>>> x\n{'ab': <class '__main__.AB'>, 'bc': <class '__main__.BC'>}\n>>> \n>>> x['ab']('hello')\nhello from class AB\n<__main__.AB object at 0x10dd14b20>\n>>> x['bc']('hello')\nhello from class BC\n<__main__.BC object at 0x10eb33dc0>\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] |
I want to know how to use variables for objects and function names in Python. In PHP, you can do this:
```
$className = "MyClass";
$newObject = new $className();
```
How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?
|
In Python,
```
className = MyClass
newObject = className()
```
The first line makes the variable `className` refer to the same thing as `MyClass`. Then the next line calls the `MyClass` constructor through the `className` variable.
As a concrete example:
```
>>> className = list
>>> newObject = className()
>>> newObject
[]
```
(In Python, `list` is the constructor for the `list` class.)
The difference is that in PHP, you represent the name of the class you want to refer to as a string, while in Python you can reference the same class directly. If you *must* use a string (for example if the name of the class is created dynamically), then you will need to use other techniques.
|
223,618 |
<p>First of all (in case this is important) I'm using ActiveState's Perl (v5.8.7 built for MSWin32-x86-multi-thread).</p>
<p>I've just emerged from a three hour long debugging session, trying to find the source of an error. I found there was simply no error, but for some reason ADO's connection object was getting the <code>Errors.Count</code> increased with each printed message in my stored procedure's output.</p>
<p>Consider following Transact SQL code:</p>
<pre><code>CREATE PROCEDURE dbo.My_Sample() AS
BEGIN TRAN my_tran
-- Does something useful
if @@error <> 0 BEGIN
ROLLBACK TRAN my_tran
RAISERROR( 'SP My_Sample failed', 16, 1)
END ELSE BEGIN
COMMIT TRAN my_tran
PRINT 'SP My_Sample succeeded'
END
</code></pre>
<p>Now imagine a Perl sub more or less like:</p>
<pre><code>sub execute_SQL {
# $conn is an already opened ADO connection object
# pointing to my SQL Server
# $sql is the T-SQL statement to be executed
my($conn, $sql) = @_;
$conn->Execute($sql);
my $error_collection = $conn->Errors();
my $ecount = $error_collection->Count;
if ($ecount == 0 ) { return 0; }
print "\n" . $ecount . " errors found\n";
print "Executed SQL Code:\n$sql\n\n";
print "Errors while executing:\n";
foreach my $error (in $error_collection){
print "Error: [" . $error->{Number} . "] " . $error->{Description} . "\n";
}
return 1;
}
</code></pre>
<p>Somewhere else, in the main Perl code, I'm calling the above sub as:</p>
<pre><code>execute_SQL( $conn, 'EXEC dbo.My_Sample' );
</code></pre>
<p>In the end I got it that <em>every</em> PRINT statement causes a new pseudo-error to be appended to the ADO Errors collection. The quick fix I implemented was to change that PRINT in the SP into a SELECT, to bypass this.</p>
<p>The questions I'd like to ask are:</p>
<ul>
<li>Is this behaviour normal?</li>
<li>Is there a way to avoid/bypass it?</li>
</ul>
|
[
{
"answer_id": 223690,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 3,
"selected": true,
"text": "<p>This is to be expected as it's what ADO does and the Win32::ADO is quite a thin layer above it.</p>\n\n<p>ref: knowledge base <a href=\"http://support.microsoft.com/kb/194792\" rel=\"nofollow noreferrer\">note that the RAISERROR and PRINT statements are returned through the ADO errors collection</a></p>\n"
},
{
"answer_id": 227041,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 1,
"selected": false,
"text": "<p>OK, after a <strong>lot</strong> of testing and reading, I came to found it explained in the BOLs' article \"Using PRINT\" (my emphasis):</p>\n\n<blockquote>\n <p>The PRINT statement is used to return messages to applications. PRINT takes either a character or Unicode string expression as a parameter and returns the string as a message to the application. The message is returned as an informational error to applications using the SQLClient namespace or the ActiveX Data Objects (ADO), OLE DB, and Open Database Connectivity (ODBC) application programming interfaces (APIs). <strong>SQLSTATE is set to 01000, the native error is set to 0, and the error message string is set to the character string specified in the PRINT statement.</strong> The string is returned to the message handler callback function in DB-Library applications.</p>\n</blockquote>\n\n<p>Armed with this knowledge I adapted this VB6 from <a href=\"http://www.devx.com/tips/Tip/13483\" rel=\"nofollow noreferrer\">this DevX article</a> until I got this:</p>\n\n<pre><code>sub execute_SQL {\n # $conn is an already opened ADO connection object\n # pointing to my SQL Server\n # $sql is the T-SQL statement to be executed\n # Returns 0 if no error found, 1 otherwise\n my($conn, $sql) = @_;\n $conn->Execute($sql);\n my $error_collection = $conn->Errors();\n my $ecount = $error_collection->Count;\n if ($ecount == 0 ) { return 0; }\n\n my ($is_message, $real_error_found);\n foreach my $error (in $error_collection){\n $is_message = ($error->{SQLState} eq \"01000\" && $error->{NativeError}==0);\n $real_error_found=1 unless $is_message;\n\n if( $is_message) {\n print \"Message # \" . $error->{Number}\n . \"\\n Text: \" . $error->{Description} .\"\\n\";\n } else {\n print \"Error # \" . $error->{Number}\n . \"\\n Description: \" . $error->{Description}\n . \"\\nSource: \" . $error->{Source} . \"\\n\";\n }\n }\n\n print $message_to_print;\n return $real_error_found;\n}\n</code></pre>\n\n<p>So now my Perl sub correctly sorts out real errors (emitted from SQL Server via a RaisError) and a common message outputted via \"PRINT\".</p>\n\n<p>Thanks to Richard Harrison for his answer which lead me to the way of success.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21258/"
] |
First of all (in case this is important) I'm using ActiveState's Perl (v5.8.7 built for MSWin32-x86-multi-thread).
I've just emerged from a three hour long debugging session, trying to find the source of an error. I found there was simply no error, but for some reason ADO's connection object was getting the `Errors.Count` increased with each printed message in my stored procedure's output.
Consider following Transact SQL code:
```
CREATE PROCEDURE dbo.My_Sample() AS
BEGIN TRAN my_tran
-- Does something useful
if @@error <> 0 BEGIN
ROLLBACK TRAN my_tran
RAISERROR( 'SP My_Sample failed', 16, 1)
END ELSE BEGIN
COMMIT TRAN my_tran
PRINT 'SP My_Sample succeeded'
END
```
Now imagine a Perl sub more or less like:
```
sub execute_SQL {
# $conn is an already opened ADO connection object
# pointing to my SQL Server
# $sql is the T-SQL statement to be executed
my($conn, $sql) = @_;
$conn->Execute($sql);
my $error_collection = $conn->Errors();
my $ecount = $error_collection->Count;
if ($ecount == 0 ) { return 0; }
print "\n" . $ecount . " errors found\n";
print "Executed SQL Code:\n$sql\n\n";
print "Errors while executing:\n";
foreach my $error (in $error_collection){
print "Error: [" . $error->{Number} . "] " . $error->{Description} . "\n";
}
return 1;
}
```
Somewhere else, in the main Perl code, I'm calling the above sub as:
```
execute_SQL( $conn, 'EXEC dbo.My_Sample' );
```
In the end I got it that *every* PRINT statement causes a new pseudo-error to be appended to the ADO Errors collection. The quick fix I implemented was to change that PRINT in the SP into a SELECT, to bypass this.
The questions I'd like to ask are:
* Is this behaviour normal?
* Is there a way to avoid/bypass it?
|
This is to be expected as it's what ADO does and the Win32::ADO is quite a thin layer above it.
ref: knowledge base [note that the RAISERROR and PRINT statements are returned through the ADO errors collection](http://support.microsoft.com/kb/194792)
|
223,627 |
<p>I'm trying to get a query working that takes the values (sometimes just the first part of a string) from a form control. The problem I have is that it only returns records when the full string is typed in.</p>
<p>i.e. in the surname box, I should be able to type gr, and it brings up </p>
<p>green
grey
graham</p>
<p>but at present it's not bringing up anything uless the full search string is used.</p>
<p>There are 4 search controls on the form in question, and they are only used in the query if the box is filled in.</p>
<p>The query is :</p>
<pre><code>SELECT TabCustomers.*,
TabCustomers.CustomerForname AS NameSearch,
TabCustomers.CustomerSurname AS SurnameSearch,
TabCustomers.CustomerDOB AS DOBSearch,
TabCustomers.CustomerID AS MemberSearch
FROM TabCustomers
WHERE IIf([Forms]![FrmSearchCustomer]![SearchMember] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchMember]=[customerid])=True
AND IIf([Forms]![FrmSearchCustomer].[SearchFore] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchFore] Like [customerforname] & "*")=True
AND IIf([Forms]![FrmSearchCustomer]![SearchLast] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchLast] Like [customersurname] & "*")=True
AND IIf([Forms]![FrmSearchCustomer]![Searchdate] Is Null
,True
,[Forms]![FrmSearchCustomer]![Searchdate] Like [customerDOB] & "*")=True;
</code></pre>
|
[
{
"answer_id": 223648,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>My only thoguht is that maybe a () is needed to group the like</p>\n\n<p>For example a snippet on the first part</p>\n\n<pre><code>,[Forms]![FrmSearchCustomer]![SearchFore] Like ([customerforname] & \"*\"))=True\n</code></pre>\n\n<p>It has been a while since I've used access, but it is the first thing that comes to mind</p>\n"
},
{
"answer_id": 223710,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "<p>This is a complete re-write to allow for nulls in the name fields or the date of birth field. This query will not fail as too complex if text is entered in the numeric customerid field.</p>\n\n<pre><code>SELECT TabCustomers.CustomerForname AS NameSearch, TabCustomers.CustomerSurname AS SurnameSearch, TabCustomers.CustomerDOB AS DOBSearch, TabCustomers.customerid AS MemberSearch\nFROM TabCustomers\nWHERE TabCustomers.customerid Like IIf([Forms]![FrmSearchCustomer].[Searchmember] Is Null,\"*\",[Forms]![FrmSearchCustomer]![Searchmember])\nAND Trim(TabCustomers.CustomerForname & \"\") Like IIf([Forms]![FrmSearchCustomer].[SearchFore] Is Null,\"*\",[Forms]![FrmSearchCustomer]![SearchFore] & \"*\")\nAND Trim(TabCustomers.CustomerSurname & \"\") like IIf([Forms]![FrmSearchCustomer].[Searchlast] Is Null,\"*\",[Forms]![FrmSearchCustomer]![SearchLast] & \"*\")\nAND (TabCustomers.CustomerDOB Like IIf([Forms]![FrmSearchCustomer].[SearchDate] Is Null,\"*\",[Forms]![FrmSearchCustomer]![SearchDate] ) Or TabCustomers.CustomerDOB Is Null)\n</code></pre>\n"
},
{
"answer_id": 223733,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 2,
"selected": false,
"text": "<p>Two things are going on - the comparisions should be reversed and you are not quoting strings properly.</p>\n\n<p>It should be [database field] like \"partial string + wild card\"</p>\n\n<p>and all strings need to be surrounded by quotes - not sure why your query doesn't throw errors</p>\n\n<p>So the following should work:</p>\n\n<pre><code>,[customerforname] Like \"\"\"\" & [Forms]![FrmSearchCustomer]![SearchFore] & \"*\"\"\" )=True\n</code></pre>\n\n<p>Note the \"\"\"\" that is the only way to append a single double-quote to a string.</p>\n"
},
{
"answer_id": 223791,
"author": "Godeke",
"author_id": 28006,
"author_profile": "https://Stackoverflow.com/users/28006",
"pm_score": 3,
"selected": false,
"text": "<p>You have your LIKE expression backwards. I have rewritten the query to remove the unnecessary IIF commands and to fix your order of operands for the LIKE operator:</p>\n\n<pre><code>SELECT TabCustomers.*\nFROM TabCustomers\nWHERE (Forms!FrmSearchCustomer!SearchMember Is Null Or Forms!FrmSearchCustomer!SearchMember=[customerid]) \nAnd (Forms!FrmSearchCustomer.SearchFore Is Null Or [customerforname] Like Forms!FrmSearchCustomer!SearchFore & \"*\") \nAnd (Forms!FrmSearchCustomer!SearchLast Is Null Or [customersurname] Like Forms!FrmSearchCustomer!SearchLast & \"*\") \nAnd (Forms!FrmSearchCustomer!Searchdate Is Null Or [customerDOB] Like Forms!FrmSearchCustomer!Searchdate & \"*\");\n</code></pre>\n\n<p>I built that query by replicating the most likely circumstance: I created a dummy table with the fields mentioned and a form with the fields and a subform with the query listed above being refreshed when the search button was pushed. I can provide a download link to the example I created if you would like. The example works as expected. J only picks up both Jim and John, while John or Jo only pulls the John record.</p>\n"
},
{
"answer_id": 224961,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 4,
"selected": true,
"text": "<h2>There is an Access Method for that!</h2>\n\n<p>If you have your \"filter\" controls on the form, why don't you use the Application.buildCriteria method, that will allow you to add your filtering criterias to a string, then make a filter out of this string, and build your WHERE clause on the fly?</p>\n\n<pre><code>selectClause = \"SELECT TabCustomers.* FROM TabCustomers\"\nif not isnull(Forms!FrmSearchCustomer!SearchMember) then\n whereClause = whereClause & application.buildCriteria(your field name, your field type, your control value) & \" AND \"\nendif\nif not isnull(Forms!FrmSearchCustomer!SearchFore) then\n whereClause = whereClause & application.buildCriteria(...) & \" AND \"\nendif\nif not isnull(Forms!FrmSearchCustomer!SearchLast) then\n whereClause = whereClause & application.buildCriteria(...) & \" AND \"\nendif\nif not isnull(Forms!FrmSearchCustomer!SearchDate) then\n whereClause = whereClause & application.buildCriteria(...) & \" AND \"\nendif\n--get rid of the last \"AND\"\nif len(whereClause) > 0 then\n whereClause = left(whereClause,len(whereClause)-5)\n selectClause = selectClause & \" WHERE \" & whereClause\nendif\n-- your SELECT instruction is ready ...\n</code></pre>\n\n<p>EDIT: the buildCriteria will return (for example):</p>\n\n<ul>\n<li><code>'field1 = \"GR\"'</code> when you type \"GR\" in the control</li>\n<li><code>'field1 LIKE \"GR*\"'</code> when you type <code>\"GR*\"</code> in the control</li>\n<li><code>'field1 LIKE \"GR*\" or field1 like \"BR*\"'</code> if you type <code>'LIKE \"GR*\" OR LIKE \"BR*\"'</code> in the control </li>\n</ul>\n\n<p>PS: if your \"filter\" controls on your form always have the same syntax (let's say \"search_fieldName\", where \"fieldName\" corresponds to the field in the underlying recordset) and are always located in the same zone (let's say formHeader), it is then possible to write a function that will automatically generate a filter for the current form. This filter can then be set as the form filter, or used for something else:</p>\n\n<pre><code>For each ctl in myForm.section(acHeader).controls\n if ctl.name like \"search_\"\n fld = myForm.recordset.fields(mid(ctl.name,8))\n if not isnull(ctl.value) then\n whereClause = whereClause & buildCriteria(fld.name ,fld.type, ctl.value) & \" AND \"\n endif\n endif\nnext ctl\nif len(whereClause)> 0 then ...\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] |
I'm trying to get a query working that takes the values (sometimes just the first part of a string) from a form control. The problem I have is that it only returns records when the full string is typed in.
i.e. in the surname box, I should be able to type gr, and it brings up
green
grey
graham
but at present it's not bringing up anything uless the full search string is used.
There are 4 search controls on the form in question, and they are only used in the query if the box is filled in.
The query is :
```
SELECT TabCustomers.*,
TabCustomers.CustomerForname AS NameSearch,
TabCustomers.CustomerSurname AS SurnameSearch,
TabCustomers.CustomerDOB AS DOBSearch,
TabCustomers.CustomerID AS MemberSearch
FROM TabCustomers
WHERE IIf([Forms]![FrmSearchCustomer]![SearchMember] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchMember]=[customerid])=True
AND IIf([Forms]![FrmSearchCustomer].[SearchFore] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchFore] Like [customerforname] & "*")=True
AND IIf([Forms]![FrmSearchCustomer]![SearchLast] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchLast] Like [customersurname] & "*")=True
AND IIf([Forms]![FrmSearchCustomer]![Searchdate] Is Null
,True
,[Forms]![FrmSearchCustomer]![Searchdate] Like [customerDOB] & "*")=True;
```
|
There is an Access Method for that!
-----------------------------------
If you have your "filter" controls on the form, why don't you use the Application.buildCriteria method, that will allow you to add your filtering criterias to a string, then make a filter out of this string, and build your WHERE clause on the fly?
```
selectClause = "SELECT TabCustomers.* FROM TabCustomers"
if not isnull(Forms!FrmSearchCustomer!SearchMember) then
whereClause = whereClause & application.buildCriteria(your field name, your field type, your control value) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchFore) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchLast) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchDate) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
--get rid of the last "AND"
if len(whereClause) > 0 then
whereClause = left(whereClause,len(whereClause)-5)
selectClause = selectClause & " WHERE " & whereClause
endif
-- your SELECT instruction is ready ...
```
EDIT: the buildCriteria will return (for example):
* `'field1 = "GR"'` when you type "GR" in the control
* `'field1 LIKE "GR*"'` when you type `"GR*"` in the control
* `'field1 LIKE "GR*" or field1 like "BR*"'` if you type `'LIKE "GR*" OR LIKE "BR*"'` in the control
PS: if your "filter" controls on your form always have the same syntax (let's say "search\_fieldName", where "fieldName" corresponds to the field in the underlying recordset) and are always located in the same zone (let's say formHeader), it is then possible to write a function that will automatically generate a filter for the current form. This filter can then be set as the form filter, or used for something else:
```
For each ctl in myForm.section(acHeader).controls
if ctl.name like "search_"
fld = myForm.recordset.fields(mid(ctl.name,8))
if not isnull(ctl.value) then
whereClause = whereClause & buildCriteria(fld.name ,fld.type, ctl.value) & " AND "
endif
endif
next ctl
if len(whereClause)> 0 then ...
```
|
223,628 |
<p>I have derived a TabControl with the express purpose of enabling double buffering, except nothing is working as expected. Here is the TabControl code:</p>
<pre><code>class DoubleBufferedTabControl : TabControl
{
public DoubleBufferedTabControl() : base()
{
this.DoubleBuffered = true;
this.SetStyle
(
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.SupportsTransparentBackColor,
false
);
}
}
</code></pre>
<p>This Tabcontrol is then set with it's draw mode as 'OwnerDrawnFixed' so i can changed the colours. Here is the custom drawing method:</p>
<pre><code> private void Navigation_PageContent_DrawItem(object sender, DrawItemEventArgs e)
{
//Structure.
Graphics g = e.Graphics;
TabControl t = (TabControl)sender;
TabPage CurrentPage = t.TabPages[e.Index];
//Get the current tab
Rectangle CurrentTabRect = t.GetTabRect(e.Index);
//Get the last tab.
Rectangle LastTab = t.GetTabRect(t.TabPages.Count - 1);
//Main background rectangle.
Rectangle BackgroundRect = new Rectangle(LastTab.Width, t.Bounds.Y - 4, t.Width - (LastTab.Width), t.Height);
//Tab background rectangle.
Rectangle TabBackgroundRect = new Rectangle(0, LastTab.Y + LastTab.Height, LastTab.Width, t.Bounds.Height - (LastTab.Y + LastTab.Height));
//Set anitialiasing for the text.
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
//String format for the text.
StringFormat StringFormat = new StringFormat();
StringFormat.Alignment = StringAlignment.Center;
StringFormat.LineAlignment = StringAlignment.Center;
//Fill the background.
g.FillRectangle(Brushes.LightGray, BackgroundRect);
g.FillRectangle(Brushes.Bisque, TabBackgroundRect);
//Draw the selected tab.
if(e.State == DrawItemState.Selected)
{
g.FillRectangle(Brushes.White, e.Bounds);
Rectangle SelectedTabOutline = new Rectangle(e.Bounds.X + 2, e.Bounds.Y + 2, e.Bounds.Width, e.Bounds.Height - 4);
g.DrawRectangle(new Pen(Brushes.LightGray, 4f), SelectedTabOutline);
g.DrawString(CurrentPage.Text, new Font("Arial", 12f, FontStyle.Bold, GraphicsUnit.Point), new SolidBrush(Color.FromArgb(70, 70, 70)), CurrentTabRect, StringFormat);
}
else
{
g.FillRectangle(new SolidBrush(Color.FromArgb(230, 230, 230)), e.Bounds);
g.DrawString(CurrentPage.Text, new Font("Arial", 12f, FontStyle.Regular, GraphicsUnit.Point), Brushes.Gray, CurrentTabRect, StringFormat);
}
}
</code></pre>
<p>All to no avail however, as this control is not double buffered and still flickers when resized.</p>
<p><strong>Any ideas?</strong></p>
|
[
{
"answer_id": 223676,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure, but you might try double-buffering the control that contains the tab control. </p>\n"
},
{
"answer_id": 224425,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 0,
"selected": false,
"text": "<p>I looked around quite a bit, tried your code and whatever else I could think of, but I don't see a way to get rid of the flicker. Unfortunately, in my tests even a regular (non-owner-drawn) tab control flickers during resizing.</p>\n\n<p>For what it's worth, turning off \"Show window contents while dragging\" will fix it, but I realize that may not be helpful.</p>\n"
},
{
"answer_id": 227983,
"author": "Robert C. Barth",
"author_id": 9209,
"author_profile": "https://Stackoverflow.com/users/9209",
"pm_score": 3,
"selected": true,
"text": "<p>If you read the documentation, it says, \"This member is not meaningful for this control.\" If you want the control to be drawn utilizing double-buffering, you'll have to implement it yourself. Besides the fact that if you owner-draw the control, you would have to implement double-buffering yourself anyhow.</p>\n"
},
{
"answer_id": 277872,
"author": "Eric W",
"author_id": 14972,
"author_profile": "https://Stackoverflow.com/users/14972",
"pm_score": 0,
"selected": false,
"text": "<p>I think it doesn't work because you are disabling double buffering!</p>\n\n<p>All <code>this.DoubleBuffered = true</code> does is set ControlStyles.OptimizedDoubleBuffer to true. Since you are disabling that flag in the next line of your program, you are really doing nothing. Remove ControlStyles.OptimizedDoubleBuffer (and perhaps ControlStyles.AllPaintingInWmPaint) and it should work for you.</p>\n"
},
{
"answer_id": 278958,
"author": "Peter Crabtree",
"author_id": 36283,
"author_profile": "https://Stackoverflow.com/users/36283",
"pm_score": 2,
"selected": false,
"text": "<p>First of all, you can get rid of your <code>TabControl</code> code—you turn on buffering, and then immediately turn it off, so it's not actually doing anything useful.</p>\n\n<p>Part of your problem is that you're trying to paint just <em>part</em> of the <code>TabControl</code>.</p>\n\n<p>The easiest solution that gives about a 90% solution (it's still possible to get a flicker) is to add this to your form class:</p>\n\n<pre><code>protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= 0x02000000;\n return cp;\n }\n}\n</code></pre>\n\n<p>If you want to be <em>very</em> sure of getting no flicker, you'll need to draw the entire <code>TabControl</code> yourself, and make sure to ignore background painting requests.</p>\n\n<p>Edit: Note that this will only work in XP and later.</p>\n"
},
{
"answer_id": 302760,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I've had problems with double buffering on controls in the past and the only way to stop the flicker was to ensure the inherited OnPaintBackground method was not being called. (See code below) You will also need to ensure the entire backgound is painted during your paint call.</p>\n\n<pre><code>protected override void OnPaintBackground( PaintEventArgs pevent )\n{\n //do not call base - I don't want the background re-painted!\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
I have derived a TabControl with the express purpose of enabling double buffering, except nothing is working as expected. Here is the TabControl code:
```
class DoubleBufferedTabControl : TabControl
{
public DoubleBufferedTabControl() : base()
{
this.DoubleBuffered = true;
this.SetStyle
(
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.SupportsTransparentBackColor,
false
);
}
}
```
This Tabcontrol is then set with it's draw mode as 'OwnerDrawnFixed' so i can changed the colours. Here is the custom drawing method:
```
private void Navigation_PageContent_DrawItem(object sender, DrawItemEventArgs e)
{
//Structure.
Graphics g = e.Graphics;
TabControl t = (TabControl)sender;
TabPage CurrentPage = t.TabPages[e.Index];
//Get the current tab
Rectangle CurrentTabRect = t.GetTabRect(e.Index);
//Get the last tab.
Rectangle LastTab = t.GetTabRect(t.TabPages.Count - 1);
//Main background rectangle.
Rectangle BackgroundRect = new Rectangle(LastTab.Width, t.Bounds.Y - 4, t.Width - (LastTab.Width), t.Height);
//Tab background rectangle.
Rectangle TabBackgroundRect = new Rectangle(0, LastTab.Y + LastTab.Height, LastTab.Width, t.Bounds.Height - (LastTab.Y + LastTab.Height));
//Set anitialiasing for the text.
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
//String format for the text.
StringFormat StringFormat = new StringFormat();
StringFormat.Alignment = StringAlignment.Center;
StringFormat.LineAlignment = StringAlignment.Center;
//Fill the background.
g.FillRectangle(Brushes.LightGray, BackgroundRect);
g.FillRectangle(Brushes.Bisque, TabBackgroundRect);
//Draw the selected tab.
if(e.State == DrawItemState.Selected)
{
g.FillRectangle(Brushes.White, e.Bounds);
Rectangle SelectedTabOutline = new Rectangle(e.Bounds.X + 2, e.Bounds.Y + 2, e.Bounds.Width, e.Bounds.Height - 4);
g.DrawRectangle(new Pen(Brushes.LightGray, 4f), SelectedTabOutline);
g.DrawString(CurrentPage.Text, new Font("Arial", 12f, FontStyle.Bold, GraphicsUnit.Point), new SolidBrush(Color.FromArgb(70, 70, 70)), CurrentTabRect, StringFormat);
}
else
{
g.FillRectangle(new SolidBrush(Color.FromArgb(230, 230, 230)), e.Bounds);
g.DrawString(CurrentPage.Text, new Font("Arial", 12f, FontStyle.Regular, GraphicsUnit.Point), Brushes.Gray, CurrentTabRect, StringFormat);
}
}
```
All to no avail however, as this control is not double buffered and still flickers when resized.
**Any ideas?**
|
If you read the documentation, it says, "This member is not meaningful for this control." If you want the control to be drawn utilizing double-buffering, you'll have to implement it yourself. Besides the fact that if you owner-draw the control, you would have to implement double-buffering yourself anyhow.
|
223,640 |
<p>My class is implementing a super-class method which which returns <code>List<JComponent></code>. The list being returned is read-only:</p>
<pre><code>public abstract class SuperClass {
public abstract List<JComponent> getComponents();
}
</code></pre>
<p>In my class, I want to return a field which is declared as List - i.e. a sub-list:</p>
<pre><code>public class SubClass extends SuperClass {
private List<JButton> buttons;
public List<JComponent> getComponents() {
return buttons;
}
}
</code></pre>
<p>This generates a compiler error, as <code>List<JButton></code> is not a subtype of <code>List<JComponent></code>.</p>
<p>I can understand why it doesn't compile, as it shouldn't be allowed to add a JTextField to a List of JButtons.</p>
<p>However, as the list is read-only, then "conceptually" this should be allowed. But, of course, the compiler doesn't know that it is read-only.</p>
<p>Is there any way to achieve what I want to achieve, without changing the method declaration in the super-class, and the field declaration in the sub-class?</p>
<p>Thanks,
Calum</p>
|
[
{
"answer_id": 223653,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>Declare <code>getComponents()</code> as:</p>\n\n<pre><code>public List<? extends JComponent> getComponents()\n</code></pre>\n"
},
{
"answer_id": 223670,
"author": "Guðmundur Bjarni",
"author_id": 27349,
"author_profile": "https://Stackoverflow.com/users/27349",
"pm_score": 0,
"selected": false,
"text": "<p>To do this you need to widen the generics thingy. :)</p>\n\n<pre><code>public abstract class SuperClass {\n public abstract List<? extends JComponent> getComponents();\n}\n\n\npublic class SubClass extends SuperClass {\n private List<JButton> buttons;\n public List<? extends JComponent> getComponents() {\n return buttons;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 223672,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 0,
"selected": false,
"text": "<p>Hmm, not sure</p>\n\n<p>The usual way to set that up would be to have the super look like </p>\n\n<pre><code>public abstract class SuperClass {\n public abstract List<? extends JComponent> getComponents();\n}\n</code></pre>\n\n<p>Not sure how to do it without changing that around.</p>\n"
},
{
"answer_id": 223718,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": -1,
"selected": false,
"text": "<p>You could do the cast with <code>@SuppressWarnings</code>. I believe that would be appropriate in this case, just make sure you document why in a comment.</p>\n\n<p>Alternately, do the following:</p>\n\n<pre><code>public List<JComponent> getComponents()\n{\n return new ArrayList<JComponent>( buttons );\n}\n</code></pre>\n\n<p>Yes I know this makes a copy and the list is already read-only. But until the profiler tells you otherwise, I would assume the penalty is small.</p>\n\n<p>@Calum: I agree that using ?-expressions in return types is bad form because calling code is unable to do this for example:</p>\n\n<pre><code>List<JComponent> list = obj.getComponents();\n</code></pre>\n"
},
{
"answer_id": 223768,
"author": "Instantsoup",
"author_id": 9861,
"author_profile": "https://Stackoverflow.com/users/9861",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think you can do what you want without changing either the super-class method signature or the sub-class list declaration. The super-class is rigidly defining the return type to be JComponent. There's no way to make your return type anything but JComponent.</p>\n\n<p>If it's read-only, I'd do something like:</p>\n\n<pre><code>public class SubClass extends SuperClass {\n private List<JComponent> buttons = new ArrayList<JComponent>();\n public void addButton(JButton button) {\n buttons.add(button);\n }\n public List<JComponent> getComponents() {\n return Collections.unmodifiableList(buttons);\n }\n}\n</code></pre>\n\n<p>If you can modify the super-class, you could try something like:</p>\n\n<pre><code>public abstract class SuperClass<E extends JComponent> {\n public abstract List<E> getComponents();\n}\n\npublic class SubClass extends SuperClass<JButton> {\n private List<JButton> buttons = new ArrayList<JButton>();\n public List<JButton> getComponents() {\n return Collections.unmodifiableList(buttons);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 223786,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I think I've found the answer which I'm looking for...</p>\n\n<pre><code>return Collections.<JComponent>unmodifiableList(buttons);\n</code></pre>\n\n<p>I had previously tried:</p>\n\n<pre><code>return Collections.unmodifiableList(buttons);\n</code></pre>\n\n<p>but this was being type-inferenced to <code>List<JButton></code>.</p>\n\n<p>Putting in the explicit type parameter allows the <code>List<JButton></code> to be treated as a <code>List<JComponent></code>, which is allowed by <code>unmodifiableList()</code>.</p>\n\n<p>I'm happy now ;-) and I've learned something thanks to the discussion.</p>\n\n<p>Calum</p>\n"
},
{
"answer_id": 223801,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 0,
"selected": false,
"text": "<p>The whole point of generics is to provide compile-time type-safety fo things such as the \"type\" of a collection. Unfortunately for you, a <code>List<JButton></code> is not a sub-type of a <code>List<JComponent></code>. the reason for this is simple and is as follows:</p>\n\n<pre><code>List<JComponent> jc;\nList<JButton> jb = new ArrayList<JButton>();\n//if List<JButton> was a sublcass of List<JComponent> then this is a valid assignment\njc = jb;\njc.add(new JCheckBox()); //valid, as jc accepts any JComponent\n\nJButton b = jb.get(0); //this will throw a ClassCastException, rendering Generic type-safety pointless\n</code></pre>\n\n<p>Generics are <em>contra-variant</em> in this manner, your original desire might as well have been to override a method which returned a <code>String</code> with one which returned a <code>Float</code></p>\n\n<p>I think it's a good general rule to be <strong>very careful</strong> when designing a generic class. Do you really need generics? How will it get used? Some generic designs end up with awful structures and mean users have to revert to the <em>raw</em> version. <code>JTable</code>'s filtering mechanism is an excellent case in point: when you want to implement a filter-chain (which you certainly will!), the whole thing falls apart. The fact is; in this case, generics were added at a cost and with practically no benefit.</p>\n"
},
{
"answer_id": 660940,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Returning a generic type with wildcard is not a good idea as it forces the client to think about what's being returned ... It'll also make the client code more cumbersome and difficult to read.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
My class is implementing a super-class method which which returns `List<JComponent>`. The list being returned is read-only:
```
public abstract class SuperClass {
public abstract List<JComponent> getComponents();
}
```
In my class, I want to return a field which is declared as List - i.e. a sub-list:
```
public class SubClass extends SuperClass {
private List<JButton> buttons;
public List<JComponent> getComponents() {
return buttons;
}
}
```
This generates a compiler error, as `List<JButton>` is not a subtype of `List<JComponent>`.
I can understand why it doesn't compile, as it shouldn't be allowed to add a JTextField to a List of JButtons.
However, as the list is read-only, then "conceptually" this should be allowed. But, of course, the compiler doesn't know that it is read-only.
Is there any way to achieve what I want to achieve, without changing the method declaration in the super-class, and the field declaration in the sub-class?
Thanks,
Calum
|
Declare `getComponents()` as:
```
public List<? extends JComponent> getComponents()
```
|
223,643 |
<p>I'm currently adding some new extended classes to this code:</p>
<pre><code>foreach (BaseType b in CollectionOfExtendedTypes) {
if (b is ExtendedType1) {
((ExtendedType1) b).foo = this;
}
else if (b is ExtendedType2) {
((ExtenedType2) b).foo = this;
}
else {
b.foo = this;
}
}
</code></pre>
<p>and was curious if there is a way to use the <code>is</code> keyword functionality in a switch statement?</p>
|
[
{
"answer_id": 223647,
"author": "Ray Li",
"author_id": 28952,
"author_profile": "https://Stackoverflow.com/users/28952",
"pm_score": -1,
"selected": false,
"text": "<p>In C#, I believe the switch statement only works with integers and strings.</p>\n"
},
{
"answer_id": 223650,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 3,
"selected": false,
"text": "<p>Nope. See</p>\n\n<p><a href=\"https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why\">C# switch statement limitations - why?</a></p>\n"
},
{
"answer_id": 223658,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": false,
"text": "<p>In C# it's not possible to use the \"is\" keyword as part of a switch statement. All case labels in a switch must evaluate to constant expressions. \"is\" is not convertible to a constant expression.</p>\n\n<p>I definately feel the pain though when it comes to switching on types. Because really the solution you outlined works but it's a conveluted way of saying for x do y, and a do b. It would be much more natular to write it more like the following </p>\n\n<pre><code>\nTypeSwitch.Do(\n sender,\n TypeSwitch.Case<Button>(() => textBox1.Text = \"Hit a Button\"),\n TypeSwitch.Case<CheckBox>(x => textBox1.Text = \"Checkbox is \" + x.Checked),\n TypeSwitch.Default(() => textBox1.Text = \"Not sure what is hovered over\"));\n</code></pre>\n\n<p>Here's a blog post I wrote on how to achieve this functionality. </p>\n\n<p><a href=\"http://blogs.msdn.com/jaredpar/archive/2008/05/16/switching-on-types.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/jaredpar/archive/2008/05/16/switching-on-types.aspx</a></p>\n"
},
{
"answer_id": 223667,
"author": "Owen",
"author_id": 4790,
"author_profile": "https://Stackoverflow.com/users/4790",
"pm_score": 1,
"selected": false,
"text": "<p>You could add a method <code>getType()</code> to <code>BaseType</code> that is implemented by each concrete subclass to return a unique integral ID (possibly an enum) and switch on that, yes?</p>\n"
},
{
"answer_id": 223680,
"author": "Fry",
"author_id": 23553,
"author_profile": "https://Stackoverflow.com/users/23553",
"pm_score": 1,
"selected": false,
"text": "<p>Not really, switches match a variable (string or int (or enum) ) with a constant expression as the switch statement.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/06tc147t(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/06tc147t(VS.71).aspx</a></p>\n"
},
{
"answer_id": 223688,
"author": "Samuel Kim",
"author_id": 437435,
"author_profile": "https://Stackoverflow.com/users/437435",
"pm_score": 2,
"selected": false,
"text": "<p>While it is not possible to use switch statement for checking types, it is not impossible to reduce the problem to a more manageable codebase.</p>\n\n<p>Depending on the specific situation and requirement I would consider.</p>\n\n<ul>\n<li><p>Using a <code>IDictionary<Type, T></code> to store the result in a dictionary. T could itself be a delegate that you can call on. This will work if you don't need to worry about inheritance - catering for inheritance will take a little more work.</p></li>\n<li><p>Using the type name of the class (which is string) inside the switch statement. This uses <code>switch (b.GetType().Name)</code> and there is no option for deep inheritance structure.</p></li>\n</ul>\n"
},
{
"answer_id": 223693,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 5,
"selected": true,
"text": "<p>This really looks like a situation for a good polymorphic implementation. If you override the appropriate methods in the derived classes, you may not need the checks in the loop at all.</p>\n"
},
{
"answer_id": 223856,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": -1,
"selected": false,
"text": "<p>There's another thing to think about besides the way that the compiler handles <code>switch</code> statements, and that's the functioning of the <code>is</code> operator. There's a big difference between:</p>\n\n<pre><code>if (obj is Foo)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if (obj.GetType() == typeof(Foo))\n</code></pre>\n\n<p>Despite the name, the <code>is</code> operator tells you if an object is <em>compatible</em> with a given type, not if it <em>is</em> of the given type. This leads to not-entirely-obvious bugs (though this one's pretty obvious) that look like:</p>\n\n<pre><code>if (obj is System.Object)\n{\n //this will always execute\n}\nelse if (obj is Foo)\n{\n //this will never execute\n}\n</code></pre>\n\n<p>Many of the suggestions here point you in the direction of using the object's type. That's fine if what you really want is logic associated with each type. But if that's the case, walk carefully when using the <code>is</code> operator.</p>\n\n<p>Also: though you can't modify these base types, that doesn't mean that you can't use Owen's suggestion. You could implement extension methods:</p>\n\n<pre><code>public enum MyType { Foo, Bar, Baz };\npublic static class MyTypeExtension\n{\n public static MyType GetMyType(this Foo o)\n {\n return MyType.Foo;\n }\n public static MyType GetMyType(this Bar o)\n {\n return MyType.Bar;\n }\n public static MyType GetMyType(this Baz o)\n {\n return MyType.Baz;\n }\n}\n</code></pre>\n\n<p>Then you <em>can</em> use a <code>switch</code> statement:</p>\n\n<pre><code>switch (myObject.GetType())\n{\n case MyType.Foo:\n // etc.\n</code></pre>\n"
},
{
"answer_id": 449511,
"author": "Jeffrey Hantin",
"author_id": 55637,
"author_profile": "https://Stackoverflow.com/users/55637",
"pm_score": 0,
"selected": false,
"text": "<p>Type-cases and object oriented code don't seem to get on that well together in my experience. The approach I prefer in this situation is the <a href=\"http://c2.com/cgi/wiki?DoubleDispatch\" rel=\"nofollow noreferrer\">double dispatch pattern</a>. In short:</p>\n\n<ul>\n<li><b>Create a listener type</b> with an empty virtual method Process(ExtendedTypeN arg) for each extended type you will be dispatching over.\n<li><b>Add a virtual method</b> Dispatch(Listener listener) to the base type that takes a listener as argument. Its implementation will be to call listener.Process((Base) this).\n<li><b>Over<i>ride</i></b> the Dispatch method in each extended type to call the appropriate <b>over<i>load</i></b> of Process in the listener type.\n<li><b>Extend the listener type</b> by overriding the appropriate Process method for each subtype you are interested in.\n</ul>\n\n<p>The argument shuffling dance eliminates the narrowing cast by folding it into the call to Dispatch -- the receiver knows its exact type, and communicates it by calling back the exact overload of Process for its type. This is also a big performance win in implementations such as .NET Compact Framework, in which narrowing casts are extremely slow but virtual dispatch is fast.</p>\n\n<p>The result will be something like this:</p>\n\n<pre><code>\npublic class Listener\n{\n public virtual void Process(Base obj) { }\n public virtual void Process(Derived obj) { }\n public virtual void Process(OtherDerived obj) { }\n}\n\npublic class Base\n{\n public virtual void Dispatch(Listener l) { l.Process(this); }\n}\n\npublic class Derived\n{\n public override void Dispatch(Listener l) { l.Process(this); }\n}\n\npublic class OtherDerived\n{\n public override void Dispatch(Listener l) { l.Process(this); }\n}\n\npublic class ExampleListener\n{\n public override void Process(Derived obj)\n {\n Console.WriteLine(\"I got a Derived\");\n }\n\n public override void Process(OtherDerived obj)\n {\n Console.WriteLine(\"I got an OtherDerived\");\n }\n\n public void ProcessCollection(IEnumerable collection)\n {\n foreach (Base obj in collection) obj.Dispatch(this);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47575390,
"author": "MikeT",
"author_id": 735897,
"author_profile": "https://Stackoverflow.com/users/735897",
"pm_score": 5,
"selected": false,
"text": "<p>The latest version of C# (7) now includes this functionality</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch#type-pattern\" rel=\"noreferrer\">Type pattern</a></p>\n\n<p>The type pattern enables concise type evaluation and conversion. When used with the switch statement to perform pattern matching, it tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type. Its syntax is:</p>\n\n<pre><code> case type varname \n</code></pre>\n"
},
{
"answer_id": 49688285,
"author": "smoksnes",
"author_id": 4949005,
"author_profile": "https://Stackoverflow.com/users/4949005",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned in the <a href=\"https://stackoverflow.com/a/47575390/4949005\">answer</a> from <a href=\"https://stackoverflow.com/users/735897/miket\">MikeT</a>, you are able to use <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch\" rel=\"nofollow noreferrer\">pattern mathing</a> which requires C# 7.</p>\n\n<p>Here's an example for your code:</p>\n\n<pre><code>foreach (BaseType b in CollectionOfExtendedTypes) {\n switch (b) {\n case ExtendedType1 et1:\n // Do stuff with et1.\n et1.DoStuff();\n break;\n case ExtendedType2 et2:\n // Do stuff with et2.\n et2.DoOtherStuff();\n break;\n default:\n // Do something else...\n break;\n }\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21387/"
] |
I'm currently adding some new extended classes to this code:
```
foreach (BaseType b in CollectionOfExtendedTypes) {
if (b is ExtendedType1) {
((ExtendedType1) b).foo = this;
}
else if (b is ExtendedType2) {
((ExtenedType2) b).foo = this;
}
else {
b.foo = this;
}
}
```
and was curious if there is a way to use the `is` keyword functionality in a switch statement?
|
This really looks like a situation for a good polymorphic implementation. If you override the appropriate methods in the derived classes, you may not need the checks in the loop at all.
|
223,652 |
<p>I was wondering if there is any way to escape a CDATA end token (<code>]]></code>) within a CDATA section in an xml document. Or, more generally, if there is some escape sequence for using within a CDATA (but if it exists, I guess it'd probably only make sense to escape begin or end tokens, anyway). </p>
<p>Basically, can you have a begin or end token embedded in a CDATA and tell the parser not to interpret it but to treat it as just another character sequence.</p>
<p>Probably, you should just refactor your xml structure or your code if you find yourself trying to do that, but even though I've been working with xml on a daily basis for the last 3 years or so and I have never had this problem, I was wondering if it was possible. Just out of curiosity.</p>
<p>Edit:</p>
<p>Other than using html encoding...</p>
|
[
{
"answer_id": 223773,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 7,
"selected": false,
"text": "<p>You have to break your data into pieces to conceal the <code>]]></code>.</p>\n\n<p>Here's the whole thing:</p>\n\n<p><code><![CDATA[]]]]><![CDATA[>]]></code></p>\n\n<p>The first <code><![CDATA[]]]]></code> has the <code>]]</code>. The second <code><![CDATA[>]]></code> has the <code>></code>.</p>\n"
},
{
"answer_id": 223782,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 8,
"selected": true,
"text": "<p>Clearly, this question is purely academic. Fortunately, it has a very definite answer.</p>\n<p>You cannot escape a CDATA end sequence. Production rule 20 of the XML <a href=\"http://www.w3.org/TR/REC-xml/#sec-cdata-sect\" rel=\"noreferrer\">specification</a> is quite clear:</p>\n<pre><code>[20] CData ::= (Char* - (Char* ']]>' Char*))\n</code></pre>\n<p>EDIT: This product rule literally means "A CData section may contain anything you want BUT the sequence ']]>'. No exception.".</p>\n<p>EDIT2: The <a href=\"http://www.w3.org/TR/REC-xml/#sec-cdata-sect\" rel=\"noreferrer\">same section</a> also reads:</p>\n<blockquote>\n<p>Within a CDATA section, only the CDEnd string is recognized as markup, so that left angle brackets and ampersands may occur in their literal form; they need not (and cannot) be escaped using "<code>&lt;</code>" and "<code>&amp;</code>". CDATA sections cannot nest.</p>\n</blockquote>\n<p>In other words, it's not possible to use entity reference, markup or any other form of interpreted syntax. The only parsed text inside a CDATA section is <code>]]></code>, and it terminates the section.</p>\n<p>Hence, it is not possible to escape <code>]]></code> within a CDATA section.</p>\n<p>EDIT3: The <a href=\"http://www.w3.org/TR/REC-xml/#sec-cdata-sect\" rel=\"noreferrer\">same section</a> also reads:</p>\n<blockquote>\n<p>2.7 CDATA Sections</p>\n<p>[Definition: CDATA sections may occur anywhere character data may occur; they are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string "<![CDATA[" and end with the string "]]>":]</p>\n</blockquote>\n<p>Then there may be a CDATA section anywhere character data may occur, including multiple adjacent CDATA sections inplace of a single CDATA section. That allows it to be possible to split the <code>]]></code> token and put the two parts of it in adjacent CDATA sections.</p>\n<p>ex:</p>\n<pre><code><![CDATA[Certain tokens like ]]> can be difficult and <invalid>]]> \n</code></pre>\n<p>should be written as</p>\n<pre><code><![CDATA[Certain tokens like ]]]]><![CDATA[> can be difficult and <valid>]]> \n</code></pre>\n"
},
{
"answer_id": 224007,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 3,
"selected": false,
"text": "<p>S. Lott's answer is right: you don't encode the end tag, you break it across multiple CDATA sections.</p>\n\n<p>How to run across this problem in the real world: using an XML editor to create an XML document that will be fed into a content-management system, try to write an article about CDATA sections. Your ordinary trick of embedding code samples in a CDATA section will fail you here. You can imagine how I learned this.</p>\n\n<p>But under most circumstances, you won't encounter this, and here's why: if you want to store (say) the text of an XML document as the content of an XML element, you'll probably use a DOM method, e.g.:</p>\n\n<pre><code>XmlElement elm = doc.CreateElement(\"foo\");\nelm.InnerText = \"<[CDATA[[Is this a problem?]]>\";\n</code></pre>\n\n<p>And the DOM quite reasonably escapes the < and the >, which means that you haven't inadvertently embedded a CDATA section in your document.</p>\n\n<p>Oh, and this is interesting:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\n\nXmlElement elm = doc.CreateElement(\"doc\");\ndoc.AppendChild(elm);\n\nstring data = \"<![[CDATA[This is an embedded CDATA section]]>\";\nXmlCDataSection cdata = doc.CreateCDataSection(data);\nelm.AppendChild(cdata);\n</code></pre>\n\n<p>This is probably an ideosyncrasy of the .NET DOM, but that doesn't throw an exception. The exception gets thrown here:</p>\n\n<pre><code>Console.Write(doc.OuterXml);\n</code></pre>\n\n<p>I'd guess that what's happening under the hood is that the XmlDocument is using an XmlWriter produce its output, and the XmlWriter checks for well-formedness as it writes.</p>\n"
},
{
"answer_id": 5491903,
"author": "Jason Pyeron",
"author_id": 58794,
"author_profile": "https://Stackoverflow.com/users/58794",
"pm_score": 4,
"selected": false,
"text": "<p>You do not escape the <code>]]></code> but you escape the <code>></code> after <code>]]</code> by inserting <code>]]><![CDATA[</code> before the <code>></code>, think of this just like a <code>\\</code> in C/Java/PHP/Perl string but only needed before a <code>></code> and after a <code>]]</code>.</p>\n\n<p>BTW, </p>\n\n<p>S.Lott's answer is the same as this, just worded differently.</p>\n"
},
{
"answer_id": 10943547,
"author": "Shawn Becker",
"author_id": 1443758,
"author_profile": "https://Stackoverflow.com/users/1443758",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another case in which <code>]]></code> needs to be escaped. Suppose we need to save a perfectly valid HTML document inside a CDATA block of an XML document and the HTML source happens to have it's own CDATA block. For example:</p>\n\n<pre><code><htmlSource><![CDATA[ \n ... html ...\n <script type=\"text/javascript\">\n /* <![CDATA[ */\n -- some working javascript --\n /* ]]> */\n </script>\n ... html ...\n]]></htmlSource>\n</code></pre>\n\n<p>the commented CDATA suffix needs to be changed to: </p>\n\n<pre><code> /* ]]]]><![CDATA[> *//\n</code></pre>\n\n<p>since an XML parser isn't going to know how to handle javascript comment blocks</p>\n"
},
{
"answer_id": 15544083,
"author": "user2194495",
"author_id": 2194495,
"author_profile": "https://Stackoverflow.com/users/2194495",
"pm_score": 1,
"selected": false,
"text": "<p>In PHP: <code>'<![CDATA['.implode(explode(']]>', $string), ']]]]><![CDATA[>').']]>'</code></p>\n"
},
{
"answer_id": 18405980,
"author": "Alain Tiemblo",
"author_id": 731138,
"author_profile": "https://Stackoverflow.com/users/731138",
"pm_score": 1,
"selected": false,
"text": "<p>A cleaner way in PHP:</p>\n\n<pre><code> function safeCData($string)\n {\n return '<![CDATA[' . str_replace(']]>', ']]]]><![CDATA[>', $string) . ']]>';\n }\n</code></pre>\n\n<p>Don't forget to use a multibyte-safe str_replace if required (non latin1 <code>$string</code>):</p>\n\n<pre><code> function mb_str_replace($search, $replace, $subject, &$count = 0)\n {\n if (!is_array($subject))\n {\n $searches = is_array($search) ? array_values($search) : array ($search);\n $replacements = is_array($replace) ? array_values($replace) : array ($replace);\n $replacements = array_pad($replacements, count($searches), '');\n foreach ($searches as $key => $search)\n {\n $parts = mb_split(preg_quote($search), $subject);\n $count += count($parts) - 1;\n $subject = implode($replacements[$key], $parts);\n }\n }\n else\n {\n foreach ($subject as $key => $value)\n {\n $subject[$key] = mb_str_replace($search, $replace, $value, $count);\n }\n }\n return $subject;\n }\n</code></pre>\n"
},
{
"answer_id": 36331725,
"author": "Thomas Grainger",
"author_id": 833093,
"author_profile": "https://Stackoverflow.com/users/833093",
"pm_score": 4,
"selected": false,
"text": "<p>simply replace <code>]]></code> with <code>]]]]><![CDATA[></code></p>\n"
},
{
"answer_id": 47445432,
"author": "Chad Kuehn",
"author_id": 1069995,
"author_profile": "https://Stackoverflow.com/users/1069995",
"pm_score": -1,
"selected": false,
"text": "<p>See this structure:</p>\n\n<pre><code><![CDATA[\n <![CDATA[\n <div>Hello World</div>\n ]]]]><![CDATA[>\n]]>\n</code></pre>\n\n<p>For the inner CDATA tag(s) you must close with <code>]]]]><![CDATA[></code> instead of <code>]]></code>. Simple as that.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24170/"
] |
I was wondering if there is any way to escape a CDATA end token (`]]>`) within a CDATA section in an xml document. Or, more generally, if there is some escape sequence for using within a CDATA (but if it exists, I guess it'd probably only make sense to escape begin or end tokens, anyway).
Basically, can you have a begin or end token embedded in a CDATA and tell the parser not to interpret it but to treat it as just another character sequence.
Probably, you should just refactor your xml structure or your code if you find yourself trying to do that, but even though I've been working with xml on a daily basis for the last 3 years or so and I have never had this problem, I was wondering if it was possible. Just out of curiosity.
Edit:
Other than using html encoding...
|
Clearly, this question is purely academic. Fortunately, it has a very definite answer.
You cannot escape a CDATA end sequence. Production rule 20 of the XML [specification](http://www.w3.org/TR/REC-xml/#sec-cdata-sect) is quite clear:
```
[20] CData ::= (Char* - (Char* ']]>' Char*))
```
EDIT: This product rule literally means "A CData section may contain anything you want BUT the sequence ']]>'. No exception.".
EDIT2: The [same section](http://www.w3.org/TR/REC-xml/#sec-cdata-sect) also reads:
>
> Within a CDATA section, only the CDEnd string is recognized as markup, so that left angle brackets and ampersands may occur in their literal form; they need not (and cannot) be escaped using "`<`" and "`&`". CDATA sections cannot nest.
>
>
>
In other words, it's not possible to use entity reference, markup or any other form of interpreted syntax. The only parsed text inside a CDATA section is `]]>`, and it terminates the section.
Hence, it is not possible to escape `]]>` within a CDATA section.
EDIT3: The [same section](http://www.w3.org/TR/REC-xml/#sec-cdata-sect) also reads:
>
> 2.7 CDATA Sections
>
>
> [Definition: CDATA sections may occur anywhere character data may occur; they are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string "<![CDATA[" and end with the string "]]>":]
>
>
>
Then there may be a CDATA section anywhere character data may occur, including multiple adjacent CDATA sections inplace of a single CDATA section. That allows it to be possible to split the `]]>` token and put the two parts of it in adjacent CDATA sections.
ex:
```
<![CDATA[Certain tokens like ]]> can be difficult and <invalid>]]>
```
should be written as
```
<![CDATA[Certain tokens like ]]]]><![CDATA[> can be difficult and <valid>]]>
```
|
223,666 |
<p>I am looking for the cleanest way. I am tempted to use delegates not sure though.</p>
|
[
{
"answer_id": 223722,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 0,
"selected": false,
"text": "<p>You might need to add more details. Delegates are a good option option, as is reflection if you only have the method name, not an actual pointer to it.</p>\n"
},
{
"answer_id": 223746,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 2,
"selected": true,
"text": "<p>Are you after something like this?</p>\n\n<pre><code>class A\n{\n public int Value;\n public int Add(int a) { return a + Value; }\n public int Mul(int a) { return a * Value; }\n}\n\nclass Program\n{\n static void Main( string[] args )\n {\n A a = new A();\n a.Value = 10;\n Func<int, int> f;\n f = a.Add;\n Console.WriteLine(\"Add: {0}\", f(5));\n f = a.Mul;\n Console.WriteLine(\"Mul: {0}\", f(5));\n }\n}\n</code></pre>\n\n<p>If you need the object it's called on to be unbound, like C++ member function pointers, I'm not sure that C# supports that. You can always use a lambda or delegate, though:</p>\n\n<pre><code>Func<A,int,int> f = delegate( A o, int i ) { return o.Add( i ); };\nConsole.WriteLine( \"Add: {0}\", f( a, 5 ) );\nf = ( A o, int i ) => o.Mul( i );\nConsole.WriteLine( \"Mul: {0}\", f( a, 5 ) );\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438/"
] |
I am looking for the cleanest way. I am tempted to use delegates not sure though.
|
Are you after something like this?
```
class A
{
public int Value;
public int Add(int a) { return a + Value; }
public int Mul(int a) { return a * Value; }
}
class Program
{
static void Main( string[] args )
{
A a = new A();
a.Value = 10;
Func<int, int> f;
f = a.Add;
Console.WriteLine("Add: {0}", f(5));
f = a.Mul;
Console.WriteLine("Mul: {0}", f(5));
}
}
```
If you need the object it's called on to be unbound, like C++ member function pointers, I'm not sure that C# supports that. You can always use a lambda or delegate, though:
```
Func<A,int,int> f = delegate( A o, int i ) { return o.Add( i ); };
Console.WriteLine( "Add: {0}", f( a, 5 ) );
f = ( A o, int i ) => o.Mul( i );
Console.WriteLine( "Mul: {0}", f( a, 5 ) );
```
|
223,673 |
<p>Alright, I am going to state up front that this question may be too involved (amount of detail not complexity) for this medium. But I figured this was the best place to start.</p>
<p>I am attempting to setup a proof of concept project and my BIND configuration is my first big hurdle. I want to setup 3 DNS servers on 3 physical boxes. <strong>None</strong> of these boxes needs to resolve public addresses, this is internal <strong>only</strong>. I have read through how to setup internal roots in the (mostly) excellent DNS & BIND 5th ed book. But my translation of their example is not functional. All IP's are RFC 1918 non-routable.</p>
<p>Box 1 will be authoritative for addresses on the <em>box1.bogus</em> domain, and Box 2 will be authoritative for addresses on the <em>box2.bogus</em> domain. Box 3 will act as both an internal root and the TLD server for the domain <em>bogus</em>.</p>
<p>Current unresolved issues:</p>
<ul>
<li><p>I have a hints file on box 1 and 2 that contains a single <strong>NS</strong> record to the NS definition of the root zone. Additionally there is an <strong>A</strong> record that translates the NS to the ip of the root. if I <code>dig .</code> from box 1 I get an <em>authority</em> Section with the NS name, not an <em>answer</em> and <em>additional</em> record section. Therefore I am unable to actually resolve the IP of the root server from box 1.</p></li>
<li><p>If I point my <code>/etc/resolv.conf</code> from box 1 directly at the root server and do a <code>dig box1.bogus</code> I get the ns.box1.bogus <em>answer</em> record and the translation in the <em>additional</em> section. However on the next iteration (when should get the A record) I get <code>dig: couldn't get address for ns.box1.bogus</code></p></li>
</ul>
<p>Obviously my configs are <strong>not</strong> correct. I don't see a way to attach them to this post, so if people want to walk through this step by step I will cut'n'paste them into a comment for this question. Otherwise I am open to taking this 'offline' with a "DNS guy" to figure out where I'm missing a '.' or have one too many!</p>
<p>I personally think the web could do with another internal root example that doesn't make use of the Movie-U example.</p>
<p>OK, if we are going to do this, then we should use a concrete example eh? I have 3 machines setup on a private VLAN for testing this. As a sanity check I paired down all my relevant configs, condensed when able, and redeployed 2 of the namesevers. I left out Scratchy for now. Same results as above. Here are the configs and initial dig outputs.</p>
<hr>
<h2>Bogus</h2>
<pre><code>Machine Name: Bogus (I just realized I should change this...)
Role: Internal Root and TLD Nameserver
IP: 10.0.0.1
BIND: 9.5.0-16.a6.fc8
</code></pre>
<h3>/etc/named.conf</h3>
<pre><code>// Controls who can make queries of this DNS server. Currently only the
// local test bed. When there is a standardized IP addr scheme, we can have
// those addr ranges enabled so that even if firewall rules get broken, the
// public internet can't query the internal DNS.
//
acl "authorized" {
localhost; // localhost
10.0.0.0/24; // Local Test
};
options {
listen-on port 53 {
127.0.0.1;
10.0.0.1;
};
listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
pid-file "/var/run/named/named.pid";
allow-query { any; };
recursion no;
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
//
// The fake root.
//
zone "." {
type master;
file "master/root";
allow-query { authorized; };
};
//
// The TLD for testing
//
zone "bogus" {
type master;
file "master/bogus";
allow-query { authorized; };
allow-transfer { authorized; };
};
</code></pre>
<h3> /var/named/master/root </h3>
<pre><code>$TTL 3600
. SOA ns.bogustld. hostmaster.internal.bogus. (
2008101601 ; serial
1H ; refresh
2H ; retry
14D ; expire
5M ) ; minimum
;
; Fake root zone servers defined.
;
. NS ns.bogustld.
ns.bogustld. A 10.0.0.1
;
; Testing TLD
;
bogus NS ns1.bogus.
ns1.bogus. A 10.0.0.1
</code></pre>
<h3>/var/named/master/bogus</h3>
<pre><code>$TTL 3600
@ SOA ns1.internal.bogus. hostmaster.internal.bogus. (
2008102201 ; serial date +seq
1H ; refresh
2H ; retry
14D ; expire
5M) ; min TTL
;
NS ns1.internal.bogus.
;
; Auth servers
;
ns1.internal.bogus. A 10.0.0.1
;
; Customer delegations each customer 2nd level domain has it's
; own zone file.
;
;Modified to be unique nameservers in the bogus domain
itchy NS ns1-itchy.bogus.
ns1-itchy.bogus. A 10.0.0.2
;
scratchy NS ns1-scratchy.bogus.
ns1-scratchy.bogus. A 10.0.0.3
</code></pre>
<h3>Output from dig .</h3>
<pre><code>; <<>> DiG 9.5.0-P2 <<>> .
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57175
;; flags: qr aa rd; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;. IN A
;; AUTHORITY SECTION:
. 300 IN SOA ns.bogustld. hostmaster.internal
.bogus. 2008101601 3600 7200 1209600 300
;; Query time: 1 msec
;; SERVER: 10.0.0.1#53(10.0.0.1)
;; WHEN: Tue Oct 21 12:23:59 2008
;; MSG SIZE rcvd: 88
</code></pre>
<h3>Output from dig +trace itchy.bogus </h3>
<pre><code>; <<>> DiG 9.5.0-P2 <<>> +trace itchy.bogus
;; global options: printcmd
. 3600 IN NS ns.bogustld.
;; Received 57 bytes from 10.0.0.1#53(10.0.0.1) in 1 ms
itchy.bogus. 3600 IN NS ns1-itchy.bogus.
;; Received 69 bytes from 10.0.0.1#53(ns.bogustld) in 0 ms
itchy.bogus. 3600 IN A 10.0.0.2
itchy.bogus. 3600 IN NS ns1.itchy.bogus.
;; Received 79 bytes from 10.0.0.2#53(ns1-itchy.bogus) in 0 ms
</code></pre>
<hr>
<h2>Itchy</h2>
<pre><code>Machine Name: Itchy
Role: SLD Nameserver (supposed to be owner of itchy.bogus)
IP: 10.0.0.2
BIND: 9.5.0-16.a6.fc8
</code></pre>
<h3>/etc/named.conf</h3>
<pre><code>// Controls who can make queries of this DNS server. Currently only the
// local test bed. When there is a standardized IP addr scheme, we can have
// those addr ranges enabled so that even if firewall rules get broken, the
// public internet can't query the internal DNS.
//
acl "authorized" {
localhost; // localhost
10.0.0.0/24; // LAN Test
};
options {
listen-on port 53 {
127.0.0.1;
10.0.0.2;
};
listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
pid-file "/var/run/named/named.pid";
allow-query { any; };
recursion no;
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
zone "." IN {
type hint;
file "master/root.hint";
};
zone "itchy.bogus" {
type master;
file "master/itchy.bogus";
allow-query { authorized; };
allow-transfer { authorized; };
};
</code></pre>
<h3>/var/named/master/itchy.bogus</h3>
<pre><code>$TTL 3600
@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (
2008102202 ; serial
1H ; refresh
2H ; retry
14D ; expire
5M ) ; minimum
;
A 10.0.0.2
NS ns1.itchy.bogus.
ns1 A 10.0.0.2
</code></pre>
<h3>/var/named/master/root.hint</h3>
<pre><code>. 3600000 NS ns.bogustld.
ns.bogustld. 3600000 A 10.0.0.1
; End of File
</code></pre>
<h3>/etc/resolv.conf</h3>
<pre><code>nameserver 10.0.0.2
</code></pre>
<h3> Output from dig .</h3>
<pre><code>; <<>> DiG 9.5.0-P2 <<>> .
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 31291
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;. IN A
;; AUTHORITY SECTION:
. 3600000 IN NS ns.bogustld.
;; Query time: 0 msec
;; SERVER: 10.0.0.2#53(10.0.0.2)
;; WHEN: Tue Oct 21 17:09:53 2008
;; MSG SIZE rcvd: 41
</code></pre>
<h3>Output from dig + trace itchy.bogus </h3>
<pre><code>; <<>> DiG 9.5.0-P2 <<>> +trace itchy.bogus
;; global options: printcmd
. 3600000 IN NS ns.bogustld.
;; Received 41 bytes from 10.0.0.2#53(10.0.0.2) in 0 ms
dig: couldn't get address for 'ns.bogustld': failure
</code></pre>
|
[
{
"answer_id": 223749,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that you've checked all of the obvious things - such as ensuring that the main bind configuration file is what you think it is. Firstly check that the that you think named is using are the right ones - sometimes it's easy to edit a file that's in the wrong directory and wonder why changes aren't noticed.</p>\n\n<p>Also have you used named-checkconf and named-checkzone</p>\n\n<p>It is hard enough to debug bind, but without seeing the config files it is almost impossible, so please add them to the original post.</p>\n\n<p>(I've added this as a comment to the question - I've posted as an answer because the OP is new here). </p>\n"
},
{
"answer_id": 223755,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>Each of the 3 servers needs to have the same hints file. It should have an NS record for \".\" with the name of the root server and an A record for that name.</p>\n\n<p>The root server should have the \".\" zone set up. The \".\" zone needs to have \"bogus\" with an ns record for itself. It then should have A records for box1.bogus going to box1 and box2.bogus going off to box2.</p>\n\n<p>Note that you should not use box1 and box2 both as the hostnames and the names of the 2nd level domains. Let's say that the domains are zone1.bogus and zone2.bogus instead.</p>\n\n<p>So box1 and box2 should be in the bogus zone, complete with A records. zone1 and zone2 should be NS records pointing to box1 and box2.</p>\n\n<p>Clear as mud? :)</p>\n"
},
{
"answer_id": 226685,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>Ok. I see you've aded your configs. Excellent.</p>\n\n<p>I would change the root zone thusly:</p>\n\n<pre><code>;Should this be ns1.itchy.bogus or ns1.itchy.internal.bogus??\nitchy NS ns1-itchy.bogus.\nns1-itchy.bogus. A 10.0.0.2\n;\nscratchy NS ns1-scratchy.bogus.\nns1-scratchy.bogus. A 10.0.0.3\n</code></pre>\n\n<p>I think the issue is that you're delegating itchy.bogus, so you can't put names inside there.</p>\n\n<p>The \"com\" name servers, I believe, use hints so that they can serve A records for name servers for delegated zones, but in your case, it's just cleaner to insure that any given zone being served only has delegations for sub-zones AND hosts within the current zone.</p>\n"
},
{
"answer_id": 227096,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 2,
"selected": true,
"text": "<p>By using @, you're defining itchy.bogus. You can't then redefine it further down in the zone with the itchy.bogus line.</p>\n\n<p>Try this:</p>\n\n<pre><code>@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (\n 2008102201 ; serial\n 1H ; refresh\n 2H ; retry\n 14D ; expire\n 5M ) ; minimum\n;\n NS ns1\n A 10.0.0.2\n ns1 A 10.0.0.2\n</code></pre>\n\n<p>Since this is the zone file for itchy.bogus, that should do the right thing.</p>\n"
},
{
"answer_id": 227254,
"author": "JT.",
"author_id": 30145,
"author_profile": "https://Stackoverflow.com/users/30145",
"pm_score": 1,
"selected": false,
"text": "<p>Now my delegation issues look resolved, but I am still having trouble with the root lookup (which I thought would be soooo easy.)</p>\n\n<p>I think the problem stems from the fact that when I <code>dig</code> from the itchy machine I get an authority record instead of an answer record. I'm just not sure what I did (or didn't) to cause that.</p>\n\n<p>If you \"dig [no args]\" from a machine using the typical hint file for the internet you get a block of answers for the root nameservers and the translation in the additional section.</p>\n\n<p>if I do that from the bogus machine (root and TLD nameserver) I get</p>\n\n<pre><code>;; QUESTION SECTION:\n;. IN NS\n\n;; ANSWER SECTION:\n. 3600 IN NS ns.bogustld.\n\n;; ADDITIONAL SECTION:\nns.bogustld. 3600 IN A 10.0.0.1\n</code></pre>\n\n<p>If I do that from the itchy machine I get</p>\n\n<pre><code>;; QUESTION SECTION:\n;. IN NS\n\n;; AUTHORITY SECTION:\n. 3600000 IN NS ns.bogustld.\n\n;; Query time: 0 msec\n</code></pre>\n\n<p>It get's more interesting if you try <code>dig +trace .</code></p>\n\n<h3>Internet box</h3>\n\n<pre><code>; <<>> DiG 9.5.0a6 <<>> +trace .\n;; global options: printcmd\n. 3005 IN NS C.ROOT-SERVERS.NET.\n. 3005 IN NS D.ROOT-SERVERS.NET.\n. 3005 IN NS E.ROOT-SERVERS.NET.\n. 3005 IN NS F.ROOT-SERVERS.NET.\n. 3005 IN NS G.ROOT-SERVERS.NET.\n. 3005 IN NS H.ROOT-SERVERS.NET.\n. 3005 IN NS I.ROOT-SERVERS.NET.\n. 3005 IN NS J.ROOT-SERVERS.NET.\n. 3005 IN NS K.ROOT-SERVERS.NET.\n. 3005 IN NS L.ROOT-SERVERS.NET.\n. 3005 IN NS M.ROOT-SERVERS.NET.\n. 3005 IN NS A.ROOT-SERVERS.NET.\n. 3005 IN NS B.ROOT-SERVERS.NET.\n;; Received 500 bytes from 64.105.172.26#53(64.105.172.26) in 19 ms\n\n. 86400 IN SOA a.root-servers.net. nstld.verisi\ngn-grs.com. 2008102201 1800 900 604800 86400\n;; Received 92 bytes from 128.63.2.53#53(H.ROOT-SERVERS.NET) in 84 ms\n</code></pre>\n\n<h3>My internal root box (Bogus)</h3>\n\n<pre><code>; <<>> DiG 9.5.0-P2 <<>> +trace .\n;; global options: printcmd\n. 3600 IN NS ns.bogustld.\n;; Received 57 bytes from 10.0.0.1#53(10.0.0.1) in 1 ms\n\n. 3600 IN NS ns.bogustld.\n;; Received 72 bytes from 10.0.0.1#53(ns.bogustld) in 0 ms\n</code></pre>\n\n<h3>Itchy</h3>\n\n<pre><code>; <<>> DiG 9.5.0-P2 <<>> +trace .\n;; global options: printcmd\n. 3600000 IN NS ns.bogustld.\n;; Received 41 bytes from 10.0.0.2#53(10.0.0.2) in 0 ms\n\ndig: couldn't get address for 'ns.bogustld': failure\n</code></pre>\n\n<p>Why does my internet facing machine find a SOA, but none of my internal machines?</p>\n"
},
{
"answer_id": 227670,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>Like the highlander, there can be only one.</p>\n\n<p>By using the normal internet root hints, you're more or less precluded from using your own internal root, because none of the real Internet root servers know about \"bogus\".</p>\n\n<p>Your only choice would be to mirror the root \".\" zone from within your \".\", but then add \"bogus\" to it. You'd do this by periodically dumping the root zone and running it through some processing to add your custom zone to it.</p>\n\n<p>Some of the alternate DNS root providers do this, but they supply root hints for their \"customers\" to use that do not reference the \"real\" root servers at all.</p>\n\n<p>... Am I understanding the question correctly? Not sure.</p>\n"
},
{
"answer_id": 227916,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>dig . @10.0.0.1 (bogus) should return authoritative records for '.', since it is indeed authoritative for the zone.</p>\n\n<p>dig . @10.0.0.2 (itchy) should not return authoritative records for '.', since it isn't. It <em>may</em> return an authoritative record the first time you query for a name in the root zone, because it has to recurse and fetch an authoritative record from the authoritative server. But if you do it a 2nd time, you'll get a cached result and the 'aa' flag will be clear.</p>\n"
},
{
"answer_id": 234716,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>Your name server won't use the hint to give answers to dig. That is, it won't give the hint back to dig as an answer. It will insist on actually querying 10.0.0.1 for bogustld. I don't think you have bogustld set up as a zone, just bogus.</p>\n\n<p>You should probably change ns.bogustld to ns.bogus. Give 10.0.0.1 the name ns.bogus.</p>\n\n<p>Alternatively, you could add an NS and an SOA record in . for bogustld.</p>\n\n<p>If you dig ns1.bogus. @10.0.0.2, that works, right (assuming the config above is still in place)?</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30145/"
] |
Alright, I am going to state up front that this question may be too involved (amount of detail not complexity) for this medium. But I figured this was the best place to start.
I am attempting to setup a proof of concept project and my BIND configuration is my first big hurdle. I want to setup 3 DNS servers on 3 physical boxes. **None** of these boxes needs to resolve public addresses, this is internal **only**. I have read through how to setup internal roots in the (mostly) excellent DNS & BIND 5th ed book. But my translation of their example is not functional. All IP's are RFC 1918 non-routable.
Box 1 will be authoritative for addresses on the *box1.bogus* domain, and Box 2 will be authoritative for addresses on the *box2.bogus* domain. Box 3 will act as both an internal root and the TLD server for the domain *bogus*.
Current unresolved issues:
* I have a hints file on box 1 and 2 that contains a single **NS** record to the NS definition of the root zone. Additionally there is an **A** record that translates the NS to the ip of the root. if I `dig .` from box 1 I get an *authority* Section with the NS name, not an *answer* and *additional* record section. Therefore I am unable to actually resolve the IP of the root server from box 1.
* If I point my `/etc/resolv.conf` from box 1 directly at the root server and do a `dig box1.bogus` I get the ns.box1.bogus *answer* record and the translation in the *additional* section. However on the next iteration (when should get the A record) I get `dig: couldn't get address for ns.box1.bogus`
Obviously my configs are **not** correct. I don't see a way to attach them to this post, so if people want to walk through this step by step I will cut'n'paste them into a comment for this question. Otherwise I am open to taking this 'offline' with a "DNS guy" to figure out where I'm missing a '.' or have one too many!
I personally think the web could do with another internal root example that doesn't make use of the Movie-U example.
OK, if we are going to do this, then we should use a concrete example eh? I have 3 machines setup on a private VLAN for testing this. As a sanity check I paired down all my relevant configs, condensed when able, and redeployed 2 of the namesevers. I left out Scratchy for now. Same results as above. Here are the configs and initial dig outputs.
---
Bogus
-----
```
Machine Name: Bogus (I just realized I should change this...)
Role: Internal Root and TLD Nameserver
IP: 10.0.0.1
BIND: 9.5.0-16.a6.fc8
```
### /etc/named.conf
```
// Controls who can make queries of this DNS server. Currently only the
// local test bed. When there is a standardized IP addr scheme, we can have
// those addr ranges enabled so that even if firewall rules get broken, the
// public internet can't query the internal DNS.
//
acl "authorized" {
localhost; // localhost
10.0.0.0/24; // Local Test
};
options {
listen-on port 53 {
127.0.0.1;
10.0.0.1;
};
listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
pid-file "/var/run/named/named.pid";
allow-query { any; };
recursion no;
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
//
// The fake root.
//
zone "." {
type master;
file "master/root";
allow-query { authorized; };
};
//
// The TLD for testing
//
zone "bogus" {
type master;
file "master/bogus";
allow-query { authorized; };
allow-transfer { authorized; };
};
```
### /var/named/master/root
```
$TTL 3600
. SOA ns.bogustld. hostmaster.internal.bogus. (
2008101601 ; serial
1H ; refresh
2H ; retry
14D ; expire
5M ) ; minimum
;
; Fake root zone servers defined.
;
. NS ns.bogustld.
ns.bogustld. A 10.0.0.1
;
; Testing TLD
;
bogus NS ns1.bogus.
ns1.bogus. A 10.0.0.1
```
### /var/named/master/bogus
```
$TTL 3600
@ SOA ns1.internal.bogus. hostmaster.internal.bogus. (
2008102201 ; serial date +seq
1H ; refresh
2H ; retry
14D ; expire
5M) ; min TTL
;
NS ns1.internal.bogus.
;
; Auth servers
;
ns1.internal.bogus. A 10.0.0.1
;
; Customer delegations each customer 2nd level domain has it's
; own zone file.
;
;Modified to be unique nameservers in the bogus domain
itchy NS ns1-itchy.bogus.
ns1-itchy.bogus. A 10.0.0.2
;
scratchy NS ns1-scratchy.bogus.
ns1-scratchy.bogus. A 10.0.0.3
```
### Output from dig .
```
; <<>> DiG 9.5.0-P2 <<>> .
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57175
;; flags: qr aa rd; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;. IN A
;; AUTHORITY SECTION:
. 300 IN SOA ns.bogustld. hostmaster.internal
.bogus. 2008101601 3600 7200 1209600 300
;; Query time: 1 msec
;; SERVER: 10.0.0.1#53(10.0.0.1)
;; WHEN: Tue Oct 21 12:23:59 2008
;; MSG SIZE rcvd: 88
```
### Output from dig +trace itchy.bogus
```
; <<>> DiG 9.5.0-P2 <<>> +trace itchy.bogus
;; global options: printcmd
. 3600 IN NS ns.bogustld.
;; Received 57 bytes from 10.0.0.1#53(10.0.0.1) in 1 ms
itchy.bogus. 3600 IN NS ns1-itchy.bogus.
;; Received 69 bytes from 10.0.0.1#53(ns.bogustld) in 0 ms
itchy.bogus. 3600 IN A 10.0.0.2
itchy.bogus. 3600 IN NS ns1.itchy.bogus.
;; Received 79 bytes from 10.0.0.2#53(ns1-itchy.bogus) in 0 ms
```
---
Itchy
-----
```
Machine Name: Itchy
Role: SLD Nameserver (supposed to be owner of itchy.bogus)
IP: 10.0.0.2
BIND: 9.5.0-16.a6.fc8
```
### /etc/named.conf
```
// Controls who can make queries of this DNS server. Currently only the
// local test bed. When there is a standardized IP addr scheme, we can have
// those addr ranges enabled so that even if firewall rules get broken, the
// public internet can't query the internal DNS.
//
acl "authorized" {
localhost; // localhost
10.0.0.0/24; // LAN Test
};
options {
listen-on port 53 {
127.0.0.1;
10.0.0.2;
};
listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
pid-file "/var/run/named/named.pid";
allow-query { any; };
recursion no;
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
zone "." IN {
type hint;
file "master/root.hint";
};
zone "itchy.bogus" {
type master;
file "master/itchy.bogus";
allow-query { authorized; };
allow-transfer { authorized; };
};
```
### /var/named/master/itchy.bogus
```
$TTL 3600
@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (
2008102202 ; serial
1H ; refresh
2H ; retry
14D ; expire
5M ) ; minimum
;
A 10.0.0.2
NS ns1.itchy.bogus.
ns1 A 10.0.0.2
```
### /var/named/master/root.hint
```
. 3600000 NS ns.bogustld.
ns.bogustld. 3600000 A 10.0.0.1
; End of File
```
### /etc/resolv.conf
```
nameserver 10.0.0.2
```
### Output from dig .
```
; <<>> DiG 9.5.0-P2 <<>> .
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 31291
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;. IN A
;; AUTHORITY SECTION:
. 3600000 IN NS ns.bogustld.
;; Query time: 0 msec
;; SERVER: 10.0.0.2#53(10.0.0.2)
;; WHEN: Tue Oct 21 17:09:53 2008
;; MSG SIZE rcvd: 41
```
### Output from dig + trace itchy.bogus
```
; <<>> DiG 9.5.0-P2 <<>> +trace itchy.bogus
;; global options: printcmd
. 3600000 IN NS ns.bogustld.
;; Received 41 bytes from 10.0.0.2#53(10.0.0.2) in 0 ms
dig: couldn't get address for 'ns.bogustld': failure
```
|
By using @, you're defining itchy.bogus. You can't then redefine it further down in the zone with the itchy.bogus line.
Try this:
```
@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (
2008102201 ; serial
1H ; refresh
2H ; retry
14D ; expire
5M ) ; minimum
;
NS ns1
A 10.0.0.2
ns1 A 10.0.0.2
```
Since this is the zone file for itchy.bogus, that should do the right thing.
|
223,677 |
<p>I have a regexp I'm using with sed, but now I need to make it work in PHP also. I can't use system calls as they are disabled.</p>
<pre>
$ cat uglynumber.txt:
Ticket number : 303905694, FOO:BAR:BAR: Some text
Case ID:123,456,789:Foobar - Some other text
303867970;[FOOBAR] Some text goes here
Case Ref: 303658850 - Some random text here - host.tld #78854w
</pre>
<pre>
$ cat uglynumbers.txt | sed "s/[, ]//g;s/.*\([0-9]\{9\}\).*/\1/g"
303905694
123456789
303867970
303658850
</pre>
<p>So, how to do the same with PHP?</p>
<p>I found one example like this, but I can't inject that regexp into that.</p>
<pre>
if (preg_match("/.../", $line, $matches)) {
echo "Match was found";
echo $matches[0];
}
</pre>
|
[
{
"answer_id": 223749,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that you've checked all of the obvious things - such as ensuring that the main bind configuration file is what you think it is. Firstly check that the that you think named is using are the right ones - sometimes it's easy to edit a file that's in the wrong directory and wonder why changes aren't noticed.</p>\n\n<p>Also have you used named-checkconf and named-checkzone</p>\n\n<p>It is hard enough to debug bind, but without seeing the config files it is almost impossible, so please add them to the original post.</p>\n\n<p>(I've added this as a comment to the question - I've posted as an answer because the OP is new here). </p>\n"
},
{
"answer_id": 223755,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>Each of the 3 servers needs to have the same hints file. It should have an NS record for \".\" with the name of the root server and an A record for that name.</p>\n\n<p>The root server should have the \".\" zone set up. The \".\" zone needs to have \"bogus\" with an ns record for itself. It then should have A records for box1.bogus going to box1 and box2.bogus going off to box2.</p>\n\n<p>Note that you should not use box1 and box2 both as the hostnames and the names of the 2nd level domains. Let's say that the domains are zone1.bogus and zone2.bogus instead.</p>\n\n<p>So box1 and box2 should be in the bogus zone, complete with A records. zone1 and zone2 should be NS records pointing to box1 and box2.</p>\n\n<p>Clear as mud? :)</p>\n"
},
{
"answer_id": 226685,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>Ok. I see you've aded your configs. Excellent.</p>\n\n<p>I would change the root zone thusly:</p>\n\n<pre><code>;Should this be ns1.itchy.bogus or ns1.itchy.internal.bogus??\nitchy NS ns1-itchy.bogus.\nns1-itchy.bogus. A 10.0.0.2\n;\nscratchy NS ns1-scratchy.bogus.\nns1-scratchy.bogus. A 10.0.0.3\n</code></pre>\n\n<p>I think the issue is that you're delegating itchy.bogus, so you can't put names inside there.</p>\n\n<p>The \"com\" name servers, I believe, use hints so that they can serve A records for name servers for delegated zones, but in your case, it's just cleaner to insure that any given zone being served only has delegations for sub-zones AND hosts within the current zone.</p>\n"
},
{
"answer_id": 227096,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 2,
"selected": true,
"text": "<p>By using @, you're defining itchy.bogus. You can't then redefine it further down in the zone with the itchy.bogus line.</p>\n\n<p>Try this:</p>\n\n<pre><code>@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (\n 2008102201 ; serial\n 1H ; refresh\n 2H ; retry\n 14D ; expire\n 5M ) ; minimum\n;\n NS ns1\n A 10.0.0.2\n ns1 A 10.0.0.2\n</code></pre>\n\n<p>Since this is the zone file for itchy.bogus, that should do the right thing.</p>\n"
},
{
"answer_id": 227254,
"author": "JT.",
"author_id": 30145,
"author_profile": "https://Stackoverflow.com/users/30145",
"pm_score": 1,
"selected": false,
"text": "<p>Now my delegation issues look resolved, but I am still having trouble with the root lookup (which I thought would be soooo easy.)</p>\n\n<p>I think the problem stems from the fact that when I <code>dig</code> from the itchy machine I get an authority record instead of an answer record. I'm just not sure what I did (or didn't) to cause that.</p>\n\n<p>If you \"dig [no args]\" from a machine using the typical hint file for the internet you get a block of answers for the root nameservers and the translation in the additional section.</p>\n\n<p>if I do that from the bogus machine (root and TLD nameserver) I get</p>\n\n<pre><code>;; QUESTION SECTION:\n;. IN NS\n\n;; ANSWER SECTION:\n. 3600 IN NS ns.bogustld.\n\n;; ADDITIONAL SECTION:\nns.bogustld. 3600 IN A 10.0.0.1\n</code></pre>\n\n<p>If I do that from the itchy machine I get</p>\n\n<pre><code>;; QUESTION SECTION:\n;. IN NS\n\n;; AUTHORITY SECTION:\n. 3600000 IN NS ns.bogustld.\n\n;; Query time: 0 msec\n</code></pre>\n\n<p>It get's more interesting if you try <code>dig +trace .</code></p>\n\n<h3>Internet box</h3>\n\n<pre><code>; <<>> DiG 9.5.0a6 <<>> +trace .\n;; global options: printcmd\n. 3005 IN NS C.ROOT-SERVERS.NET.\n. 3005 IN NS D.ROOT-SERVERS.NET.\n. 3005 IN NS E.ROOT-SERVERS.NET.\n. 3005 IN NS F.ROOT-SERVERS.NET.\n. 3005 IN NS G.ROOT-SERVERS.NET.\n. 3005 IN NS H.ROOT-SERVERS.NET.\n. 3005 IN NS I.ROOT-SERVERS.NET.\n. 3005 IN NS J.ROOT-SERVERS.NET.\n. 3005 IN NS K.ROOT-SERVERS.NET.\n. 3005 IN NS L.ROOT-SERVERS.NET.\n. 3005 IN NS M.ROOT-SERVERS.NET.\n. 3005 IN NS A.ROOT-SERVERS.NET.\n. 3005 IN NS B.ROOT-SERVERS.NET.\n;; Received 500 bytes from 64.105.172.26#53(64.105.172.26) in 19 ms\n\n. 86400 IN SOA a.root-servers.net. nstld.verisi\ngn-grs.com. 2008102201 1800 900 604800 86400\n;; Received 92 bytes from 128.63.2.53#53(H.ROOT-SERVERS.NET) in 84 ms\n</code></pre>\n\n<h3>My internal root box (Bogus)</h3>\n\n<pre><code>; <<>> DiG 9.5.0-P2 <<>> +trace .\n;; global options: printcmd\n. 3600 IN NS ns.bogustld.\n;; Received 57 bytes from 10.0.0.1#53(10.0.0.1) in 1 ms\n\n. 3600 IN NS ns.bogustld.\n;; Received 72 bytes from 10.0.0.1#53(ns.bogustld) in 0 ms\n</code></pre>\n\n<h3>Itchy</h3>\n\n<pre><code>; <<>> DiG 9.5.0-P2 <<>> +trace .\n;; global options: printcmd\n. 3600000 IN NS ns.bogustld.\n;; Received 41 bytes from 10.0.0.2#53(10.0.0.2) in 0 ms\n\ndig: couldn't get address for 'ns.bogustld': failure\n</code></pre>\n\n<p>Why does my internet facing machine find a SOA, but none of my internal machines?</p>\n"
},
{
"answer_id": 227670,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>Like the highlander, there can be only one.</p>\n\n<p>By using the normal internet root hints, you're more or less precluded from using your own internal root, because none of the real Internet root servers know about \"bogus\".</p>\n\n<p>Your only choice would be to mirror the root \".\" zone from within your \".\", but then add \"bogus\" to it. You'd do this by periodically dumping the root zone and running it through some processing to add your custom zone to it.</p>\n\n<p>Some of the alternate DNS root providers do this, but they supply root hints for their \"customers\" to use that do not reference the \"real\" root servers at all.</p>\n\n<p>... Am I understanding the question correctly? Not sure.</p>\n"
},
{
"answer_id": 227916,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>dig . @10.0.0.1 (bogus) should return authoritative records for '.', since it is indeed authoritative for the zone.</p>\n\n<p>dig . @10.0.0.2 (itchy) should not return authoritative records for '.', since it isn't. It <em>may</em> return an authoritative record the first time you query for a name in the root zone, because it has to recurse and fetch an authoritative record from the authoritative server. But if you do it a 2nd time, you'll get a cached result and the 'aa' flag will be clear.</p>\n"
},
{
"answer_id": 234716,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 0,
"selected": false,
"text": "<p>Your name server won't use the hint to give answers to dig. That is, it won't give the hint back to dig as an answer. It will insist on actually querying 10.0.0.1 for bogustld. I don't think you have bogustld set up as a zone, just bogus.</p>\n\n<p>You should probably change ns.bogustld to ns.bogus. Give 10.0.0.1 the name ns.bogus.</p>\n\n<p>Alternatively, you could add an NS and an SOA record in . for bogustld.</p>\n\n<p>If you dig ns1.bogus. @10.0.0.2, that works, right (assuming the config above is still in place)?</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30141/"
] |
I have a regexp I'm using with sed, but now I need to make it work in PHP also. I can't use system calls as they are disabled.
```
$ cat uglynumber.txt:
Ticket number : 303905694, FOO:BAR:BAR: Some text
Case ID:123,456,789:Foobar - Some other text
303867970;[FOOBAR] Some text goes here
Case Ref: 303658850 - Some random text here - host.tld #78854w
```
```
$ cat uglynumbers.txt | sed "s/[, ]//g;s/.*\([0-9]\{9\}\).*/\1/g"
303905694
123456789
303867970
303658850
```
So, how to do the same with PHP?
I found one example like this, but I can't inject that regexp into that.
```
if (preg_match("/.../", $line, $matches)) {
echo "Match was found";
echo $matches[0];
}
```
|
By using @, you're defining itchy.bogus. You can't then redefine it further down in the zone with the itchy.bogus line.
Try this:
```
@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (
2008102201 ; serial
1H ; refresh
2H ; retry
14D ; expire
5M ) ; minimum
;
NS ns1
A 10.0.0.2
ns1 A 10.0.0.2
```
Since this is the zone file for itchy.bogus, that should do the right thing.
|
223,678 |
<p>Given the hash of a blob, is there a way to get a list of commits that have this blob in their tree?</p>
|
[
{
"answer_id": 223870,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>I thought this would be a generally useful thing to have, so I wrote up a little perl script to do it:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>#!/usr/bin/perl -w\n\nuse strict;\n\nmy @commits;\nmy %trees;\nmy $blob;\n\nsub blob_in_tree {\n my $tree = $_[0];\n if (defined $trees{$tree}) {\n return $trees{$tree};\n }\n my $r = 0;\n open(my $f, \"git cat-file -p $tree|\") or die $!;\n while (<$f>) {\n if (/^\\d+ blob (\\w+)/ && $1 eq $blob) {\n $r = 1;\n } elsif (/^\\d+ tree (\\w+)/) {\n $r = blob_in_tree($1);\n }\n last if $r;\n }\n close($f);\n $trees{$tree} = $r;\n return $r;\n}\n\nsub handle_commit {\n my $commit = $_[0];\n open(my $f, \"git cat-file commit $commit|\") or die $!;\n my $tree = <$f>;\n die unless $tree =~ /^tree (\\w+)$/;\n if (blob_in_tree($1)) {\n print \"$commit\\n\";\n }\n while (1) {\n my $parent = <$f>;\n last unless $parent =~ /^parent (\\w+)$/;\n push @commits, $1;\n }\n close($f);\n}\n\nif (!@ARGV) {\n print STDERR \"Usage: git-find-blob blob [head ...]\\n\";\n exit 1;\n}\n\n$blob = $ARGV[0];\nif (@ARGV > 1) {\n foreach (@ARGV) {\n handle_commit($_);\n }\n} else {\n handle_commit(\"HEAD\");\n}\nwhile (@commits) {\n handle_commit(pop @commits);\n}\n</code></pre>\n\n<p>I'll put this up on github when I get home this evening.</p>\n\n<p>Update: It looks like somebody <a href=\"http://github.com/jwiegley/git-scripts/tree/master/git-find-blob\" rel=\"nofollow noreferrer\">already did this</a>. That one uses the same general idea but the details are different and the implementation is <em>much</em> shorter. I don't know which would be faster but performance is probably not a concern here!</p>\n\n<p>Update 2: For what it's worth, my implementation is orders of magnitude faster, especially for a large repository. That <code>git ls-tree -r</code> really hurts.</p>\n\n<p>Update 3: I should note that my performance comments above apply to the implementation I linked above in the first Update. <a href=\"https://stackoverflow.com/questions/223678/git-which-commit-has-this-blob#223890\">Aristotle's implementation</a> performs comparably to mine. More details in the comments for those who are curious.</p>\n"
},
{
"answer_id": 223890,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 8,
"selected": true,
"text": "<p>Both of the following scripts take the blob’s SHA1 as the first argument, and after it, optionally, any arguments that <a href=\"http://git-scm.com/docs/git-log\" rel=\"noreferrer\"><code>git log</code></a> will understand. E.g. <code>--all</code> to search in all branches instead of just the current one, or <code>-g</code> to search in the reflog, or whatever else you fancy.</p>\n<p>Here it is as a shell script – short and sweet, but slow:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>#!/bin/sh\nobj_name="$1"\nshift\ngit log "$@" --pretty=tformat:'%T %h %s' \\\n| while read tree commit subject ; do\n if git ls-tree -r $tree | grep -q "$obj_name" ; then\n echo $commit "$subject"\n fi\ndone\n</code></pre>\n<p>And an optimised version in Perl, still quite short but much faster:</p>\n<pre class=\"lang-perl prettyprint-override\"><code>#!/usr/bin/perl\nuse 5.008;\nuse strict;\nuse Memoize;\n\nmy $obj_name;\n\nsub check_tree {\n my ( $tree ) = @_;\n my @subtree;\n\n {\n open my $ls_tree, '-|', git => 'ls-tree' => $tree\n or die "Couldn't open pipe to git-ls-tree: $!\\n";\n\n while ( <$ls_tree> ) {\n /\\A[0-7]{6} (\\S+) (\\S+)/\n or die "unexpected git-ls-tree output";\n return 1 if $2 eq $obj_name;\n push @subtree, $2 if $1 eq 'tree';\n }\n }\n\n check_tree( $_ ) && return 1 for @subtree;\n\n return;\n}\n\nmemoize 'check_tree';\n\ndie "usage: git-find-blob <blob> [<git-log arguments ...>]\\n"\n if not @ARGV;\n\nmy $obj_short = shift @ARGV;\n$obj_name = do {\n local $ENV{'OBJ_NAME'} = $obj_short;\n `git rev-parse --verify \\$OBJ_NAME`;\n} or die "Couldn't parse $obj_short: $!\\n";\nchomp $obj_name;\n\nopen my $log, '-|', git => log => @ARGV, '--pretty=format:%T %h %s'\n or die "Couldn't open pipe to git-log: $!\\n";\n\nwhile ( <$log> ) {\n chomp;\n my ( $tree, $commit, $subject ) = split " ", $_, 3;\n print "$commit $subject\\n" if check_tree( $tree );\n}\n</code></pre>\n"
},
{
"answer_id": 9748398,
"author": "Mario",
"author_id": 472,
"author_profile": "https://Stackoverflow.com/users/472",
"pm_score": 3,
"selected": false,
"text": "<p>While the original question does not ask for it, I think it is useful to also check the staging area to see if a blob is referenced. I modified the original bash script to do this and found what was referencing a corrupt blob in my repository:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>#!/bin/sh\nobj_name=\"$1\"\nshift\ngit ls-files --stage \\\n| if grep -q \"$obj_name\"; then\n echo Found in staging area. Run git ls-files --stage to see.\nfi\n\ngit log \"$@\" --pretty=format:'%T %h %s' \\\n| while read tree commit subject ; do\n if git ls-tree -r $tree | grep -q \"$obj_name\" ; then\n echo $commit \"$subject\"\n fi\ndone\n</code></pre>\n"
},
{
"answer_id": 12737458,
"author": "cmyers",
"author_id": 156785,
"author_profile": "https://Stackoverflow.com/users/156785",
"pm_score": 2,
"selected": false,
"text": "<p>So... I needed to find all files over a given limit in a repo over 8GB in size, with over 108,000 revisions. I adapted Aristotle's perl script along with a ruby script I wrote to reach this complete solution.</p>\n\n<p>First, <code>git gc</code> - do this to ensure all objects are in packfiles - we don't scan objects not in pack files.</p>\n\n<p>Next Run this script to locate all blobs over CUTOFF_SIZE bytes. Capture output to a file like \"large-blobs.log\"</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>#!/usr/bin/env ruby\n\nrequire 'log4r'\n\n# The output of git verify-pack -v is:\n# SHA1 type size size-in-packfile offset-in-packfile depth base-SHA1\n#\n#\nGIT_PACKS_RELATIVE_PATH=File.join('.git', 'objects', 'pack', '*.pack')\n\n# 10MB cutoff\nCUTOFF_SIZE=1024*1024*10\n#CUTOFF_SIZE=1024\n\nbegin\n\n include Log4r\n log = Logger.new 'git-find-large-objects'\n log.level = INFO\n log.outputters = Outputter.stdout\n\n git_dir = %x[ git rev-parse --show-toplevel ].chomp\n\n if git_dir.empty?\n log.fatal \"ERROR: must be run in a git repository\"\n exit 1\n end\n\n log.debug \"Git Dir: '#{git_dir}'\"\n\n pack_files = Dir[File.join(git_dir, GIT_PACKS_RELATIVE_PATH)]\n log.debug \"Git Packs: #{pack_files.to_s}\"\n\n # For details on this IO, see http://stackoverflow.com/questions/1154846/continuously-read-from-stdout-of-external-process-in-ruby\n #\n # Short version is, git verify-pack flushes buffers only on line endings, so\n # this works, if it didn't, then we could get partial lines and be sad.\n\n types = {\n :blob => 1,\n :tree => 1,\n :commit => 1,\n }\n\n\n total_count = 0\n counted_objects = 0\n large_objects = []\n\n IO.popen(\"git verify-pack -v -- #{pack_files.join(\" \")}\") do |pipe|\n pipe.each do |line|\n # The output of git verify-pack -v is:\n # SHA1 type size size-in-packfile offset-in-packfile depth base-SHA1\n data = line.chomp.split(' ')\n # types are blob, tree, or commit\n # we ignore other lines by looking for that\n next unless types[data[1].to_sym] == 1\n log.info \"INPUT_THREAD: Processing object #{data[0]} type #{data[1]} size #{data[2]}\"\n hash = {\n :sha1 => data[0],\n :type => data[1],\n :size => data[2].to_i,\n }\n total_count += hash[:size]\n counted_objects += 1\n if hash[:size] > CUTOFF_SIZE\n large_objects.push hash\n end\n end\n end\n\n log.info \"Input complete\"\n\n log.info \"Counted #{counted_objects} totalling #{total_count} bytes.\"\n\n log.info \"Sorting\"\n\n large_objects.sort! { |a,b| b[:size] <=> a[:size] }\n\n log.info \"Sorting complete\"\n\n large_objects.each do |obj|\n log.info \"#{obj[:sha1]} #{obj[:type]} #{obj[:size]}\"\n end\n\n exit 0\nend\n</code></pre>\n\n<p>Next, edit the file to remove any blobs you don't wait and the INPUT_THREAD bits at the top. once you have only lines for the sha1s you want to find, run the following script like this:</p>\n\n<pre><code>cat edited-large-files.log | cut -d' ' -f4 | xargs git-find-blob | tee large-file-paths.log\n</code></pre>\n\n<p>Where the <code>git-find-blob</code> script is below.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>#!/usr/bin/perl\n\n# taken from: http://stackoverflow.com/questions/223678/which-commit-has-this-blob\n# and modified by Carl Myers <[email protected]> to scan multiple blobs at once\n# Also, modified to keep the discovered filenames\n# vi: ft=perl\n\nuse 5.008;\nuse strict;\nuse Memoize;\nuse Data::Dumper;\n\n\nmy $BLOBS = {};\n\nMAIN: {\n\n memoize 'check_tree';\n\n die \"usage: git-find-blob <blob1> <blob2> ... -- [<git-log arguments ...>]\\n\"\n if not @ARGV;\n\n\n while ( @ARGV && $ARGV[0] ne '--' ) {\n my $arg = $ARGV[0];\n #print \"Processing argument $arg\\n\";\n open my $rev_parse, '-|', git => 'rev-parse' => '--verify', $arg or die \"Couldn't open pipe to git-rev-parse: $!\\n\";\n my $obj_name = <$rev_parse>;\n close $rev_parse or die \"Couldn't expand passed blob.\\n\";\n chomp $obj_name;\n #$obj_name eq $ARGV[0] or print \"($ARGV[0] expands to $obj_name)\\n\";\n print \"($arg expands to $obj_name)\\n\";\n $BLOBS->{$obj_name} = $arg;\n shift @ARGV;\n }\n shift @ARGV; # drop the -- if present\n\n #print \"BLOBS: \" . Dumper($BLOBS) . \"\\n\";\n\n foreach my $blob ( keys %{$BLOBS} ) {\n #print \"Printing results for blob $blob:\\n\";\n\n open my $log, '-|', git => log => @ARGV, '--pretty=format:%T %h %s'\n or die \"Couldn't open pipe to git-log: $!\\n\";\n\n while ( <$log> ) {\n chomp;\n my ( $tree, $commit, $subject ) = split \" \", $_, 3;\n #print \"Checking tree $tree\\n\";\n my $results = check_tree( $tree );\n\n #print \"RESULTS: \" . Dumper($results);\n if (%{$results}) {\n print \"$commit $subject\\n\";\n foreach my $blob ( keys %{$results} ) {\n print \"\\t\" . (join \", \", @{$results->{$blob}}) . \"\\n\";\n }\n }\n }\n }\n\n}\n\n\nsub check_tree {\n my ( $tree ) = @_;\n #print \"Calculating hits for tree $tree\\n\";\n\n my @subtree;\n\n # results = { BLOB => [ FILENAME1 ] }\n my $results = {};\n {\n open my $ls_tree, '-|', git => 'ls-tree' => $tree\n or die \"Couldn't open pipe to git-ls-tree: $!\\n\";\n\n # example git ls-tree output:\n # 100644 blob 15d408e386400ee58e8695417fbe0f858f3ed424 filaname.txt\n while ( <$ls_tree> ) {\n /\\A[0-7]{6} (\\S+) (\\S+)\\s+(.*)/\n or die \"unexpected git-ls-tree output\";\n #print \"Scanning line '$_' tree $2 file $3\\n\";\n foreach my $blob ( keys %{$BLOBS} ) {\n if ( $2 eq $blob ) {\n print \"Found $blob in $tree:$3\\n\";\n push @{$results->{$blob}}, $3;\n }\n }\n push @subtree, [$2, $3] if $1 eq 'tree';\n }\n }\n\n foreach my $st ( @subtree ) {\n # $st->[0] is tree, $st->[1] is dirname\n my $st_result = check_tree( $st->[0] );\n foreach my $blob ( keys %{$st_result} ) {\n foreach my $filename ( @{$st_result->{$blob}} ) {\n my $path = $st->[1] . '/' . $filename;\n #print \"Generating subdir path $path\\n\";\n push @{$results->{$blob}}, $path;\n }\n }\n }\n\n #print \"Returning results for tree $tree: \" . Dumper($results) . \"\\n\\n\";\n return $results;\n}\n</code></pre>\n\n<p>The output will look like this:</p>\n\n<pre><code><hash prefix> <oneline log message>\n path/to/file.txt\n path/to/file2.txt\n ...\n<hash prefix2> <oneline log msg...>\n</code></pre>\n\n<p>And so on. Every commit which contains a large file in its tree will be listed. if you <code>grep</code> out the lines that start with a tab, and <code>uniq</code> that, you will have a list of all paths you can filter-branch to remove, or you can do something more complicated.</p>\n\n<p>Let me reiterate: this process ran successfully, on a 10GB repo with 108,000 commits. It took much longer than I predicted when running on a large number of blobs though, over 10 hours, I will have to see if the memorize bit is working...</p>\n"
},
{
"answer_id": 32611564,
"author": "aragaer",
"author_id": 390363,
"author_profile": "https://Stackoverflow.com/users/390363",
"pm_score": 5,
"selected": false,
"text": "<p>Unfortunately scripts were a bit slow for me, so I had to optimize a bit. Luckily I had not only the hash but also the path of a file.</p>\n<pre><code>git log --all --pretty=format:%H -- <path> | xargs -I% sh -c "git ls-tree % -- <path> | grep -q <hash> && echo %"\n</code></pre>\n"
},
{
"answer_id": 48027778,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>Given the hash of a blob, is there a way to get a list of commits that have this blob in their tree?</p>\n</blockquote>\n\n<p>With Git 2.16 (Q1 2018), <a href=\"https://git-scm.com/docs/git-describe\" rel=\"noreferrer\"><code>git describe</code></a> would be a good solution, since it was taught to dig trees deeper to find a <code><commit-ish>:<path></code> that refers to a given blob object.</p>\n\n<p>See <a href=\"https://github.com/git/git/commit/644eb60bd01a15f665b63774fd80e3b6316073a1\" rel=\"noreferrer\">commit 644eb60</a>, <a href=\"https://github.com/git/git/commit/4dbc59a4cce418ff8428a9d2ecd67c34ca50db56\" rel=\"noreferrer\">commit 4dbc59a</a>, <a href=\"https://github.com/git/git/commit/cdaed0cf023a47cae327671fae11c10d88100ee7\" rel=\"noreferrer\">commit cdaed0c</a>, <a href=\"https://github.com/git/git/commit/c87b653c46c4455561642b14efc8920a0b3e44b9\" rel=\"noreferrer\">commit c87b653</a>, <a href=\"https://github.com/git/git/commit/ce5b6f9be84690ba38eba10c42b3f7c7e2511abb\" rel=\"noreferrer\">commit ce5b6f9</a> (16 Nov 2017), and <a href=\"https://github.com/git/git/commit/91904f5645196ceef92c6fca21cc9454928613f0\" rel=\"noreferrer\">commit 91904f5</a>, <a href=\"https://github.com/git/git/commit/2deda00707f8278382d64c696d75f33cc16e1233\" rel=\"noreferrer\">commit 2deda00</a> (02 Nov 2017) by <a href=\"https://github.com/stefanbeller\" rel=\"noreferrer\">Stefan Beller (<code>stefanbeller</code>)</a>.<br>\n<sup>(Merged by <a href=\"https://github.com/gitster\" rel=\"noreferrer\">Junio C Hamano -- <code>gitster</code> --</a> in <a href=\"https://github.com/git/git/commit/556de1a8e38ff03d31fd35751582447001f39d0c\" rel=\"noreferrer\">commit 556de1a</a>, 28 Dec 2017)</sup> </p>\n\n<blockquote>\n <h2><a href=\"https://github.com/git/git/blob/644eb60bd01a15f665b63774fd80e3b6316073a1/builtin/describe.c\" rel=\"noreferrer\"><code>builtin/describe.c</code></a>: describe a blob</h2>\n \n <p>Sometimes users are given a hash of an object and they want to\n identify it further (ex.: Use <code>verify-pack</code> to find the largest blobs,\n but what are these? or this very SO question \"<a href=\"https://stackoverflow.com/q/223678/6309\">Which commit has this blob?</a>\")</p>\n \n <p>When describing commits, we try to anchor them to tags or refs, as these\n are conceptually on a higher level than the commit. And if there is no ref\n or tag that matches exactly, we're out of luck.<br>\n So we employ a heuristic to make up a name for the commit. These names are ambiguous, there might be different tags or refs to anchor to, and there might be different path in the DAG to travel to arrive at the commit precisely.</p>\n \n <p>When describing a blob, we want to describe the blob from a higher layer\n as well, which is a tuple of <code>(commit, deep/path)</code> as the tree objects\n involved are rather uninteresting.<br>\n The same blob can be referenced by multiple commits, so how we decide which commit to use? </p>\n \n <p>This patch implements a rather naive approach on this: <strong>As there are no back pointers from blobs to commits in which the blob occurs, we'll start walking from any tips available, listing the blobs in-order of the commit and once we\n found the blob, we'll take the first commit that listed the blob</strong>. </p>\n \n <p>For example:</p>\n\n<pre><code>git describe --tags v0.99:Makefile\nconversion-901-g7672db20c2:Makefile\n</code></pre>\n \n <p>tells us the <code>Makefile</code> as it was in <code>v0.99</code> was introduced in <a href=\"https://github.com/git/git/commit/7672db20c2060f20b01788e4a4289ebc5f818605#diff-b67911656ef5d18c4ae36cb6741b7965\" rel=\"noreferrer\">commit 7672db2</a>.</p>\n \n <p>The walking is performed in reverse order to show the introduction of a\n blob rather than its last occurrence.</p>\n</blockquote>\n\n<p>That means the <a href=\"https://github.com/git/git/blob/644eb60bd01a15f665b63774fd80e3b6316073a1/Documentation/git-describe.txt\" rel=\"noreferrer\"><code>git describe</code> man page</a> adds to the purposes of this command: </p>\n\n<blockquote>\n <p>Instead of simply describing a commit using the most recent tag reachable from it, <code>git describe</code> will actually give an object a human readable name based on an available ref when used as <code>git describe <blob></code>.</p>\n \n <p>If the given object refers to a blob, it will be described as <code><commit-ish>:<path></code>, such that the blob can be found at <code><path></code> in the <code><commit-ish></code>, which itself describes the first commit in which this blob occurs in a reverse revision walk from HEAD.</p>\n</blockquote>\n\n<p>But:</p>\n\n<blockquote>\n <h2>BUGS</h2>\n \n <p><strong>Tree objects as well as tag objects not pointing at commits, cannot be described</strong>.<br>\n When describing blobs, the lightweight tags pointing at blobs are ignored, but the blob is still described as <code><committ-ish>:<path></code> despite the lightweight tag being favorable.</p>\n</blockquote>\n"
},
{
"answer_id": 48590251,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "<p>In addition to <a href=\"https://stackoverflow.com/a/48027778/6309\"><code>git describe</code>, that I mention in my previous answer</a>, <code>git log</code> and <code>git diff</code> now benefits as well from the "<code>--find-object=<object-id></code>" option to limit the findings to changes that involve the named object.<br />\nThat is in Git 2.16.x/2.17 (Q1 2018)</p>\n<p>See <a href=\"https://github.com/git/git/commit/4d8c51aa19be94bddb7cac6b11bccb4d23dfd4f8\" rel=\"noreferrer\">commit 4d8c51a</a>, <a href=\"https://github.com/git/git/commit/5e505257f2651647c072f9c61fdc5dd52bbce8b2\" rel=\"noreferrer\">commit 5e50525</a>, <a href=\"https://github.com/git/git/commit/15af58c1adba431c216e2a45fa0d22944560ba02\" rel=\"noreferrer\">commit 15af58c</a>, <a href=\"https://github.com/git/git/commit/cf63051adad03e827e0313a57db0a79ad39a04a0\" rel=\"noreferrer\">commit cf63051</a>, <a href=\"https://github.com/git/git/commit/c1ddc4610c553b06591aac74b610b56448cbb976\" rel=\"noreferrer\">commit c1ddc46</a>, <a href=\"https://github.com/git/git/commit/929ed70a7263fc3be909b363993672b649153706\" rel=\"noreferrer\">commit 929ed70</a> (04 Jan 2018) by <a href=\"https://github.com/stefanbeller\" rel=\"noreferrer\">Stefan Beller (<code>stefanbeller</code>)</a>.<br />\n<sup>(Merged by <a href=\"https://github.com/gitster\" rel=\"noreferrer\">Junio C Hamano -- <code>gitster</code> --</a> in <a href=\"https://github.com/git/git/commit/c0d75f0e2e2cbf432358bfd00be593fd28e257a3\" rel=\"noreferrer\">commit c0d75f0</a>, 23 Jan 2018)</sup></p>\n<blockquote>\n<h2><code>diffcore</code>: add a pickaxe option to find a specific blob</h2>\n</blockquote>\n<blockquote>\n<p>Sometimes users are given a hash of an object and they want to identify it further (ex.: Use verify-pack to find the largest blobs,\nbut what are these? Or this Stack Overflow question "<a href=\"https://stackoverflow.com/q/223678/6309\">Which commit has this blob?</a>")</p>\n<p>One might be tempted to extend <code>git-describe</code> to also work with blobs,\nsuch that <code>git describe <blob-id></code> gives a description as\n'<code><commit-ish>:<path></code>'.<br />\nThis was <a href=\"https://public-inbox.org/git/[email protected]/\" rel=\"noreferrer\">implemented here</a>; as seen by the sheer\nnumber of responses (>110), it turns out this is tricky to get right.<br />\nThe hard part to get right is picking the correct 'commit-ish' as that\ncould be the commit that (re-)introduced the blob or the blob that\nremoved the blob; the blob could exist in different branches.</p>\n<p>Junio hinted at a different approach of solving this problem, which this\npatch implements.<br />\nTeach the <code>diff</code> machinery another flag for restricting the information to what is shown.<br />\nFor example:</p>\n<pre><code>$ ./git log --oneline --find-object=v2.0.0:Makefile\n b2feb64 Revert the whole "ask curl-config" topic for now\n 47fbfde i18n: only extract comments marked with "TRANSLATORS:"\n</code></pre>\n<p>we observe that the <code>Makefile</code> as shipped with <code>2.0</code> was appeared in\n<code>v1.9.2-471-g47fbfded53</code> and in <code>v2.0.0-rc1-5-gb2feb6430b</code>.<br />\nThe reason why these commits both occur prior to v2.0.0 are evil\nmerges that are not found using this new mechanism.</p>\n</blockquote>\n<hr />\n<p>As noted in <a href=\"https://stackoverflow.com/questions/223678/which-commit-has-this-blob/48590251#comment122173464_48590251\">the comments</a> by <a href=\"https://stackoverflow.com/users/4288506/marcono1234\">marcono1234</a>, you can combine that with the <a href=\"https://git-scm.com/docs/git-log#Documentation/git-log.txt---all\" rel=\"noreferrer\">git log --all</a> option:</p>\n<blockquote>\n<p>this can be useful when you don't know which branch contains the object.</p>\n</blockquote>\n"
},
{
"answer_id": 66662476,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 5,
"selected": false,
"text": "<p>For humans, the most useful command is probably</p>\n<pre><code>git whatchanged --all --find-object=<blob hash>\n</code></pre>\n<p>This shows, across <code>--all</code> branches, any commits that added or removed a file with that hash, along with what the path was.</p>\n<pre><code>git$ git whatchanged --all --find-object=b3bb59f06644\ncommit 8ef93124645f89c45c9ec3edd3b268b38154061a \n⋮\ndiff: do not show submodule with untracked files as "-dirty"\n⋮\n:100644 100644 b3bb59f06644 8f6227c993a5 M submodule.c\n\ncommit 7091499bc0a9bccd81a1c864de7b5f87a366480e \n⋮\nRevert "submodules: fix of regression on fetching of non-init subsub-repo"\n⋮\n:100644 100644 eef5204e641e b3bb59f06644 M submodule.c\n</code></pre>\n<p>Note that <code>git whatchanged</code> already includes the before-and-after blob hashes in its output lines.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
Given the hash of a blob, is there a way to get a list of commits that have this blob in their tree?
|
Both of the following scripts take the blob’s SHA1 as the first argument, and after it, optionally, any arguments that [`git log`](http://git-scm.com/docs/git-log) will understand. E.g. `--all` to search in all branches instead of just the current one, or `-g` to search in the reflog, or whatever else you fancy.
Here it is as a shell script – short and sweet, but slow:
```bash
#!/bin/sh
obj_name="$1"
shift
git log "$@" --pretty=tformat:'%T %h %s' \
| while read tree commit subject ; do
if git ls-tree -r $tree | grep -q "$obj_name" ; then
echo $commit "$subject"
fi
done
```
And an optimised version in Perl, still quite short but much faster:
```perl
#!/usr/bin/perl
use 5.008;
use strict;
use Memoize;
my $obj_name;
sub check_tree {
my ( $tree ) = @_;
my @subtree;
{
open my $ls_tree, '-|', git => 'ls-tree' => $tree
or die "Couldn't open pipe to git-ls-tree: $!\n";
while ( <$ls_tree> ) {
/\A[0-7]{6} (\S+) (\S+)/
or die "unexpected git-ls-tree output";
return 1 if $2 eq $obj_name;
push @subtree, $2 if $1 eq 'tree';
}
}
check_tree( $_ ) && return 1 for @subtree;
return;
}
memoize 'check_tree';
die "usage: git-find-blob <blob> [<git-log arguments ...>]\n"
if not @ARGV;
my $obj_short = shift @ARGV;
$obj_name = do {
local $ENV{'OBJ_NAME'} = $obj_short;
`git rev-parse --verify \$OBJ_NAME`;
} or die "Couldn't parse $obj_short: $!\n";
chomp $obj_name;
open my $log, '-|', git => log => @ARGV, '--pretty=format:%T %h %s'
or die "Couldn't open pipe to git-log: $!\n";
while ( <$log> ) {
chomp;
my ( $tree, $commit, $subject ) = split " ", $_, 3;
print "$commit $subject\n" if check_tree( $tree );
}
```
|
223,700 |
<p>I have a class that I need to binary serialize. The class contains one field as below:</p>
<pre><code>private T[,] m_data;
</code></pre>
<p>These multi-dimensional arrays can be fairly large (hundreds of thousands of elements) and of any primitive type. When I tried standard .net serialization on an object the file written to disk was large and I think .net is storing a lot of repeated data about element types and possibly not as efficiently as could be done.</p>
<p>I have looked around for custom serializers but have not seen any that deal with multi-dimensional generic arrays. I have also experimented with built-in .net compression on a byte array of the memory stream following serializing with some success, but not as quick / compressed as I had hoped.</p>
<p>My question is, should I try and write a custom serializer to optimally serialize this array for the appropriate type (this seems a little daunting), or should I use standard .net serialization and add compression?</p>
<p>Any advice on the best approach would be most appreciated, or links to resources showing how to tackle serialization of a multi-dimensional generic array - as mentioned <a href="http://www.codeproject.com/KB/dotnet/FastSerializer.aspx" rel="noreferrer">existing examples</a> I have found do not support such structures.</p>
|
[
{
"answer_id": 223721,
"author": "Shachar",
"author_id": 13897,
"author_profile": "https://Stackoverflow.com/users/13897",
"pm_score": 0,
"selected": false,
"text": "<p>The best code length/output size ratio would be to encode your array using BitConverter, converting all elements into their compact binary format. It's manual, I know, but will save 80-90% space compared to .NET binary serialization.</p>\n"
},
{
"answer_id": 224008,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 4,
"selected": true,
"text": "<p>Here's what I came up with. The code below makes an int[1000][10000] and writes it out using the BinaryFormatter to 2 files - one zipped and one not. </p>\n\n<p>The zipped file is 1.19 MB (1,255,339 bytes)\nUnzipped is 38.2 MB (40,150,034 bytes)</p>\n\n<pre><code> int width = 1000;\n int height = 10000;\n List<int[]> list = new List<int[]>();\n for (int i = 0; i < height; i++)\n {\n list.Add(Enumerable.Range(0, width).ToArray());\n }\n int[][] bazillionInts = list.ToArray();\n using (FileStream fsZ = new FileStream(\"c:\\\\temp_zipped.txt\", FileMode.Create))\n using (FileStream fs = new FileStream(\"c:\\\\temp_notZipped.txt\", FileMode.Create))\n using (GZipStream gz = new GZipStream(fsZ, CompressionMode.Compress))\n {\n BinaryFormatter f = new BinaryFormatter();\n f.Serialize(gz, bazillionInts);\n f.Serialize(fs, bazillionInts);\n }\n</code></pre>\n\n<p>I can't think of a better/easy way to do this. The zipped version is pretty damn tight.</p>\n\n<p>I'd go with the BinaryFormatter + GZipStream. Making something custom would not be fun at all.</p>\n\n<hr>\n\n<p>[edit by MG]\nI hope you won't be offended by an edit, but the uniform repeated Range(0,width) is skewing things vastly; change to:</p>\n\n<pre><code> int width = 1000;\n int height = 10000;\n Random rand = new Random(123456);\n int[,] bazillionInts = new int[width, height];\n for(int i = 0 ; i < width;i++)\n for (int j = 0; j < height; j++)\n {\n bazillionInts[i, j] = rand.Next(50000);\n }\n</code></pre>\n\n<p>And try it; you'll see <code>temp_notZipped.txt</code> at 40MB, <code>temp_zipped.txt</code> at 62MB. Not so appealing...</p>\n"
},
{
"answer_id": 224598,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>Can you define \"large\"? The 1000x10000xint example (another post) comes out at 40Mb; and 1000x10000x4 bytes (=int) is 38MB. As overheads go, that isn't terrible.</p>\n\n<p>What sort of data is T likely to be? Just primatives?\nI'm thinking that I could probably edit <a href=\"http://code.google.com/p/protobuf-net/\" rel=\"nofollow noreferrer\">protobuf-net</a> to support rectangular arrays<code>*</code> - but to keep some kind of wire-compatibility we'd probably need a header (one byte) <em>per element</em> - i.e. 9MB of overhead for the 1000x10000 example.</p>\n\n<p>This probably isn't worth it for things like <code>float</code>, <code>double</code>, etc (since they are stored verbatim under \"protocol buffers\") - but there may be savings for things like <code>int</code> simply due to how it packs ints... (especially if they tend to be on the smaller side [magnitude]). Finally, if T is actually objects like <code>Person</code> etc, then it should be a <em>lot</em> better than binary serialization, since it is very good at packing objects.</p>\n\n<p>It wouldn't be trivial to shoe-horn in rectangular arrays, but let me know if this is something you'd be interested in trying.</p>\n\n<p><code>*</code>: it doesn't at the moment since the \"protocol buffers\" spec doesn't support them, but we can hack around that...</p>\n"
},
{
"answer_id": 1477773,
"author": "David Boike",
"author_id": 10039,
"author_profile": "https://Stackoverflow.com/users/10039",
"pm_score": 0,
"selected": false,
"text": "<p>The reason there needs to be so much data about the types is that your array of T could be any type, but more specifically, T could be of type SomeBaseClass, and you could still store SomeDerivedClass in that array, and the deserializer would need to know this.</p>\n\n<p>But this redundant data makes it a good candidate for compression, as others have noted.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30132/"
] |
I have a class that I need to binary serialize. The class contains one field as below:
```
private T[,] m_data;
```
These multi-dimensional arrays can be fairly large (hundreds of thousands of elements) and of any primitive type. When I tried standard .net serialization on an object the file written to disk was large and I think .net is storing a lot of repeated data about element types and possibly not as efficiently as could be done.
I have looked around for custom serializers but have not seen any that deal with multi-dimensional generic arrays. I have also experimented with built-in .net compression on a byte array of the memory stream following serializing with some success, but not as quick / compressed as I had hoped.
My question is, should I try and write a custom serializer to optimally serialize this array for the appropriate type (this seems a little daunting), or should I use standard .net serialization and add compression?
Any advice on the best approach would be most appreciated, or links to resources showing how to tackle serialization of a multi-dimensional generic array - as mentioned [existing examples](http://www.codeproject.com/KB/dotnet/FastSerializer.aspx) I have found do not support such structures.
|
Here's what I came up with. The code below makes an int[1000][10000] and writes it out using the BinaryFormatter to 2 files - one zipped and one not.
The zipped file is 1.19 MB (1,255,339 bytes)
Unzipped is 38.2 MB (40,150,034 bytes)
```
int width = 1000;
int height = 10000;
List<int[]> list = new List<int[]>();
for (int i = 0; i < height; i++)
{
list.Add(Enumerable.Range(0, width).ToArray());
}
int[][] bazillionInts = list.ToArray();
using (FileStream fsZ = new FileStream("c:\\temp_zipped.txt", FileMode.Create))
using (FileStream fs = new FileStream("c:\\temp_notZipped.txt", FileMode.Create))
using (GZipStream gz = new GZipStream(fsZ, CompressionMode.Compress))
{
BinaryFormatter f = new BinaryFormatter();
f.Serialize(gz, bazillionInts);
f.Serialize(fs, bazillionInts);
}
```
I can't think of a better/easy way to do this. The zipped version is pretty damn tight.
I'd go with the BinaryFormatter + GZipStream. Making something custom would not be fun at all.
---
[edit by MG]
I hope you won't be offended by an edit, but the uniform repeated Range(0,width) is skewing things vastly; change to:
```
int width = 1000;
int height = 10000;
Random rand = new Random(123456);
int[,] bazillionInts = new int[width, height];
for(int i = 0 ; i < width;i++)
for (int j = 0; j < height; j++)
{
bazillionInts[i, j] = rand.Next(50000);
}
```
And try it; you'll see `temp_notZipped.txt` at 40MB, `temp_zipped.txt` at 62MB. Not so appealing...
|
223,713 |
<p>I've just started working with ASP.NET MVC now that it's in beta. In my code, I'm running a simple LINQ to SQL query to get a list of results and passing that to my view. This sort of thing:</p>
<pre><code>var ords = from o in db.Orders
where o.OrderDate == DateTime.Today
select o;
return View(ords);
</code></pre>
<p>However, in my View, I realised that I'd need to access the customer's name for each order. I started using <code>o.Customer.Name</code> but I'm fairly certain that this is executing a separate query for each order (because of LINQ's lazy loading).</p>
<p>The logical way to cut down the number of queries would be to select the customer name at the same time. Something like:</p>
<pre><code>var ords = from o in db.Orders
from c in db.Customers
where o.OrderDate == DateTime.Today
and o.CustomerID == c.CustomerID
select new { o.OrderID, /* ... */, c.CustomerName };
return View(ords);
</code></pre>
<p>Except now my "ords" variable is an IEnumerable of an anonymous type.</p>
<p>Is it possible to declare an ASP.NET MVC View in such a way that it accepts an IEnumerable as its view data where T is defined by what gets passed from the controller, or will I have to define a concrete type to populate from my query?</p>
|
[
{
"answer_id": 223811,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "<p>you may be able to pass an Object and use reflection to get your desired results. Have a look at ObjectDumper.cs (included in csharpexamples.zip) for an example of this.</p>\n"
},
{
"answer_id": 223846,
"author": "Mitch",
"author_id": 393334,
"author_profile": "https://Stackoverflow.com/users/393334",
"pm_score": 0,
"selected": false,
"text": "<p>If I'm not mistaken, anonymous types are converted into strongly typed objects at compile time. Whether the strongly typed object is valid for view data is another question though.</p>\n"
},
{
"answer_id": 223907,
"author": "zadam",
"author_id": 410357,
"author_profile": "https://Stackoverflow.com/users/410357",
"pm_score": 1,
"selected": false,
"text": "<p>This <a href=\"http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx\" rel=\"nofollow noreferrer\">post</a> shows how you can return an anonymous type from a method, but it is not going to suit your requirements.</p>\n\n<p>Another option may be to instead convert the anonymous type into JSON (JavaScriptSerializer will do it) and then return that JSON to the view, you would then need some jQuery etc to do what you like with it.</p>\n\n<p>I have been using Linq to 'shape' my data into a JSON format that my view needs with great success.</p>\n"
},
{
"answer_id": 224005,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 6,
"selected": true,
"text": "<p>Can you pass it to the view? Yes, but your view won't be strongly typed. But the helpers will work. For example:</p>\n\n<pre><code>public ActionResult Foo() {\n return View(new {Something=\"Hey, it worked!\"});\n}\n\n//Using a normal ViewPage\n\n<%= Html.TextBox(\"Something\") %>\n</code></pre>\n\n<p>That textbox should render \"Hey, it worked!\" as the value.</p>\n\n<p>So can you define a view where T is defined by what gets passed to it from the controller? Well yes, but not at compile time obviously.</p>\n\n<p>Think about it for a moment. When you declare a model type for a view, it's so you get intellisense for the view. That means the type must be determined at compile time. But the question asks, can we determine the type from something given to it at runtime. Sure, but not with strong typing preserved.</p>\n\n<p>How would you get Intellisense for a type you don't even know yet? The controller could end up passing any type to the view while at runtime. We can't even analyze the code and guess, because action filters could change the object passed to the view for all we know.</p>\n\n<p>I hope that clarifies the answer without obfuscating it more. :)</p>\n"
},
{
"answer_id": 225159,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>For what it's worth, tonight I discovered the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx\" rel=\"nofollow noreferrer\">DataLoadOptions</a> class and its <a href=\"http://msdn.microsoft.com/en-us/library/bb534268.aspx\" rel=\"nofollow noreferrer\">LoadWith</a> method. I was able to tell my LINQ to SQL DataContext to always load a Customers row whenever an Orders row is retrieved, so the original query now gets everything I need in one hit.</p>\n"
},
{
"answer_id": 1043218,
"author": "Alper",
"author_id": 89841,
"author_profile": "https://Stackoverflow.com/users/89841",
"pm_score": 1,
"selected": false,
"text": "<p>You can write a class with the same properties of your anonymous type's, and you can cast your anonymous type to your hand-written type. The drawback is you have to update the class when you make projection changes in your linq query.</p>\n"
},
{
"answer_id": 1168822,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm with the same problem... after thinking a bit, I came to the conclusion that the most correct and most scalable solution, its to serialize this anonymous type before sending to the View. So, you can use the same method to fill the page using the View code behind and to populate your page using JSON</p>\n"
},
{
"answer_id": 4680966,
"author": "Lasse Skindstad Ebert",
"author_id": 395700,
"author_profile": "https://Stackoverflow.com/users/395700",
"pm_score": 4,
"selected": false,
"text": "<p>You <em>can</em> pass anonymous types to a view, just remember to cast the model to a dynamic.</p>\n\n<p>You can do like this:</p>\n\n<pre><code>return View(new { \n MyItem = \"Hello\", \n SomethingElse = 42, \n Third = new MyClass(42, \"Yes\") })\n</code></pre>\n\n<p>In the top of the view you can then do this (using razor here)</p>\n\n<pre><code>@{\n string myItem = (dynamic)Model.MyItem;\n int somethingElse = (dynamic)Model.SomethingElse;\n MyClass third = (dynamic)Model.Third;\n}\n</code></pre>\n\n<p>Or you can cast them from the ViewData like this:</p>\n\n<pre><code>@{\n var myItem = ViewData.Eval(\"MyItem\") as string\n var somethingElse = ViewData.Eval(\"SomethingElse\") as int?\n var third = ViewData.Eval(\"Third\") as MyClass \n}\n</code></pre>\n"
},
{
"answer_id": 5670992,
"author": "Adaptabi",
"author_id": 219349,
"author_profile": "https://Stackoverflow.com/users/219349",
"pm_score": 3,
"selected": false,
"text": "<p>On .NET 4.0 Anonymous types can easily be converted to ExpandoObjects and thus all the problems is fixed with the overhead of the conversion itself. \nCheck out <a href=\"https://stackoverflow.com/questions/5120317/dynamic-anonymous-type-in-razor-causes-runtimebinderexception/5670899#5670899\">here</a></p>\n"
},
{
"answer_id": 19922551,
"author": "Raja",
"author_id": 2982034,
"author_profile": "https://Stackoverflow.com/users/2982034",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.dotnetfunda.com/articles/show/2655/binding-views-with-anonymous-type-collection-in-aspnet-mvc\" rel=\"nofollow\">Here</a> is an article explaining about passing Anonymous type to Views and binding the data.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 50454454,
"author": "AlexMelw",
"author_id": 5259296,
"author_profile": "https://Stackoverflow.com/users/5259296",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Remember:</strong> <code>anonymous</code> types are internal, which means their properties can't be seen outside their defining assembly.</p>\n\n<p>You'd better pass <code>dynamic</code> object (instead of <code>anonymous</code> one) to your <code>View</code> by converting <code>anonymous</code> type to <code>dynamic</code>, using an extension method.</p>\n\n<pre><code>public class AwesomeController : Controller\n{\n // Other actions omitted...\n public ActionResult SlotCreationSucceeded(string email, string roles)\n {\n return View(\"SlotCreationSucceeded\", new { email, roles }.ToDynamic());\n }\n}\n</code></pre>\n\n<hr>\n\n<p>The extension method would look like this:</p>\n\n<pre><code>public static class DynamicExtensions\n{\n public static dynamic ToDynamic(this object value)\n {\n IDictionary<string, object> expando = new ExpandoObject();\n\n foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))\n expando.Add(property.Name, property.GetValue(value));\n\n return (ExpandoObject) expando;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Nevertheless you are <strong>still able</strong> to pass an <code>anonymous</code> object, but you'll have to convert it to a <code>dynamic</code> one later on.</p>\n\n<pre><code>public class AwesomeController : Controller\n{\n // Other actions omitted...\n public ActionResult SlotCreationSucceeded(string email, string roles)\n {\n return View(\"SlotCreationSucceeded\", new { email, roles });\n }\n}\n</code></pre>\n\n<p><strong>View:</strong></p>\n\n<pre><code>@{\n var anonymousModel = DynamicUtil.ToAnonymous(Model, new { email = default(string), roles = default(string) });\n}\n\n<h1>@anonymousModel.email</h1>\n<h2>@anonymousModel.roles</h2>\n</code></pre>\n\n<p>The helper method would look like this:</p>\n\n<pre><code>public class DynamicUtil\n{\n public static T ToAnonymous<T>(ExpandoObject source, T sample)\n where T : class\n {\n var dict = (IDictionary<string, object>) source;\n\n var ctor = sample.GetType().GetConstructors().Single();\n\n var parameters = ctor.GetParameters();\n\n var parameterValues = parameters.Select(p => dict[p.Name]).ToArray();\n\n return (T) ctor.Invoke(parameterValues);\n }\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
] |
I've just started working with ASP.NET MVC now that it's in beta. In my code, I'm running a simple LINQ to SQL query to get a list of results and passing that to my view. This sort of thing:
```
var ords = from o in db.Orders
where o.OrderDate == DateTime.Today
select o;
return View(ords);
```
However, in my View, I realised that I'd need to access the customer's name for each order. I started using `o.Customer.Name` but I'm fairly certain that this is executing a separate query for each order (because of LINQ's lazy loading).
The logical way to cut down the number of queries would be to select the customer name at the same time. Something like:
```
var ords = from o in db.Orders
from c in db.Customers
where o.OrderDate == DateTime.Today
and o.CustomerID == c.CustomerID
select new { o.OrderID, /* ... */, c.CustomerName };
return View(ords);
```
Except now my "ords" variable is an IEnumerable of an anonymous type.
Is it possible to declare an ASP.NET MVC View in such a way that it accepts an IEnumerable as its view data where T is defined by what gets passed from the controller, or will I have to define a concrete type to populate from my query?
|
Can you pass it to the view? Yes, but your view won't be strongly typed. But the helpers will work. For example:
```
public ActionResult Foo() {
return View(new {Something="Hey, it worked!"});
}
//Using a normal ViewPage
<%= Html.TextBox("Something") %>
```
That textbox should render "Hey, it worked!" as the value.
So can you define a view where T is defined by what gets passed to it from the controller? Well yes, but not at compile time obviously.
Think about it for a moment. When you declare a model type for a view, it's so you get intellisense for the view. That means the type must be determined at compile time. But the question asks, can we determine the type from something given to it at runtime. Sure, but not with strong typing preserved.
How would you get Intellisense for a type you don't even know yet? The controller could end up passing any type to the view while at runtime. We can't even analyze the code and guess, because action filters could change the object passed to the view for all we know.
I hope that clarifies the answer without obfuscating it more. :)
|
223,738 |
<p>I have a DataSet consisting of XML data, I can easily output this to a file:</p>
<pre><code>DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
ds.Load(reader, LoadOption.PreserveChanges, ds.Tables[0]);
ds.WriteXml("C:\\test.xml");
</code></pre>
<p>However what I want to do is compress the XML into a ZIP or other type of compressed file and then just save this file to disk while splitting the ZIP file into 1MB chunks. I do not really want to save the uncompressed file, and then zip it, then split it.</p>
<p><strong>What I'm looking for specifically is:</strong></p>
<ol>
<li>a suitable compression library that I can stream the XML to and have the zip file(s) saved to disk</li>
<li>some sample C# code that can show me how to do this.</li>
</ol>
|
[
{
"answer_id": 223764,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": true,
"text": "<p>I've managed to compress a DataSet's XML stream using .NET 2.0's gzip compression.</p>\n\n<p>Here's the blog post I made a few years ago about it:</p>\n\n<p><a href=\"http://www.madprops.org/blog/saving-datasets-locally-with-compression\" rel=\"noreferrer\">Saving DataSets Locally With Compression</a></p>\n\n<p>... and here's the code I added to my DataSet's partial class to write the compressed file (the blog post has the reading code too):</p>\n\n<pre><code>public void WriteFile(string fileName)\n{\n using (FileStream fs = new FileStream(fileName, FileMode.Create))\n {\n Stream s;\n if (Path.GetExtension(fileName) == \".cmx\")\n {\n s = new GZipStream(fs, CompressionMode.Compress);\n }\n else if (Path.GetExtension(fileName) == \".cmz\")\n {\n s = new DeflateStream(fs, CompressionMode.Compress);\n }\n else\n {\n s = fs;\n }\n WriteXml(s);\n s.Close();\n }\n} \n</code></pre>\n\n<p>Note that this code uses different compression schemes based on the file's extension. That was purely so I could test one scheme against the other with my DataSet.</p>\n"
},
{
"answer_id": 223765,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 1,
"selected": false,
"text": "<p>the framework includes a few classes for compressing streams. One of them is GZipStream. If you search for it you'll find plenty of hits. Here's <a href=\"https://web.archive.org/web/20200808123920/http://geekswithblogs.net/Podwysocki/archive/2006/06/21/82628.aspx\" rel=\"nofollow noreferrer\">one</a> of them. I imagine chunking the output would involve some some additional work.</p>\n"
},
{
"answer_id": 224079,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 2,
"selected": false,
"text": "<p>This works with streams or files, has a good license and source: <a href=\"http://www.codeplex.com/DotNetZip\" rel=\"nofollow noreferrer\">http://www.codeplex.com/DotNetZip</a></p>\n\n<p>Here's the code to do exactly what the original poster asked: write a DataSet into a zip that is split into 1mb chunks: </p>\n\n<pre><code>// get connection to the database\nvar c1= new System.Data.SqlClient.SqlConnection(connstring1);\nvar da = new System.Data.SqlClient.SqlDataAdapter()\n{\n SelectCommand= new System.Data.SqlClient.SqlCommand(strSelect, c1)\n};\n\nDataSet ds1 = new DataSet();\n\n// fill the dataset with the SELECT \nda.Fill(ds1, \"Invoices\");\n\n// write the XML for that DataSet into a zip file (split into 1mb chunks)\nusing(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())\n{\n zip.MaxOutputSegmentSize = 1024*1024;\n zip.AddEntry(zipEntryName, (name,stream) => ds1.WriteXml(stream) );\n zip.Save(zipFileName);\n}\n</code></pre>\n"
},
{
"answer_id": 224112,
"author": "Martin Plante",
"author_id": 4898,
"author_profile": "https://Stackoverflow.com/users/4898",
"pm_score": 1,
"selected": false,
"text": "<p>You should use <a href=\"http://xceed.com/Zip_Net_Intro.html\" rel=\"nofollow noreferrer\">Xceed Zip</a>. The code would look like this (not tested):</p>\n\n<pre><code>ZipArchive archive = new ZipArchive( new DiskFile( @\"c:\\path\\file.zip\" ) );\n\narchive.SplitSize = 1024*1024;\narchive.BeginUpdate();\n\ntry\n{\n AbstractFile destFile = archive.GetFile( \"data.xml\" );\n\n using( Stream stream = destFile.OpenWrite( true ) )\n {\n ds.WriteXml( stream );\n }\n}\nfinally\n{\n archive.EndUpdate();\n}\n</code></pre>\n"
},
{
"answer_id": 224206,
"author": "flatline",
"author_id": 20846,
"author_profile": "https://Stackoverflow.com/users/20846",
"pm_score": 2,
"selected": false,
"text": "<p>There is a not-so-well-known packaging API included with the 3.5 framework. The Assembly reference is in the GAC, called WindowsBase. The System.IO.Packaging namespace contains stuff for creating OPC files (e.g. OOXML), which are zip files containing xml and whatever else is desired. You get some extra stuff you don't need, but the ZipPackage class uses a streaming interface for adding content iteratively.</p>\n"
},
{
"answer_id": 627454,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://dotnetzip.codeplex.com\" rel=\"nofollow noreferrer\">DotNetZip</a> does zip compression, via streams, but does not do multi-part zip files. \n:(</p>\n\n<p><strong>EDIT</strong>: as of September 2009, DotNetZip can do multi-part zip files.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15144/"
] |
I have a DataSet consisting of XML data, I can easily output this to a file:
```
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
ds.Load(reader, LoadOption.PreserveChanges, ds.Tables[0]);
ds.WriteXml("C:\\test.xml");
```
However what I want to do is compress the XML into a ZIP or other type of compressed file and then just save this file to disk while splitting the ZIP file into 1MB chunks. I do not really want to save the uncompressed file, and then zip it, then split it.
**What I'm looking for specifically is:**
1. a suitable compression library that I can stream the XML to and have the zip file(s) saved to disk
2. some sample C# code that can show me how to do this.
|
I've managed to compress a DataSet's XML stream using .NET 2.0's gzip compression.
Here's the blog post I made a few years ago about it:
[Saving DataSets Locally With Compression](http://www.madprops.org/blog/saving-datasets-locally-with-compression)
... and here's the code I added to my DataSet's partial class to write the compressed file (the blog post has the reading code too):
```
public void WriteFile(string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
Stream s;
if (Path.GetExtension(fileName) == ".cmx")
{
s = new GZipStream(fs, CompressionMode.Compress);
}
else if (Path.GetExtension(fileName) == ".cmz")
{
s = new DeflateStream(fs, CompressionMode.Compress);
}
else
{
s = fs;
}
WriteXml(s);
s.Close();
}
}
```
Note that this code uses different compression schemes based on the file's extension. That was purely so I could test one scheme against the other with my DataSet.
|
223,748 |
<p>I have a nice little file upload control I wrote for ASP.NET webforms that utilizes an IFrame and ASP.NET AJAX.</p>
<p>However, on large uploads, the browser times out before it can finish posting the form.</p>
<p>Is there a way I can increase this?</p>
<p>I'm not really interesting in alternative solutions, so don't suggest changing the entire thing out please. It works good for <5 meg uploads, I'd just like to get it up to about 8mb.</p>
<p>EDIT: Setting the timeout in Page_Load didn't appear to change anything.</p>
|
[
{
"answer_id": 223778,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 2,
"selected": false,
"text": "<p>In Page_Load, set Server.ScriptTimeout to a value that works for you. Measured in seconds I believe.</p>\n"
},
{
"answer_id": 230916,
"author": "Godeke",
"author_id": 28006,
"author_profile": "https://Stackoverflow.com/users/28006",
"pm_score": 4,
"selected": false,
"text": "<p>You need to update a metabase setting on IIS6 and later. The key is \" AspMaxRequestEntityAllowed\" and is expressed in bytes. I highly recommend the Metabase Explorer to make the change, wading through the XML at %systemroot%\\system32\\inetserv\\metabase.xml is possible though.</p>\n\n<p>Metabase Explorer: <a href=\"http://support.microsoft.com/kb/840671\" rel=\"noreferrer\">http://support.microsoft.com/kb/840671</a></p>\n\n<p>Hmmm, perhaps I'm barking up the wrong tree... you wouldn't be doing 5 MB files if that wasn't already adjusted. </p>\n\n<p>Another stab at it: see your web.config:</p>\n\n<pre><code><system.web>\n <httpRuntime maxRequestLength=\"10240\" executionTimeout=\"360\"/>\n</system.web>\n</code></pre>\n\n<p>Max request length is in kilobytes and execution timeout is in seconds.</p>\n"
},
{
"answer_id": 230936,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 1,
"selected": false,
"text": "<p>I think you may need to adjust the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.maxrequestlength.aspx\" rel=\"nofollow noreferrer\">MaxRequestLength</a></p>\n\n<p>Its in the Web.config I think by default its 4megs.</p>\n\n<p>The following would allow ~10 meg file:</p>\n\n<pre><code><httpRuntime maxRequestLength=\"10240\" />\n</code></pre>\n"
},
{
"answer_id": 333594,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Check the code of <a href=\"http://www.codeplex.com/VelodocXP\" rel=\"nofollow noreferrer\">Velodoc XP Edition</a>. It includes an upload streaming module, a resumable download handler and ASP.NET upload controls based on ASP.NET Ajax extensions and it is all open source.</p>\n\n<p>For more information check also <a href=\"http://www.memba.com\" rel=\"nofollow noreferrer\">www.memba.com</a> and <a href=\"http://www.velodoc.com\" rel=\"nofollow noreferrer\">www.velodoc.com</a>.</p>\n"
},
{
"answer_id": 3304300,
"author": "Carter Medlin",
"author_id": 324479,
"author_profile": "https://Stackoverflow.com/users/324479",
"pm_score": 2,
"selected": false,
"text": "<p>Place this in your web.config</p>\n\n<pre><code> <system.web>\n <httpRuntime executionTimeout=\"360\" maxRequestLength=\"100000\" />\n</code></pre>\n\n<p>That enables a 360 second timeout and 100,000 Kb of upload data at a time.</p>\n\n<p>If that doesn't work, run this command on your IIS server. (replace [IISWebsitename])</p>\n\n<pre><code>C:\\Windows\\System32\\inetsrv>appcmd set config \"[IISWebsitename]\" -section:requestFiltering -requestLimits.maxAllowedContentLength:100000000 -commitpath:apphost\n</code></pre>\n\n<p>That enables 100,000,000 bytes of upload data at a time.</p>\n"
},
{
"answer_id": 5213976,
"author": "Dooug",
"author_id": 647377,
"author_profile": "https://Stackoverflow.com/users/647377",
"pm_score": -1,
"selected": false,
"text": "<p>I solved this using PHP with HTML:</p>\n\n<ol>\n<li>I start a session</li>\n<li>enter a loop</li>\n<li>create a loop that reloads the page that does part of the job at a\ntime</li>\n<li>do until job is done</li>\n<li>the code inside the loop does a portion of the job</li>\n<li>increment a session variable to point to next part of the job</li>\n<li>reload the page using java script //this will restart the severs\npage timer</li>\n<li>loop</li>\n<li>load a page to report the job is done</li>\n</ol>\n"
},
{
"answer_id": 35169737,
"author": "omar nazzal",
"author_id": 4086690,
"author_profile": "https://Stackoverflow.com/users/4086690",
"pm_score": 1,
"selected": false,
"text": "<p>Open your Web.config file, and just below the <code><system.web></code> tag, add the following tag: </p>\n\n<p><code><httpRuntime \n executionTimeout=\"90\" \n maxRequestLength=\"4096\" \n useFullyQualifiedRedirectUrl=\"false\" \n minFreeThreads=\"8\" \n minLocalRequestFreeThreads=\"4\" \n appRequestQueueLimit=\"100\" \n enableVersionHeader=\"true\"\n /></code></p>\n\n<p>Now, just take a look at the maxRequestLength=\"4096\" attribute of the <code><httpRuntime></code> tag. As you may have realized, all you need to do is change the value to some other value of your choice (8192 for 8 Mb, 16384 for 16 Mb, 65536 for 64 Mb, and so on...).</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
I have a nice little file upload control I wrote for ASP.NET webforms that utilizes an IFrame and ASP.NET AJAX.
However, on large uploads, the browser times out before it can finish posting the form.
Is there a way I can increase this?
I'm not really interesting in alternative solutions, so don't suggest changing the entire thing out please. It works good for <5 meg uploads, I'd just like to get it up to about 8mb.
EDIT: Setting the timeout in Page\_Load didn't appear to change anything.
|
You need to update a metabase setting on IIS6 and later. The key is " AspMaxRequestEntityAllowed" and is expressed in bytes. I highly recommend the Metabase Explorer to make the change, wading through the XML at %systemroot%\system32\inetserv\metabase.xml is possible though.
Metabase Explorer: <http://support.microsoft.com/kb/840671>
Hmmm, perhaps I'm barking up the wrong tree... you wouldn't be doing 5 MB files if that wasn't already adjusted.
Another stab at it: see your web.config:
```
<system.web>
<httpRuntime maxRequestLength="10240" executionTimeout="360"/>
</system.web>
```
Max request length is in kilobytes and execution timeout is in seconds.
|
223,771 |
<p>So, no matter what I seem to do, I cannot seem to avoid having Dev C++ spew out numerous Multiple Definition errors as a result of me including the same header file in multiple source code files in the same project. I'd strongly prefer to avoid having to dump all my source code into one file and only include the header once, as that's going to make my file very long and difficult to manage.</p>
<p>Essentially, this is what's going on:</p>
<pre><code>#ifndef _myheader_h
#define _myheader_h
typedef struct MYSTRUCT{
int blah;
int blah2; } MYSTRUCT;
MYSTRUCT Job_Grunt;
MYSTRUCT *Grunt = &Job_Grunt;
MYSTRUCT Job_Uruk;
MYSTRUCT *Uruk = &Job_Grunt;
int Other_data[100];
void load_jobs();
#endif
</code></pre>
<p>Example Cpp File (They pretty much all look something like this):</p>
<pre><code>#include "myheader.h"
void load_jobs(){
Grunt->blah = 1;
Grunt->blah2 = 14;
Uruk->blah = 2;
Uruk->blah2 = 15;
return; }
</code></pre>
<p>Bear in mind that I have about 5 cpp files that include this one header, each one dealing with a different type of struct found in the header file. In this example there was only the one struct containing a couple of members, when there are about 4-6 different structs with many more members in the actual header file. All the files I've included it in follow the same formula as you see in this example here.</p>
<p>Now I understand that the header guard only stops each individual cpp file from including the header file more than once. What would seem to be happening is that when the compiler reads the include at the start of each cpp, it defines the header file all over again, which is causing it to spit out lines and lines of:</p>
<pre><code>Multiple Definition of Uruk, first defined here
Multiple Definition of Job_Uruk, first defined here
Multiple Definition of Grunt, first defined here
Multiple Definition of Job_Grunt, first defined here
Multiple Definition of Other_data, first defined here
</code></pre>
<p>I'll see a set of this for just about every cpp file in the project which includes the header. I've tried moving the definitions of the struct and the struct variables to the cpp files, but then the other cpp files cannot see them or work with them, which is very important as I need all files in the project to be able to work with these structs.</p>
<p>But the single most confusing part about this problem requires a little more explanation:</p>
<p>The way I'm setting up these multiple files in this project is identical to the book I'm working with, All In One Game Programming by John S. Harbour. I ran into the exact same problems when I created the files for example projects in the book which called for one header included by multiple cpps in the same project.</p>
<p>I could type them out, word for word from the book, and I do mean word for word...<br>
and I'd get the series of MD errors for every cpp in the project. </p>
<p>If I loaded the example project from the CD included with the book, it would compile and run without a problem, allthough the files themselves, as well as the project options, were by all appearances identical to the ones I had created.</p>
<p>If I created my own project file, and simply added the source and header files for the example project from the CD, this, too, would also compile and run, though I can find no difference between those and mine.</p>
<p>So then, I tried making my own project file, then creating the blank source and header files and adding them to it, and then filling them by copying and pasting their contents from the files on the CD they were meant to correspond to(the same ones that had worked).
And sure enough, I'd get the same thing...lines and lines of MD error messages.</p>
<p>I'm absolutely baffled. I've repeated all these methods multiple times, and am certain I'm not mistyping or miscopying the code. There just seems to be something about the premade files themselves; some configuration setting or something else I'm missing entirely...that will cause them to compile correctly while the files I make myself won't.</p>
|
[
{
"answer_id": 223785,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 3,
"selected": false,
"text": "<p>You need to define your variables as extern in the header file, and then define them in a cpp file as well. i.e.:</p>\n\n<pre><code>extern MYSTRUCT Job_Grunt;\n</code></pre>\n\n<p>in your header file, and then in a cpp file in your project declare them normally. </p>\n\n<p>The header file is only for definitions, when you instantiate a variable in the header file it will try to instantiate it every time the header is included in your project. Using the extern directive tells the compiler that it's just a definition and that the instantiation is done somewhere else.</p>\n"
},
{
"answer_id": 223798,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 5,
"selected": false,
"text": "<p>Since you're declaring those variables in the header file, and including the header file in each C++ file, each C++ file has its own copy of them.</p>\n\n<p>The usual way around this is to <em>not</em> declare any variables within header files. Instead, declare them in a single C++ file, and declare them as <code>extern</code> in all the other files that you might need them in.</p>\n\n<p>Another way I've handled this before, which some people might consider unpleasant... declare them in the header file, like this:</p>\n\n<pre><code>#ifdef MAINFILE\n #define EXTERN\n#else\n #define EXTERN extern\n#endif\n\nEXTERN MYSTRUCT Job_Grunt;\nEXTERN MYSTRUCT *Grunt = &Job_Grunt;\nEXTERN MYSTRUCT Job_Uruk;\nEXTERN MYSTRUCT *Uruk = &Job_Uruk;\n</code></pre>\n\n<p>Then, in <em>one</em> of your C++ files, add a...</p>\n\n<pre><code>#define MAINFILE\n</code></pre>\n\n<p>...before your <code>#include</code> lines. That will take care of everything, and is (in my personal opinion) a lot nicer than having to redeclare all of the variables in every file.</p>\n\n<p>Of course, the <em>real</em> solution is not to use global variables at all, but when you're just starting out that's hard to achieve.</p>\n"
},
{
"answer_id": 223803,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 0,
"selected": false,
"text": "<p>To expand on what Gerald said, the header is defining an instance of the struct (which is not what you want). This is causing each compilation unit (cpp file) which includes the header to get its own version of the struct instance, which causes problems at link time.</p>\n\n<p>As Gerald said, you need to define a reference to the struct (using 'extern') in the header, and have one cpp file in your project which instantiates the instance.</p>\n"
},
{
"answer_id": 223813,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": false,
"text": "<p>When you define a variable, the compiler sets aside memory for that variable. By defining a variable in the header file, and including that file into all your source files, you are defining the same variable in multiple files.</p>\n\n<p>Putting the keyword <code>extern</code> before a variable definition will tell the compiler that this variable has already been defined somewhere, and that you are only <em>declaring</em> (i.e. naming) the variable so that other files can use it.</p>\n\n<p>So in your header file you should make all your definitions <em>forward declarations</em> by adding the <code>extern</code> keyword.</p>\n\n<pre><code>extern MYSTRUCT Job_Grunt;\nextern MYSTRUCT *Grunt;\nextern MYSTRUCT Job_Uruk;\nextern MYSTRUCT *Uruk;\n\nextern int Other_data[100];\n</code></pre>\n\n<p>And then in <strong>one</strong> (and only one) of your source files, define the variables normally:</p>\n\n<pre><code>MYSTRUCT Job_Grunt;\nMYSTRUCT *Grunt = &Job_Grunt;\nMYSTRUCT Job_Uruk;\nMYSTRUCT *Uruk = &Job_Grunt;\n\nint Other_data[100];\n</code></pre>\n"
},
{
"answer_id": 223815,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": -1,
"selected": false,
"text": "<p>GCC 3.4 and up supports <code>#pragma once</code>. Just put <code>#pragma once</code> at the top of your code instead of using include guards. This may or may not be more successful, but it's worth a shot. And no, this is not (always) precisely equivalent to an include guard.</p>\n"
},
{
"answer_id": 224152,
"author": "Steve Fallows",
"author_id": 18882,
"author_profile": "https://Stackoverflow.com/users/18882",
"pm_score": 3,
"selected": false,
"text": "<p>While most of the other answers are correct as to why you are seeing multiple definitions, the terminology is imprecise. Understanding declaration vs. definition is the key to your problem.</p>\n\n<p>A declaration announces the existence of an item but does not cause instantiation. Hence the extern statements are declarations - not definitions.</p>\n\n<p>A definition creates an instance of the defined item. Hence if you have a definition in a header it is instantiated in each .cpp file, resulting in the multiple definitions. Definitions are also declarations - i.e. no separate declaration is needed if for instance the scope of the item is limited to one .cpp file.</p>\n\n<p>Note: the use of the word instantiation here really only applies to data items.</p>\n"
},
{
"answer_id": 765016,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I too was having this problem some time back. Let me try to explain what solved it.\nI had a global.h file which had all declaration and need to be included in every cpp file. Instead of including it in every .cpp, I included it in .h. All my \".h\" files I have added the lines #ifndef and #define and ended with #endif. This solved MD problem. Hope this works for you too.</p>\n"
},
{
"answer_id": 1032419,
"author": "jbatista",
"author_id": 36145,
"author_profile": "https://Stackoverflow.com/users/36145",
"pm_score": 0,
"selected": false,
"text": "<p>This is what worked for me: linking the sources into separate libraries. (My problem was not with creating a program but one/many libraries.) I then linked (successfully) one program with the <em>two</em> libraries I created.</p>\n\n<p>I had two sets of functions (with one depending on the other) in the same source file, and declared in the same single header file. Then I tried to separate the two function sets in two header+source files.</p>\n\n<p>I tried with both #pragma once and include guards with #ifndef ... #define ... #endif. I also defined the variables and functions as extern in the header files.</p>\n\n<p>As Steve Fallows pointed out, the problem isn't with the compilation but rather with linkage. In my particular problem, I could get away with having two sets of functions, each in its own source file, compiling and then linking into <em>two separate libraries</em>.</p>\n\n<pre><code>g++ -o grandfather.o -c grandfather.cpp\ng++ -o father.o -c father.cpp\ng++ -fPIC -shared -o libgf.so grandfather.o\ng++ -fPIC -shared -o libfather.so father.o\n</code></pre>\n\n<p>This forces me to link my programs with both libgf.so and libfather.so. In my particular case it makes no difference; but otherwise I couldn't get them to work together.</p>\n"
},
{
"answer_id": 6263012,
"author": "bpamuk",
"author_id": 787152,
"author_profile": "https://Stackoverflow.com/users/787152",
"pm_score": 2,
"selected": false,
"text": "<p>I also received this error for a function defined in a .h file. The header file was not intended to make declarations of a class but definitions of some functions which are needed in various places in a project. (I may confuse the \"definition\" and \"declaration\" usages, but i hope i could give the main idea.) When I put an \"inline\" keyword just before the definition of the function which give the \"multiple definitions\" error, the error is avoided. </p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
So, no matter what I seem to do, I cannot seem to avoid having Dev C++ spew out numerous Multiple Definition errors as a result of me including the same header file in multiple source code files in the same project. I'd strongly prefer to avoid having to dump all my source code into one file and only include the header once, as that's going to make my file very long and difficult to manage.
Essentially, this is what's going on:
```
#ifndef _myheader_h
#define _myheader_h
typedef struct MYSTRUCT{
int blah;
int blah2; } MYSTRUCT;
MYSTRUCT Job_Grunt;
MYSTRUCT *Grunt = &Job_Grunt;
MYSTRUCT Job_Uruk;
MYSTRUCT *Uruk = &Job_Grunt;
int Other_data[100];
void load_jobs();
#endif
```
Example Cpp File (They pretty much all look something like this):
```
#include "myheader.h"
void load_jobs(){
Grunt->blah = 1;
Grunt->blah2 = 14;
Uruk->blah = 2;
Uruk->blah2 = 15;
return; }
```
Bear in mind that I have about 5 cpp files that include this one header, each one dealing with a different type of struct found in the header file. In this example there was only the one struct containing a couple of members, when there are about 4-6 different structs with many more members in the actual header file. All the files I've included it in follow the same formula as you see in this example here.
Now I understand that the header guard only stops each individual cpp file from including the header file more than once. What would seem to be happening is that when the compiler reads the include at the start of each cpp, it defines the header file all over again, which is causing it to spit out lines and lines of:
```
Multiple Definition of Uruk, first defined here
Multiple Definition of Job_Uruk, first defined here
Multiple Definition of Grunt, first defined here
Multiple Definition of Job_Grunt, first defined here
Multiple Definition of Other_data, first defined here
```
I'll see a set of this for just about every cpp file in the project which includes the header. I've tried moving the definitions of the struct and the struct variables to the cpp files, but then the other cpp files cannot see them or work with them, which is very important as I need all files in the project to be able to work with these structs.
But the single most confusing part about this problem requires a little more explanation:
The way I'm setting up these multiple files in this project is identical to the book I'm working with, All In One Game Programming by John S. Harbour. I ran into the exact same problems when I created the files for example projects in the book which called for one header included by multiple cpps in the same project.
I could type them out, word for word from the book, and I do mean word for word...
and I'd get the series of MD errors for every cpp in the project.
If I loaded the example project from the CD included with the book, it would compile and run without a problem, allthough the files themselves, as well as the project options, were by all appearances identical to the ones I had created.
If I created my own project file, and simply added the source and header files for the example project from the CD, this, too, would also compile and run, though I can find no difference between those and mine.
So then, I tried making my own project file, then creating the blank source and header files and adding them to it, and then filling them by copying and pasting their contents from the files on the CD they were meant to correspond to(the same ones that had worked).
And sure enough, I'd get the same thing...lines and lines of MD error messages.
I'm absolutely baffled. I've repeated all these methods multiple times, and am certain I'm not mistyping or miscopying the code. There just seems to be something about the premade files themselves; some configuration setting or something else I'm missing entirely...that will cause them to compile correctly while the files I make myself won't.
|
Since you're declaring those variables in the header file, and including the header file in each C++ file, each C++ file has its own copy of them.
The usual way around this is to *not* declare any variables within header files. Instead, declare them in a single C++ file, and declare them as `extern` in all the other files that you might need them in.
Another way I've handled this before, which some people might consider unpleasant... declare them in the header file, like this:
```
#ifdef MAINFILE
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN MYSTRUCT Job_Grunt;
EXTERN MYSTRUCT *Grunt = &Job_Grunt;
EXTERN MYSTRUCT Job_Uruk;
EXTERN MYSTRUCT *Uruk = &Job_Uruk;
```
Then, in *one* of your C++ files, add a...
```
#define MAINFILE
```
...before your `#include` lines. That will take care of everything, and is (in my personal opinion) a lot nicer than having to redeclare all of the variables in every file.
Of course, the *real* solution is not to use global variables at all, but when you're just starting out that's hard to achieve.
|
223,788 |
<p>In a previous question, I asked about various ORM libraries. It turns out Kohana looks very clean yet functional for the purposes of ORM. I already have an MVC framework that I am working in though. If I don't want to run it as a framework, what is the right fileset to include to just give me the DB and ORM base class files?</p>
<p>Update:</p>
<p>I jumped in and started looking at the ORM source code.. One thing was immediately confusing to me.. all the ORM classes have the class name appended with _CORE i.e. ORM_Core ORM_Iterator_Core, but the code everywhere is extending the ORM class. Problem is, I've searched the whole code base 6 different ways, and I've never seen a plain ORM class def nor an ORM interface def or anything.. Could someone enlighten me on where that magic happens?</p>
|
[
{
"answer_id": 224341,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 2,
"selected": false,
"text": "<p>It turns out that Kohana uses magic class loading so that if a defined class with an _Core extention doesn't exist as a class </p>\n\n<p>i.e. ORM_Core exists, but ORM doesn't, so Kohana will magically define an ORM class\nSince the package uses 100% magic class loading.</p>\n\n<p>In case anyone is interested, I'm documenting my finds here so everyone can find it later:</p>\n\n<pre><code>From Kohana.php in the system directory:\n\n<-- snip if ($extension = self::find_file($type, self::$configuration['core']['extension_prefix'].$class))\n{\n// Load the extension\nrequire $extension;\n}\nelseif ($suffix !== 'Core' AND class_exists($class.'_Core', FALSE))\n{\n// Class extension to be evaluated\n$extension = 'class '.$class.' extends '.$class.'_Core { }';\n-->\n\n<-- snip\n\n// Transparent class extensions are handled using eval. This is\n// a disgusting hack, but it gets the job done.\neval($extension);\n\n-->\n</code></pre>\n\n<p>So it does an eval.. </p>\n"
},
{
"answer_id": 224666,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 4,
"selected": true,
"text": "<p>Why not just have a </p>\n\n<pre><code>class ORM extends ORM_Core {} \n</code></pre>\n\n<p>somewhere in your code? This removes the need to use any of the loader code.</p>\n\n<p>You'll also need Kohana_Exception, the Database library (and appropraite driver), Kohana::config(), Kohana::auto_load(), Kohana::log() methods (search Database.php for those). </p>\n\n<p>Kohana is a great MVC framework, but not really designed to be taken apart in chunks like that. You may want to also investigate <a href=\"http://www.doctrine-project.org/\" rel=\"noreferrer\">Doctrine</a>, another ORM for PHP (that IS designed to be stand-alone)</p>\n"
},
{
"answer_id": 315976,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Zak, check Maintainable framework's ORM. <a href=\"http://framework.maintainable.com/mvc/3_model.php#c3.7\" rel=\"nofollow noreferrer\">http://framework.maintainable.com/mvc/3_model.php#c3.7</a>\nRead thoroughly, I am sure you'll like it. I post this in more detail in:\n<a href=\"https://stackoverflow.com/questions/220229/what-is-the-easiest-to-use-orm-framework-for-php\">What is the easiest to use ORM framework for PHP?</a></p>\n"
},
{
"answer_id": 810152,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://obando.com.ve/2009/04/29/modelado-orm-rapido-y-facil/\" rel=\"nofollow noreferrer\">http://obando.com.ve/2009/04/29/modelado-orm-rapido-y-facil/</a></p>\n\n<p>That is all your need!! </p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2112692/"
] |
In a previous question, I asked about various ORM libraries. It turns out Kohana looks very clean yet functional for the purposes of ORM. I already have an MVC framework that I am working in though. If I don't want to run it as a framework, what is the right fileset to include to just give me the DB and ORM base class files?
Update:
I jumped in and started looking at the ORM source code.. One thing was immediately confusing to me.. all the ORM classes have the class name appended with \_CORE i.e. ORM\_Core ORM\_Iterator\_Core, but the code everywhere is extending the ORM class. Problem is, I've searched the whole code base 6 different ways, and I've never seen a plain ORM class def nor an ORM interface def or anything.. Could someone enlighten me on where that magic happens?
|
Why not just have a
```
class ORM extends ORM_Core {}
```
somewhere in your code? This removes the need to use any of the loader code.
You'll also need Kohana\_Exception, the Database library (and appropraite driver), Kohana::config(), Kohana::auto\_load(), Kohana::log() methods (search Database.php for those).
Kohana is a great MVC framework, but not really designed to be taken apart in chunks like that. You may want to also investigate [Doctrine](http://www.doctrine-project.org/), another ORM for PHP (that IS designed to be stand-alone)
|
223,800 |
<p><a href="http://www.php.net/features.safe-mode" rel="noreferrer">open_basedir</a> limits the files that can be opened by PHP within a directory-tree.</p>
<p>I am storing several class libraries and configuration files outside of my web root directory. This way the web server does not make them publicly accessible. However when I try to include them from my application I get an open_basedir restriction error like this:</p>
<blockquote>
<p>Warning: realpath()
[function.realpath]: open_basedir
restriction in effect.
File(/var/www/vhosts/domain.tld/zend/application)
is not within the allowed path(s):
(/var/www/vhosts/domain.tld/httpdocs:/tmp)
in
/var/www/vhosts/domain.tld/httpdocs/index.php
on line 5</p>
</blockquote>
<p>My web root is here:</p>
<pre><code>/var/www/vhosts/domain.tld/httpdocs
</code></pre>
<p>My libraries and configuration directory are here:</p>
<pre><code>/var/www/vhosts/domain.tld/zend
</code></pre>
<p>What would be the best workaround to relax the open_basedir restriction so that the the directory tree under the domain folder becomes available to my application? I have a number of domains that I want to do this with, and I'm also obviously wary of creating security vulnerabilities.</p>
<p>Note: I am using CentOS, Apache, Plesk, and I have root ssh access to the server. And though this doesn't apply to Zend Framework directly, I am using it in this instance. So here is the inclusion from Zend's bootstrap:</p>
<pre><code>define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../zend/application/'));
set_include_path(APPLICATION_PATH . '/../zend/library' . PATH_SEPARATOR . get_include_path());
</code></pre>
|
[
{
"answer_id": 223820,
"author": "user27987",
"author_id": 27987,
"author_profile": "https://Stackoverflow.com/users/27987",
"pm_score": 2,
"selected": false,
"text": "<p>add the paths you need to access to (/var/www/vhosts/domain.tld/zend) to your open_basedir directive (you can specify several paths using the path separator ':' or ';' in windows)</p>\n\n<p>note that the values in the open_basedir are prefixes, which means that anything under the /var/www/vhosts/domain.tld/zend will be accessible</p>\n"
},
{
"answer_id": 223834,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 5,
"selected": true,
"text": "<p>You can also do this easily on a per-directory basis using the Apache (assuming this is your web server) configuration file (e.g. httpd.conf)</p>\n\n<pre><code><Directory /var/www/vhosts/domain.tld/httpdocs>\nphp_admin_value open_basedir \"/var/www/vhosts/domain.tld/httpdocs:/var/www/vhosts/domain.tld/zend\"\n</Directory>\n</code></pre>\n\n<p>you can also completely remove the restriction with</p>\n\n<pre><code><Directory /var/www/vhosts/domain.tld/httpdocs>\nphp_admin_value open_basedir none\n</Directory>\n</code></pre>\n"
},
{
"answer_id": 22965914,
"author": "Igor Parra",
"author_id": 333061,
"author_profile": "https://Stackoverflow.com/users/333061",
"pm_score": 1,
"selected": false,
"text": "<p>In Parallels Plesk Panel (e.g. 1and1) you can do it in the PHP panel settings:</p>\n\n<p><img src=\"https://i.stack.imgur.com/gcRFS.png\" alt=\"enter image description here\"></p>\n\n<p>here:</p>\n\n<p><img src=\"https://i.stack.imgur.com/c2AJK.png\" alt=\"enter image description here\"></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9290/"
] |
[open\_basedir](http://www.php.net/features.safe-mode) limits the files that can be opened by PHP within a directory-tree.
I am storing several class libraries and configuration files outside of my web root directory. This way the web server does not make them publicly accessible. However when I try to include them from my application I get an open\_basedir restriction error like this:
>
> Warning: realpath()
> [function.realpath]: open\_basedir
> restriction in effect.
> File(/var/www/vhosts/domain.tld/zend/application)
> is not within the allowed path(s):
> (/var/www/vhosts/domain.tld/httpdocs:/tmp)
> in
> /var/www/vhosts/domain.tld/httpdocs/index.php
> on line 5
>
>
>
My web root is here:
```
/var/www/vhosts/domain.tld/httpdocs
```
My libraries and configuration directory are here:
```
/var/www/vhosts/domain.tld/zend
```
What would be the best workaround to relax the open\_basedir restriction so that the the directory tree under the domain folder becomes available to my application? I have a number of domains that I want to do this with, and I'm also obviously wary of creating security vulnerabilities.
Note: I am using CentOS, Apache, Plesk, and I have root ssh access to the server. And though this doesn't apply to Zend Framework directly, I am using it in this instance. So here is the inclusion from Zend's bootstrap:
```
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../zend/application/'));
set_include_path(APPLICATION_PATH . '/../zend/library' . PATH_SEPARATOR . get_include_path());
```
|
You can also do this easily on a per-directory basis using the Apache (assuming this is your web server) configuration file (e.g. httpd.conf)
```
<Directory /var/www/vhosts/domain.tld/httpdocs>
php_admin_value open_basedir "/var/www/vhosts/domain.tld/httpdocs:/var/www/vhosts/domain.tld/zend"
</Directory>
```
you can also completely remove the restriction with
```
<Directory /var/www/vhosts/domain.tld/httpdocs>
php_admin_value open_basedir none
</Directory>
```
|
223,804 |
<p>Suppose you have two models, User and City, joined by a third model CityPermission:</p>
<pre><code>class CityPermission < ActiveRecord::Base
belongs_to :city
belongs_to :user
end
class City < ActiveRecord::Base
has_many :city_permissions
has_many :users, :through => :city_permissions
end
class User < ActiveRecord::Base
has_many :city_permissions
has_many :cities, :through => :city_permissions
end
</code></pre>
<p>Currently, I create the join table, and the index for the table, using the following migration code snippet:</p>
<pre><code>create_table :city_permissions do |t|
t.integer :user_id, :city_id
t.other_fields ...
end
add_index(:city_permissions, :user_id)
add_index(:city_permissions, :city_id)
</code></pre>
<p>Are these the optimal indexes to create? Will these indexes allow quick access back and forth through the join table, as well as quick lookups within the table itself, or is there some other better way? To restate this a bit differently, will these indexes, given <code>city</code> and <code>user</code> are instance variables of class City and User, allow <code>city.users</code>, <code>city.city_permissions</code>, <code>user.cities</code>, and <code>user.city_permissions</code> to all perform equally well?</p>
|
[
{
"answer_id": 223812,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 3,
"selected": true,
"text": "<p>Looks good to me.</p>\n\n<p>The joins generated should just be on either the PK IDs of the entity tables, or on the FK IDs in the join table - which are both indexes.</p>\n\n<p>Probably would be good to look at the generated ActiveRecord SQL and compare it against the indexes.</p>\n\n<p>Depending on what database you're on you could then run that SQL through an Explain plan (or whatever tool exists, I'm thinking Oracle here)</p>\n\n<p>To simplify your code, you could look at using <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001114\" rel=\"nofollow noreferrer\"><code>has_and_belongs_to_many</code></a> as well. That would let you get rid of the CityPermission object (unless you want to use that to store data in itself)</p>\n"
},
{
"answer_id": 223818,
"author": "jcnnghm",
"author_id": 4767,
"author_profile": "https://Stackoverflow.com/users/4767",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the SQL that ActiveRecord generates for <code>user.cities</code>:</p>\n\n<pre><code>SELECT `cities`.* FROM `cities` INNER JOIN city_permissions ON (cities.id = city_permissions.city_id) WHERE (city_permissions.user_id = 1 )\n</code></pre>\n\n<p>EXPLAIN results below:</p>\n\n<pre><code>+----+-------------+------------------+--------+---------------------------------------------------------------------+-----------------------------------+---------+-------------------------------------------------+------+-------------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+------------------+--------+---------------------------------------------------------------------+-----------------------------------+---------+-------------------------------------------------+------+-------------+\n| 1 | SIMPLE | city_permissions | ref | index_city_permissions_on_user_id,index_city_permissions_on_city_id | index_city_permissions_on_user_id | 5 | const | 1 | Using where |\n| 1 | SIMPLE | cities | eq_ref | PRIMARY | PRIMARY | 4 | barhopolis_development.city_permissions.city_id | 1 | |\n+----+-------------+------------------+--------+---------------------------------------------------------------------+-----------------------------------+---------+-------------------------------------------------+------+-------------+\n</code></pre>\n\n<p>And here's the SQL that ActiveRecord generates for <code>user.city_permissions</code>:</p>\n\n<pre><code>SELECT * FROM `city_permissions` WHERE (`city_permissions`.user_id = 1)\n</code></pre>\n\n<p>With the EXPLAIN results for that query:</p>\n\n<pre><code>+----+-------------+------------------+------+-----------------------------------+-----------------------------------+---------+-------+------+-------------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+------------------+------+-----------------------------------+-----------------------------------+---------+-------+------+-------------+\n| 1 | SIMPLE | city_permissions | ref | index_city_permissions_on_user_id | index_city_permissions_on_user_id | 5 | const | 1 | Using where |\n+----+-------------+------------------+------+-----------------------------------+-----------------------------------+---------+-------+------+-------------+\n</code></pre>\n\n<p>Looks like it <strong>is indeed working correctly</strong>. From the MySQL Manual:</p>\n\n<h2>eq_ref</h2>\n\n<p>One row is read from this table for each combination of rows from the previous tables. Other than the system and const types, this is the best possible join type. It is used when all parts of an index are used by the join and the index is a PRIMARY KEY or UNIQUE index.</p>\n\n<h2>ref</h2>\n\n<p>All rows with matching index values are read from this table for each combination of rows from the previous tables. ref is used if the join uses only a leftmost prefix of the key or if the key is not a PRIMARY KEY or UNIQUE index (in other words, if the join cannot select a single row based on the key value). If the key that is used matches only a few rows, this is a good join type.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4767/"
] |
Suppose you have two models, User and City, joined by a third model CityPermission:
```
class CityPermission < ActiveRecord::Base
belongs_to :city
belongs_to :user
end
class City < ActiveRecord::Base
has_many :city_permissions
has_many :users, :through => :city_permissions
end
class User < ActiveRecord::Base
has_many :city_permissions
has_many :cities, :through => :city_permissions
end
```
Currently, I create the join table, and the index for the table, using the following migration code snippet:
```
create_table :city_permissions do |t|
t.integer :user_id, :city_id
t.other_fields ...
end
add_index(:city_permissions, :user_id)
add_index(:city_permissions, :city_id)
```
Are these the optimal indexes to create? Will these indexes allow quick access back and forth through the join table, as well as quick lookups within the table itself, or is there some other better way? To restate this a bit differently, will these indexes, given `city` and `user` are instance variables of class City and User, allow `city.users`, `city.city_permissions`, `user.cities`, and `user.city_permissions` to all perform equally well?
|
Looks good to me.
The joins generated should just be on either the PK IDs of the entity tables, or on the FK IDs in the join table - which are both indexes.
Probably would be good to look at the generated ActiveRecord SQL and compare it against the indexes.
Depending on what database you're on you could then run that SQL through an Explain plan (or whatever tool exists, I'm thinking Oracle here)
To simplify your code, you could look at using [`has_and_belongs_to_many`](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001114) as well. That would let you get rid of the CityPermission object (unless you want to use that to store data in itself)
|
223,810 |
<p>Ruby on Rails has a lot of ways to generate JavaScript. Particularly when it comes to Ajax. Unfortunately, there are a few problems that I often see with the JavaScript that it generates. </p>
<ul>
<li><p>Rails typically uses inline event handling.</p>
<pre><code><a onclick="somejavascript(); return false;" />
</code></pre>
<p>This is generally frowned upon, as it's mixing behavior in with the XHTML. </p></li>
<li><p>The generated JavaScript also relies heavily on Prototype. Personally, I prefer jQuery. </p></li>
<li><p>In my experience, the attitude with a lot of Rails developers has been to write as much of the code in Ruby as possible. The final step is to generate some very procedural and repetitive JavaScript. Often, this code ends up being very inflexible and difficult to debug.</p></li>
</ul>
<p>So, my question is: how much JavaScript do you write manually for your projects and how much of it is generated server-side with Rails/Ruby? Or is there a happy medium where you get the benefits of both? With a subquestion: if you write a lot of the JavaScript manually, what techniques do you use to fit it into the MVC model?</p>
|
[
{
"answer_id": 223849,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 0,
"selected": false,
"text": "<p>Let Rails do as much as possible. Then when you have problems, start rewriting it with hand coded versions.</p>\n"
},
{
"answer_id": 223876,
"author": "MatthewFord",
"author_id": 21596,
"author_profile": "https://Stackoverflow.com/users/21596",
"pm_score": 0,
"selected": false,
"text": "<p>none, use jquery if need be. Ajax and ie js bugs are hard to trackdown</p>\n"
},
{
"answer_id": 223899,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 2,
"selected": false,
"text": "<p>I used to work in Symfony (a Rails clone) and at first, we used a lot of Javascript helpers. Client requirements led us (me!) to have to write a lot of code the helpers just couldn't generate. I eventually came to the conclusion that I prefer not to use helpers <strong>at all.</strong></p>\n\n<p>Progressive enhancement is the way to go, in my opinion. Generate standards-friendly HTML that works without JavaScript enabled, then pile on the fancy functionality on document ready.</p>\n\n<p>By the way, I've also switched from Prototype to jQuery and have no desire to switch back! In my opinion, jQuery is better suited to progressive enhancement.</p>\n"
},
{
"answer_id": 224118,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 4,
"selected": true,
"text": "<p>If you prefer jQuery you can use the <a href=\"http://ennerchi.com/projects/jrails\" rel=\"nofollow noreferrer\">jQuery on Rails Project</a>. A drop in to replace Prototype with jQuery.</p>\n\n<p>Some of what Rails does with Javascript generation is good and some is bad. In the bad instances, write it yourself and keep it unobtrusive. At any given time you're uncomfortable with the Javascript Rails generates, you can go ahead and write it yourself. </p>\n\n<p>And be sure to check out this great intro to <a href=\"http://www.railsenvy.com/2008/1/3/unobtrusive-javascript\" rel=\"nofollow noreferrer\">unobtrusive Javascript</a> that was done with Rails in mind.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22291/"
] |
Ruby on Rails has a lot of ways to generate JavaScript. Particularly when it comes to Ajax. Unfortunately, there are a few problems that I often see with the JavaScript that it generates.
* Rails typically uses inline event handling.
```
<a onclick="somejavascript(); return false;" />
```
This is generally frowned upon, as it's mixing behavior in with the XHTML.
* The generated JavaScript also relies heavily on Prototype. Personally, I prefer jQuery.
* In my experience, the attitude with a lot of Rails developers has been to write as much of the code in Ruby as possible. The final step is to generate some very procedural and repetitive JavaScript. Often, this code ends up being very inflexible and difficult to debug.
So, my question is: how much JavaScript do you write manually for your projects and how much of it is generated server-side with Rails/Ruby? Or is there a happy medium where you get the benefits of both? With a subquestion: if you write a lot of the JavaScript manually, what techniques do you use to fit it into the MVC model?
|
If you prefer jQuery you can use the [jQuery on Rails Project](http://ennerchi.com/projects/jrails). A drop in to replace Prototype with jQuery.
Some of what Rails does with Javascript generation is good and some is bad. In the bad instances, write it yourself and keep it unobtrusive. At any given time you're uncomfortable with the Javascript Rails generates, you can go ahead and write it yourself.
And be sure to check out this great intro to [unobtrusive Javascript](http://www.railsenvy.com/2008/1/3/unobtrusive-javascript) that was done with Rails in mind.
|
223,832 |
<p>What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise?</p>
<h3>Example</h3>
<pre><code>void Test()
{
OnlyHexInString("123ABC"); // Returns true
OnlyHexInString("123def"); // Returns true
OnlyHexInString("123g"); // Returns false
}
bool OnlyHexInString(string text)
{
// Most efficient algorithm to check each digit in C# 2.0 goes here
}
</code></pre>
|
[
{
"answer_id": 223843,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 3,
"selected": false,
"text": "<p>I use <code>Int32.TryParse()</code> to do this. <a href=\"http://msdn.microsoft.com/en-us/library/zf50za27(VS.80).aspx\" rel=\"nofollow noreferrer\">Here's the MSDN page on it</a>.</p>\n"
},
{
"answer_id": 223847,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 1,
"selected": false,
"text": "<p>In terms of <em>programmer time</em>, it's probably best to call your platform's string-to-integer parsing function (such as Java's <em>Integer.parseInt(str, base)</em>), and see if you get an exception. If you want to write it yourself, and potentially be more time/space-efficient...</p>\n\n<p>Most efficient I suppose would be a lookup table on each character. You would have a 2^8 (or 2^16 for Unicode)-entry array of booleans, each of which would be <em>true</em> if it is a valid hex character, or <em>false</em> if not. The code would look something like (in Java, sorry ;-):</p>\n\n<pre><code>boolean lut[256]={false,false,true,........}\n\nboolean OnlyHexInString(String text)\n{\n for(int i = 0; i < text.size(); i++)\n if(!lut[text.charAt(i)])\n return false;\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 223852,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 5,
"selected": false,
"text": "<p>You can do a <a href=\"https://msdn.microsoft.com/en-us/library/zc2x2b1h%28v=vs.110%29.aspx\" rel=\"noreferrer\">TryParse</a> on the string to test if the string in its entirity is a hexadecimal number.</p>\n\n<p>If it's a particularly long string, you could take it in chunks and loop through it.</p>\n\n<pre><code>// string hex = \"bacg123\"; Doesn't parse\n// string hex = \"bac123\"; Parses\nstring hex = \"bacg123\";\nlong output;\nlong.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out output);\n</code></pre>\n"
},
{
"answer_id": 223854,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 6,
"selected": false,
"text": "<p>Something like this:</p>\n\n<p>(I don't know C# so I'm not sure how to loop through the chars of a string.)</p>\n\n<pre><code>loop through the chars {\n bool is_hex_char = (current_char >= '0' && current_char <= '9') ||\n (current_char >= 'a' && current_char <= 'f') ||\n (current_char >= 'A' && current_char <= 'F');\n\n if (!is_hex_char) {\n return false;\n }\n}\n\nreturn true;\n</code></pre>\n\n<p><strong>Code for Logic Above</strong></p>\n\n<pre><code>private bool IsHex(IEnumerable<char> chars)\n{\n bool isHex; \n foreach(var c in chars)\n {\n isHex = ((c >= '0' && c <= '9') || \n (c >= 'a' && c <= 'f') || \n (c >= 'A' && c <= 'F'));\n\n if(!isHex)\n return false;\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 223857,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 7,
"selected": true,
"text": "<pre><code>public bool OnlyHexInString(string test)\n{\n // For C-style hex notation (0xFF) you can use @\"\\A\\b(0[xX])?[0-9a-fA-F]+\\b\\Z\"\n return System.Text.RegularExpressions.Regex.IsMatch(test, @\"\\A\\b[0-9a-fA-F]+\\b\\Z\");\n}\n</code></pre>\n"
},
{
"answer_id": 223872,
"author": "marcj",
"author_id": 23940,
"author_profile": "https://Stackoverflow.com/users/23940",
"pm_score": 0,
"selected": false,
"text": "<p>This could be done with regular expressions, which are an efficient way of checking if a string matches a particular pattern. </p>\n\n<p>A possible regular expression for a hex digit would be [A-Ha-h0-9]<em>, some implementations even have a specific code for hex digits, e.g. [[:xdigit:]]</em>.</p>\n"
},
{
"answer_id": 5781008,
"author": "Robert Bernstein",
"author_id": 280622,
"author_profile": "https://Stackoverflow.com/users/280622",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a LINQ version of <a href=\"https://stackoverflow.com/users/813/yjerem\">yjerem</a>'s solution above:</p>\n\n<pre><code>private static bool IsValidHexString(IEnumerable<char> hexString)\n{\n return hexString.Select(currentCharacter =>\n (currentCharacter >= '0' && currentCharacter <= '9') ||\n (currentCharacter >= 'a' && currentCharacter <= 'f') ||\n (currentCharacter >= 'A' && currentCharacter <= 'F')).All(isHexCharacter => isHexCharacter);\n}\n</code></pre>\n"
},
{
"answer_id": 8024808,
"author": "Kumba",
"author_id": 482691,
"author_profile": "https://Stackoverflow.com/users/482691",
"pm_score": 3,
"selected": false,
"text": "<p>Posting a VB.NET version of <a href=\"https://stackoverflow.com/q/223832/482691#223854\">Jeremy's answer</a>, because I came here while looking for such a version. Should be easy to convert it to C#.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>''' <summary>\n''' Checks if a string contains ONLY hexadecimal digits.\n''' </summary>\n''' <param name=\"str\">String to check.</param>\n''' <returns>\n''' True if string is a hexadecimal number, False if otherwise.\n''' </returns>\nPublic Function IsHex(ByVal str As String) As Boolean\n If String.IsNullOrWhiteSpace(str) Then _\n Return False\n\n Dim i As Int32, c As Char\n\n If str.IndexOf(\"0x\") = 0 Then _\n str = str.Substring(2)\n\n While (i < str.Length)\n c = str.Chars(i)\n\n If Not (((c >= \"0\"c) AndAlso (c <= \"9\"c)) OrElse\n ((c >= \"a\"c) AndAlso (c <= \"f\"c)) OrElse\n ((c >= \"A\"c) AndAlso (c <= \"F\"c))) _\n Then\n Return False\n Else\n i += 1\n End If\n End While\n\n Return True\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 8024875,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": false,
"text": "<p>In terms of performance the fastest is likely to simply enumerate the characters and do a simple comparison check.</p>\n\n<pre><code>bool OnlyHexInString(string text) {\n for (var i = 0; i < text.Length; i++) {\n var current = text[i];\n if (!(Char.IsDigit(current) || (current >= 'a' && current <= 'f'))) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>To truly know which method is fastest though you'll need to do some profiling. </p>\n"
},
{
"answer_id": 11143213,
"author": "Prueba",
"author_id": 1472819,
"author_profile": "https://Stackoverflow.com/users/1472819",
"pm_score": -1,
"selected": false,
"text": "<p>Now, only</p>\n\n<pre><code>if (IsHex(text)) {\n return true;\n} else {\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 14543208,
"author": "Jordan Morris",
"author_id": 970673,
"author_profile": "https://Stackoverflow.com/users/970673",
"pm_score": 2,
"selected": false,
"text": "<p>A regular expression is not very efficient at the best of times. The most efficient will be using a plain <code>for</code> loop to search through the characters of the string, and break on the first invalid one found.</p>\n\n<p>However, it can be done very succinctly with <a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query\" rel=\"nofollow\">LINQ</a>:</p>\n\n<pre><code>bool isHex = \n myString.ToCharArray().Any(c => !\"0123456789abcdefABCDEF\".Contains(c));\n</code></pre>\n\n<p>I cannot vouch for the efficiency, since LINQ is LINQ, but Any() should have a pretty well-optimised compilation scheme.</p>\n"
},
{
"answer_id": 18452890,
"author": "jcallejas",
"author_id": 2434242,
"author_profile": "https://Stackoverflow.com/users/2434242",
"pm_score": 2,
"selected": false,
"text": "<pre><code> //Another workaround, although RegularExpressions is the best solution\n boolean OnlyHexInString(String text)\n {\n for(int i = 0; i < text.size(); i++)\n if( !Uri.IsHexDigit(text.charAt(i)) )\n return false;\n return true;\n }\n</code></pre>\n"
},
{
"answer_id": 24353176,
"author": "WaltZie",
"author_id": 1865608,
"author_profile": "https://Stackoverflow.com/users/1865608",
"pm_score": 0,
"selected": false,
"text": "<p>You can Extend string and char using someting like this:</p>\n\n<pre><code> public static bool IsHex(this string value)\n { return value.All(c => c.IsHex()); }\n\n public static bool IsHex(this char c)\n {\n c = Char.ToLower(c);\n if (Char.IsDigit(c) || (c >= 'a' && c <= 'f'))\n return true;\n else\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 29439742,
"author": "Kapé",
"author_id": 465942,
"author_profile": "https://Stackoverflow.com/users/465942",
"pm_score": 4,
"selected": false,
"text": "<p>What about just: </p>\n\n<p><code>bool isHex = text.All(\"0123456789abcdefABCDEF\".Contains);</code></p>\n\n<p>This basically says: check if all chars in the <code>text</code> string do exist in the valid hex values string.</p>\n\n<p>Which is the simplest still readable solution to me.</p>\n\n<p>(don't forget to add <code>using System.Linq;</code>)</p>\n\n<p><strong>EDIT:</strong><br>\nJust noticed that <a href=\"https://msdn.microsoft.com/en-us/library/bb548541(v=vs.90).aspx\" rel=\"noreferrer\"><code>Enumerable.All()</code></a> is only available since .NET 3.5.</p>\n"
},
{
"answer_id": 30921419,
"author": "Manfred",
"author_id": 5025083,
"author_profile": "https://Stackoverflow.com/users/5025083",
"pm_score": 1,
"selected": false,
"text": "<p>An easy solution without regular expressions is:</p>\n\n<p>VB.NET:</p>\n\n<pre><code>Public Function IsHexString(value As String) As Boolean\n Dim hx As String = \"0123456789ABCDEF\"\n For Each c As Char In value.ToUpper\n If Not hx.Contains(c) Then Return False\n Next\n Return True\nEnd Function\n</code></pre>\n\n<p>Or in C#</p>\n\n<pre><code>public bool IsHexString(string value)\n{\n string hx = \"0123456789ABCDEF\";\n foreach (char c in value.ToUpper()) {\n if (!hx.Contains(c))\n return false;\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 31455671,
"author": "Barak Rosenfeld",
"author_id": 4274727,
"author_profile": "https://Stackoverflow.com/users/4274727",
"pm_score": 0,
"selected": false,
"text": "<p>I use this method:</p>\n\n<pre><code>public static bool IsHex(this char c)\n{\n return (c >= '0' && c <= '9') ||\n (c >= 'a' && c <= 'f') ||\n (c >= 'A' && c <= 'F');\n}\n</code></pre>\n"
},
{
"answer_id": 43493548,
"author": "Rosdi Kasim",
"author_id": 193634,
"author_profile": "https://Stackoverflow.com/users/193634",
"pm_score": 0,
"selected": false,
"text": "<p>And this as C# extension method...</p>\n\n<pre><code>public static class StringExtensions\n{\n public static bool IsHexString(this string str)\n {\n foreach (var c in str)\n {\n var isHex = ((c >= '0' && c <= '9') ||\n (c >= 'a' && c <= 'f') ||\n (c >= 'A' && c <= 'F'));\n\n if (!isHex)\n {\n return false;\n }\n }\n\n return true;\n }\n\n //bonus, verify whether a string can be parsed as byte[]\n public static bool IsParseableToByteArray(this string str)\n {\n return IsHexString(str) && str.Length % 2 == 0;\n }\n}\n</code></pre>\n\n<p>Use it like so...</p>\n\n<pre><code>if(\"08c9b54d1099e73d121c4200168f252e6e75d215969d253e074a9457d0401cc6\".IsHexString())\n{\n //returns true...\n}\n</code></pre>\n"
},
{
"answer_id": 43844931,
"author": "Rahbek",
"author_id": 3326779,
"author_profile": "https://Stackoverflow.com/users/3326779",
"pm_score": 0,
"selected": false,
"text": "<p>I made this solution to come around this issue. Check that the Request string is not null before executing.</p>\n\n<pre><code>for (int i = 0; i < Request.Length; i += 2)\n if (!byte.TryParse(string.Join(\"\", Request.Skip(i).Take(2)), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)) return false;\n</code></pre>\n"
},
{
"answer_id": 47568218,
"author": "Ismet Tanrikulu",
"author_id": 7249379,
"author_profile": "https://Stackoverflow.com/users/7249379",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static bool HexInCardUID(string test)\n {\n if (test.Trim().Length != 14)\n return false;\n for (int i = 0; i < test.Length; i++)\n if (!Uri.IsHexDigit(Convert.ToChar(test.Substring(i, 1))))\n return false;\n return true;\n }**strong text**\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise?
### Example
```
void Test()
{
OnlyHexInString("123ABC"); // Returns true
OnlyHexInString("123def"); // Returns true
OnlyHexInString("123g"); // Returns false
}
bool OnlyHexInString(string text)
{
// Most efficient algorithm to check each digit in C# 2.0 goes here
}
```
|
```
public bool OnlyHexInString(string test)
{
// For C-style hex notation (0xFF) you can use @"\A\b(0[xX])?[0-9a-fA-F]+\b\Z"
return System.Text.RegularExpressions.Regex.IsMatch(test, @"\A\b[0-9a-fA-F]+\b\Z");
}
```
|
223,833 |
<p>This is what I have, which works in IE7, but not in Firefox:</p>
<pre><code>@media screen { @import 'screen.css'; }
</code></pre>
<p>It works outside of the @media block in Firefox:</p>
<pre><code>@import 'screen.css';
</code></pre>
<p><strong>UPDATE:</strong> </p>
<p>This works:</p>
<pre><code>@media screen {
.yui-d3f
{
border: 1px solid #999;
height: 250px;
}
}
</code></pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 223949,
"author": "Peter Coulton",
"author_id": 117,
"author_profile": "https://Stackoverflow.com/users/117",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, so Firefox doesn't like the method I chose, favouring:</p>\n\n<pre><code>@import 'stylesheet.css' media_type;\n</code></pre>\n\n<p>But IE7 doesn't understand this method, but this could be good:</p>\n\n<pre><code>@import 'firefox-screen.css' screen;\n@media screen { @import 'IE7-screen.css'; }\n</code></pre>\n"
},
{
"answer_id": 224278,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 4,
"selected": true,
"text": "<p>Firefox is following the CSS2 specification, while IE is playing fast and loose, as it were.</p>\n\n<p>The exact reason is that <code>@import</code> directives must be the first directives after the optional <code>@charset</code> directive. They cannot appear inside of any block. If you want an <code>@import</code> to apply to only one media type, specify that after the imported URI.</p>\n\n<p>Here is the pertinent section of the CSS2 specification: <a href=\"http://www.w3.org/TR/CSS2/cascade.html#at-import\" rel=\"noreferrer\" title=\"6.3 The @import rule\">6.3 The <code>@import</code> rule</a>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117/"
] |
This is what I have, which works in IE7, but not in Firefox:
```
@media screen { @import 'screen.css'; }
```
It works outside of the @media block in Firefox:
```
@import 'screen.css';
```
**UPDATE:**
This works:
```
@media screen {
.yui-d3f
{
border: 1px solid #999;
height: 250px;
}
}
```
What am I missing?
|
Firefox is following the CSS2 specification, while IE is playing fast and loose, as it were.
The exact reason is that `@import` directives must be the first directives after the optional `@charset` directive. They cannot appear inside of any block. If you want an `@import` to apply to only one media type, specify that after the imported URI.
Here is the pertinent section of the CSS2 specification: [6.3 The `@import` rule](http://www.w3.org/TR/CSS2/cascade.html#at-import "6.3 The @import rule").
|
223,844 |
<p>I can't find a definitive answer. Since C# 2.0 you've been able to declare</p>
<pre><code>int? i = 125;
</code></pre>
<p>as shorthand for</p>
<pre><code>Nullable<int> i = Nullable<int>(123);
</code></pre>
<p>I recall reading somewhere that VB.NET did not allow this shortcut. But low and behold, I tried it in VS 2008 today and it works.</p>
<p>Does anyone know whether it's been this way since .NET 2.0 or was this added later?</p>
|
[
{
"answer_id": 223848,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know the history, but yes it was a VS 2008 enhancement.</p>\n"
},
{
"answer_id": 224110,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 5,
"selected": true,
"text": "<p>System.Nullable was introduced in .Net 2.0 and is available to VB <em>as a generic type</em>. You just cannot use the nullable syntax. So in VS 2005 you can do:</p>\n\n<pre><code>Dim x as Nullable(of Integer)\n</code></pre>\n\n<p>I don't know if null equivalence and boxing works for nullables in VB 2005, but I would suspect that the answer is yes since the .Net team made a change to the 2.0 CLR to accomplish boxing with nullables. I would imagine VB leverages this.</p>\n\n<p>In 2008, you can obviously just do:</p>\n\n<pre><code>Dim x as Integer?\n</code></pre>\n"
},
{
"answer_id": 302422,
"author": "user23462",
"author_id": 23462,
"author_profile": "https://Stackoverflow.com/users/23462",
"pm_score": 2,
"selected": false,
"text": "<p>it works in VB 2005 (dotnet 2.0) but it's ugly.</p>\n\n<p>You can't use it like a normal variable, I thought it might work like an Object type but it doesn't.</p>\n\n<p>Rather than this:</p>\n\n<pre><code>dim oInt as object\n\ndim i as integer\n\nif oInt is nothing then \n\n msgbox(\"int is null\")\nelse\n\n i = cint(oInt)\n\nend if\n</code></pre>\n\n<p>you have this.</p>\n\n<pre><code>Dim oInt as nullable(of integer)\n\ndim i as integer\n\nif oInt.HasValue = false then \n\n msgbox(\"int is null\")\n\nelse\n\n i = oInt.Value\n\nend if\n</code></pre>\n\n<p>The problem here is that if your variable is null and you happen to invoke the Value property it barfs up an unhandled exception.</p>\n\n<p>so for instance, my favorite one is this.</p>\n\n<pre><code>AddParamToSQLCmd(sqlCmd, \"@SomeID\", SqlDbType.Int, 0, ParameterDirection.Input, iif(oInt.HasValue, oInt.Value, DBNull.value))\n</code></pre>\n\n<p>Will result in an runtime error when your Supposed Nullable value is null!!! </p>\n\n<p>so here's nullable(of integer) vs Object code</p>\n\n<p>nullable(of integer) </p>\n\n<pre><code>if oInt.HasValue then \n AddParamToSQLCmd(sqlCmd, \"@SomeID\", SqlDbType.Int, 0, ParameterDirection.Input, oInt.Value)\nelse\n AddParamToSQLCmd(sqlCmd, \"@SomeID\", SqlDbType.Int, 0, ParameterDirection.Input, dbnull.value)\nend if\n</code></pre>\n\n<p>Object</p>\n\n<pre><code>AddParamToSQLCmd(sqlCmd, \"@SomeID\", SqlDbType.Int, 0, ParameterDirection.Input, oInt)\n</code></pre>\n"
},
{
"answer_id": 964606,
"author": "Christian Hayter",
"author_id": 115413,
"author_profile": "https://Stackoverflow.com/users/115413",
"pm_score": 1,
"selected": false,
"text": "<p>IIRC, nullable types were introduced in .NET 2.0 at a very late stage. The C# compiler team managed to cram in more language support for them than the VB.NET team did. The VB.NET team more or less caught up in VS2008. That's why you can, for example, use the == operator to compare nullables in C# 2.0 whereas in VB.NET you had to put up with the Nullable.Equals() method. Grrr.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
I can't find a definitive answer. Since C# 2.0 you've been able to declare
```
int? i = 125;
```
as shorthand for
```
Nullable<int> i = Nullable<int>(123);
```
I recall reading somewhere that VB.NET did not allow this shortcut. But low and behold, I tried it in VS 2008 today and it works.
Does anyone know whether it's been this way since .NET 2.0 or was this added later?
|
System.Nullable was introduced in .Net 2.0 and is available to VB *as a generic type*. You just cannot use the nullable syntax. So in VS 2005 you can do:
```
Dim x as Nullable(of Integer)
```
I don't know if null equivalence and boxing works for nullables in VB 2005, but I would suspect that the answer is yes since the .Net team made a change to the 2.0 CLR to accomplish boxing with nullables. I would imagine VB leverages this.
In 2008, you can obviously just do:
```
Dim x as Integer?
```
|
223,866 |
<p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But… that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
|
[
{
"answer_id": 223904,
"author": "dalyons",
"author_id": 16925,
"author_profile": "https://Stackoverflow.com/users/16925",
"pm_score": 2,
"selected": false,
"text": "<p>Using multiline, commented regexs can mitigate the maintainance problem somewhat. Try and avoid the one line super regex!</p>\n\n<p>Also, consider breaking the regex down into individual tasks, one for each 'thing' you want to get. eg.</p>\n\n<pre><code>visitor = text.find(/Visitor:(.*)/)\noperator = text.find(/Operator:(.*)/)\nbody = text.find(/whatever....)\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>text.match(/Visitor:(.*)\\nOperator:(.*)...whatever to giant regex/m) do\n visitor = $1\n operator = $2\n etc.\nend\n</code></pre>\n\n<p>Then it makes it easy to change how any particular item is parsed. As far as parsing through a file with many \"chat blocks\", just have a single simple regex that matches a single chat block, iterate over the text and pass the match data from this to your group of other matchers.</p>\n\n<p>This will obviously affect performance, but unless you processing <em>enormous</em> files i wouldnt worry.</p>\n"
},
{
"answer_id": 223925,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>No and in fact, for the specific type of task you describe, I doubt there's a \"cleaner\" way to do it than regular expressions. It looks like your files have embedded line breaks so typically what we'll do here is make the line your unit of decomposition, applying per-line regexes. Meanwhile, you create a small state machine and use regex matches to trigger transitions in that state machine. This way you know where you are in the file, and what types of character data you can expect. Also, consider using named capture groups and loading the regexes from an external file. That way if the format of your transcript changes, it's a simple matter of tweaking the regex, rather than writing new parse-specific code.</p>\n"
},
{
"answer_id": 224014,
"author": "Greg",
"author_id": 13009,
"author_profile": "https://Stackoverflow.com/users/13009",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://pyparsing.wikispaces.com/\" rel=\"nofollow noreferrer\">Build a parser</a>? I can't decide if your data is regular enough for that, but it might be worth looking into.</p>\n"
},
{
"answer_id": 224033,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Just a quick post, I've only glanced at your transcript example but I've recently also had to look into text parsing and hoped to avoid going the route of hand rolled parsing. I did happen across <a href=\"http://www.complang.org/ragel/\" rel=\"nofollow noreferrer\">Ragel</a> which I've only started to get my head around but it's looking to be pretty useful.</p>\n"
},
{
"answer_id": 224052,
"author": "user21714",
"author_id": 21714,
"author_profile": "https://Stackoverflow.com/users/21714",
"pm_score": 3,
"selected": false,
"text": "<p>You might want to consider a full parser generator. </p>\n\n<p>Regular expressions are good for searching text for small substrings but they're woefully under-powered if you're really interested in parsing the entire file into meaningful data. </p>\n\n<p>They are especially insufficient if the context of the substring is important.</p>\n\n<p>Most people throw regexes at everything because that's what they know. They've never learned any parser generating tools and they end up coding a lot of the production rule composition and semantic action handling that you can get for free with a parser generator. </p>\n\n<p>Regexes are great and all, but if you need a parser they're no substitute.</p>\n"
},
{
"answer_id": 224073,
"author": "Jauder Ho",
"author_id": 26366,
"author_profile": "https://Stackoverflow.com/users/26366",
"pm_score": 2,
"selected": false,
"text": "<p>Consider using Ragel <a href=\"https://www.colm.net/open-source/ragel/\" rel=\"nofollow noreferrer\">https://www.colm.net/open-source/ragel/</a></p>\n<p>That's what powers mongrel under the hood. Parsing a string multiple times is going to slow things down dramatically.</p>\n"
},
{
"answer_id": 224344,
"author": "JDrago",
"author_id": 29060,
"author_profile": "https://Stackoverflow.com/users/29060",
"pm_score": 4,
"selected": false,
"text": "<p>With Perl, you can use <a href=\"http://search.cpan.org/perldoc?Parse::RecDescent\" rel=\"nofollow noreferrer\">Parse::RecDescent</a></p>\n\n<p>It is simple, and your grammar will be maintainable later on.</p>\n"
},
{
"answer_id": 226711,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I have used Paul McGuire's pyParsing class library and I continue to be impressed by it, in that it's well-documented, easy to get started, and the rules are easy to tweak and maintain. BTW, the rules are expressed in your python code. It certainly appears that the log file has enough regularity to parse each line as a stand-alone unit.</p>\n"
},
{
"answer_id": 1657561,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<p>Here's two parsers based on <a href=\"http://www.acooke.org/lepl/\" rel=\"nofollow noreferrer\"><code>lepl</code></a> parser generator library. They both produce the same result.</p>\n\n<pre><code>from pprint import pprint\nfrom lepl import AnyBut, Drop, Eos, Newline, Separator, SkipTo, Space\n\n# field = name , \":\" , value\nname, value = AnyBut(':\\n')[1:,...], AnyBut('\\n')[::'n',...] \nwith Separator(~Space()[:]):\n field = name & Drop(':') & value & ~(Newline() | Eos()) > tuple\n\nheader_start = SkipTo('Chat Transcript' & Newline()[2])\nheader = ~header_start & field[1:] > dict\nserver_message = Drop('* ') & AnyBut('\\n')[:,...] & ~Newline() > 'Server'\nconversation = (server_message | field)[1:] > list\nfooter_start = 'Visitor Details' & Newline() & '-'*15 & Newline()\nfooter = ~footer_start & field[1:] > dict\nchat_log = header & ~Newline() & conversation & ~Newline() & footer\n\npprint(chat_log.parse_file(open('chat.log')))\n</code></pre>\n\n<h3>Stricter Parser</h3>\n\n<pre><code>from pprint import pprint\nfrom lepl import And, Drop, Newline, Or, Regexp, SkipTo\n\ndef Field(name, value=Regexp(r'\\s*(.*?)\\s*?\\n')):\n \"\"\"'name , \":\" , value' matcher\"\"\"\n return name & Drop(':') & value > tuple\n\nFields = lambda names: reduce(And, map(Field, names))\n\nheader_start = SkipTo(Regexp(r'^Chat Transcript$') & Newline()[2])\nheader_fields = Fields(\"Visitor Operator Company Started Finished\".split())\nserver_message = Regexp(r'^\\* (.*?)\\n') > 'Server'\nfooter_fields = Fields((\"Your Name, Your Question, IP Address, \"\n \"Host Name, Referrer, Browser/OS\").split(', '))\n\nwith open('chat.log') as f:\n # parse header to find Visitor and Operator's names\n headers, = (~header_start & header_fields > dict).parse_file(f)\n # only Visitor, Operator and Server may take part in the conversation\n message = reduce(Or, [Field(headers[name])\n for name in \"Visitor Operator\".split()])\n conversation = (message | server_message)[1:]\n messages, footers = ((conversation > list)\n & Drop('\\nVisitor Details\\n---------------\\n')\n & (footer_fields > dict)).parse_file(f)\n\npprint((headers, messages, footers))\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>({'Company': 'Initech',\n 'Finished': '16 Oct 2008 9:45:44',\n 'Operator': 'Milton',\n 'Started': '16 Oct 2008 9:13:58',\n 'Visitor': 'Random Website Visitor'},\n [('Random Website Visitor',\n 'Where do i get the cover sheet for the TPS report?'),\n ('Server',\n 'There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click \"Send\" button'),\n ('Server',\n 'Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.'),\n ('Milton', 'Y-- Excuse me. You-- I believe you have my stapler?'),\n ('Random Website Visitor', 'I really just need the cover sheet, okay?'),\n ('Milton',\n \"it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...\"),\n ('Random Website Visitor', 'oh i found it, thanks anyway.'),\n ('Server',\n 'Random Website Visitor is now off-line and may not reply. Currently in room: Milton.'),\n ('Milton', \"Well, Ok. But… that's the last straw.\"),\n ('Server',\n 'Milton has left the conversation. Currently in room: room is empty.')],\n {'Browser/OS': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)',\n 'Host Name': '255.255.255.255',\n 'IP Address': '255.255.255.255',\n 'Referrer': 'Unknown',\n 'Your Name': 'Random Website Visitor',\n 'Your Question': 'Where do i get the cover sheet for the TPS report?'})\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2178/"
] |
I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used.
I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.
The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.
The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.
Here is an example of a transcript file:
```
Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But… that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
```
|
No and in fact, for the specific type of task you describe, I doubt there's a "cleaner" way to do it than regular expressions. It looks like your files have embedded line breaks so typically what we'll do here is make the line your unit of decomposition, applying per-line regexes. Meanwhile, you create a small state machine and use regex matches to trigger transitions in that state machine. This way you know where you are in the file, and what types of character data you can expect. Also, consider using named capture groups and loading the regexes from an external file. That way if the format of your transcript changes, it's a simple matter of tweaking the regex, rather than writing new parse-specific code.
|
223,875 |
<p>I am starting to develop an Eclipse plugin (technically, an OSGi plugin) and one of the first problems I've run into is that I can't seem to control the commons-logging output as I normally would.</p>
<p>I've included the commons-logging package in the plugin dependencies, and indeed, when I log something (at INFO or higher severity) it is logged to the console. However, I can't seem to log at any lower level (such as DEBUG or TRACE).</p>
<p>I have specified a log4j.properties file, and it is on the classpath (for the runtime, just as the commons-logging package is) but none of the settings in that properties file have any impact on the behavior of the logger.</p>
<p>Here's the log4j.properties file:</p>
<pre><code># Log4j Logging levels, in order of decreasing importance are:
# FATAL, ERROR, WARN, INFO, DEBUG, TRACE
#
# Root logger option
log4j.rootLogger=ERROR,stdout
#,LOGFILE
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %r (%l) %t%n - %m%n
</code></pre>
<p>What do I need to do so that I can actually control the output of the logger?</p>
<p>Here are some sample output messages, in the hopes that the formatting may coincide with a default for java.util.logging, or provide other hints to someone:</p>
<pre><code>Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start
SEVERE: fatal_message
Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start
WARNING: warn_message
Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start
INFO: info_message
</code></pre>
<p><strong>Update:</strong></p>
<p>I have now tried various combinations of:</p>
<ul>
<li>org.osgi.service.log.LogService et al.</li>
<li><a href="http://www.slf4j.org/" rel="noreferrer">slf4j</a></li>
<li><a href="http://logging.apache.org/log4j/" rel="noreferrer">Log4J</a></li>
<li><a href="http://commons.apache.org/logging/" rel="noreferrer">Commons-logging</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/package-summary.html" rel="noreferrer">java.util.logging</a></li>
</ul>
<p>and I can <em>only</em> get DEBUG, or lower, level messages to appear if I am running OSGi manually from a prompt (which is impractical for what I am developing). Furthermore, I can't effect any other type of logging configuration via various properties files. Everything I try in that regard seems to be overridden by an eclipse setting.</p>
<p>I've also tried putting various config files for the above libraries in numerous places, including as plug-in fragments attached to their respective libraries as suggested <a href="http://www.eclipsezone.com/eclipse/forums/t99588.html" rel="noreferrer">here</a>, and still, the same result happens.</p>
<p>I've implemented a custom LogListener, and traced the entire path of a log message (as well as I know how, anyway) with System.out.println's, and debug messages <em>are</em> present right up until they are output by whatever underlying logging API I'm using, then they disappear.</p>
|
[
{
"answer_id": 224821,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "<p>This is not an actual answer to your question, but you might find some clues in this <a href=\"http://ekkescorner.wordpress.com/blog-series/osgi-apps/\" rel=\"nofollow noreferrer\">set of articles by ekke</a>.</p>\n\n<p>I suppose you read already \"<a href=\"http://www.eclipsezone.com/eclipse/forums/t99588.html\" rel=\"nofollow noreferrer\">Using Log4J in Eclipse Equinox/OSGi</a>\":</p>\n\n<p>Did you launch an osgi session in a console mode ?</p>\n\n<pre><code>java -jar org.eclipse.osgi_3.3.0.v20070530.jar -console -noExit -clean\n</code></pre>\n\n<p>That way, you may test log4j in a pure osgi environment and check if it works there.</p>\n\n<p>Let use know if you find a solution (publish it as an answer), and I will vote it up ;)</p>\n"
},
{
"answer_id": 235532,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 6,
"selected": true,
"text": "<p>3 days later...</p>\n\n<p>I found the problem! There were two things I needed to do, first off, there was a problem with one MANIFEST.MF file:</p>\n\n<p>I had the following in the MANIFEST.MF for one bundle:</p>\n\n<pre><code>Bundle-ClassPath: lib/jena.jar,\n .,\n org.apache.log4j-1.2.12.jar,\n lib/google-collect-snapshot.jar\nImport-Package: com.acme.client.translation,\n com.acme.translation.interfaces,\n com.acme.shared.osgi,\n com.acme.utilities\n</code></pre>\n\n<p>That <em>should</em> have been this:</p>\n\n<pre><code>Bundle-ClassPath: lib/jena.jar,\n .,\n lib/google-collect-snapshot.jar\nImport-Package: com.acme.client.translation,\n com.acme.client.translation.interfaces,\n com.acme.shared.osgi,\n com.acme.utilities,\n org.apache.log4j\n</code></pre>\n\n<p>The key difference is that the log4j was being used as a package, when it should have been used as a bundle. (I had a log4j jar in my lib dir from when I had expected Log4j to \"just work\" with OSGi.) The jar <em>does</em> work, sort-of. It evidently found some eclipse-level log4j configuration, and made use of that. Since it was just a jar (not a bundle) it didn't make use of any fragments that could specify a custom logging config, which leads us to the other thing that had to happen:</p>\n\n<p>I needed to set up a bundle fragment to specify the logging config. <a href=\"http://www.eclipsezone.com/eclipse/forums/t99588.html\" rel=\"nofollow noreferrer\">This link</a> from <a href=\"https://stackoverflow.com/questions/223875/logging-in-eclipseosgi-plugins#224821\">VonC</a> gave me the info to do that. That entailed doing a number of things, unfortunately, the package with the incorrect MANIFEST.MF still had the log4j jar specified in the Bundle-ClassPath, and that seems to override the Import-Package list.</p>\n\n<p>I finally figured out what was going on when I needed to log in another bundle (I had just given up at this point, and went back to using logs at the Warn level and higher.) This new bundle couldn't find a logging config! (so then I had three bundles running in the same OSGi environment, each with different log4j behavior -- one using my fragment settings, another using some random Eclipse logging settings, and finally the new bundle that didn't have any logging config.) Detailed comparisons of these three bundles revealed the difference in the Manifest.MF files, and now they all use the fragment bundle.</p>\n\n<p>I owe a <em>huge</em> thanks to the authors of much of <a href=\"http://www.eclipsezone.com/eclipse/forums/t99588.html\" rel=\"nofollow noreferrer\">Eclipse Zone</a>, <a href=\"https://stackoverflow.com/questions/223875/logging-in-eclipseosgi-plugins#224821\">VonC</a>, <a href=\"http://ekkes-corner.blogspot.com/2008/09/logging-in-osgi-enterprise-applications.html\" rel=\"nofollow noreferrer\">Ekkes</a>, and everyone in #eclipse on freenode for their help and patience :)</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
] |
I am starting to develop an Eclipse plugin (technically, an OSGi plugin) and one of the first problems I've run into is that I can't seem to control the commons-logging output as I normally would.
I've included the commons-logging package in the plugin dependencies, and indeed, when I log something (at INFO or higher severity) it is logged to the console. However, I can't seem to log at any lower level (such as DEBUG or TRACE).
I have specified a log4j.properties file, and it is on the classpath (for the runtime, just as the commons-logging package is) but none of the settings in that properties file have any impact on the behavior of the logger.
Here's the log4j.properties file:
```
# Log4j Logging levels, in order of decreasing importance are:
# FATAL, ERROR, WARN, INFO, DEBUG, TRACE
#
# Root logger option
log4j.rootLogger=ERROR,stdout
#,LOGFILE
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %r (%l) %t%n - %m%n
```
What do I need to do so that I can actually control the output of the logger?
Here are some sample output messages, in the hopes that the formatting may coincide with a default for java.util.logging, or provide other hints to someone:
```
Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start
SEVERE: fatal_message
Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start
WARNING: warn_message
Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start
INFO: info_message
```
**Update:**
I have now tried various combinations of:
* org.osgi.service.log.LogService et al.
* [slf4j](http://www.slf4j.org/)
* [Log4J](http://logging.apache.org/log4j/)
* [Commons-logging](http://commons.apache.org/logging/)
* [java.util.logging](http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/package-summary.html)
and I can *only* get DEBUG, or lower, level messages to appear if I am running OSGi manually from a prompt (which is impractical for what I am developing). Furthermore, I can't effect any other type of logging configuration via various properties files. Everything I try in that regard seems to be overridden by an eclipse setting.
I've also tried putting various config files for the above libraries in numerous places, including as plug-in fragments attached to their respective libraries as suggested [here](http://www.eclipsezone.com/eclipse/forums/t99588.html), and still, the same result happens.
I've implemented a custom LogListener, and traced the entire path of a log message (as well as I know how, anyway) with System.out.println's, and debug messages *are* present right up until they are output by whatever underlying logging API I'm using, then they disappear.
|
3 days later...
I found the problem! There were two things I needed to do, first off, there was a problem with one MANIFEST.MF file:
I had the following in the MANIFEST.MF for one bundle:
```
Bundle-ClassPath: lib/jena.jar,
.,
org.apache.log4j-1.2.12.jar,
lib/google-collect-snapshot.jar
Import-Package: com.acme.client.translation,
com.acme.translation.interfaces,
com.acme.shared.osgi,
com.acme.utilities
```
That *should* have been this:
```
Bundle-ClassPath: lib/jena.jar,
.,
lib/google-collect-snapshot.jar
Import-Package: com.acme.client.translation,
com.acme.client.translation.interfaces,
com.acme.shared.osgi,
com.acme.utilities,
org.apache.log4j
```
The key difference is that the log4j was being used as a package, when it should have been used as a bundle. (I had a log4j jar in my lib dir from when I had expected Log4j to "just work" with OSGi.) The jar *does* work, sort-of. It evidently found some eclipse-level log4j configuration, and made use of that. Since it was just a jar (not a bundle) it didn't make use of any fragments that could specify a custom logging config, which leads us to the other thing that had to happen:
I needed to set up a bundle fragment to specify the logging config. [This link](http://www.eclipsezone.com/eclipse/forums/t99588.html) from [VonC](https://stackoverflow.com/questions/223875/logging-in-eclipseosgi-plugins#224821) gave me the info to do that. That entailed doing a number of things, unfortunately, the package with the incorrect MANIFEST.MF still had the log4j jar specified in the Bundle-ClassPath, and that seems to override the Import-Package list.
I finally figured out what was going on when I needed to log in another bundle (I had just given up at this point, and went back to using logs at the Warn level and higher.) This new bundle couldn't find a logging config! (so then I had three bundles running in the same OSGi environment, each with different log4j behavior -- one using my fragment settings, another using some random Eclipse logging settings, and finally the new bundle that didn't have any logging config.) Detailed comparisons of these three bundles revealed the difference in the Manifest.MF files, and now they all use the fragment bundle.
I owe a *huge* thanks to the authors of much of [Eclipse Zone](http://www.eclipsezone.com/eclipse/forums/t99588.html), [VonC](https://stackoverflow.com/questions/223875/logging-in-eclipseosgi-plugins#224821), [Ekkes](http://ekkes-corner.blogspot.com/2008/09/logging-in-osgi-enterprise-applications.html), and everyone in #eclipse on freenode for their help and patience :)
|
223,878 |
<p>In my question <a href="https://stackoverflow.com/questions/184729/as-a-mockist-tdd-practitioner-should-i-mock-other-methods-in-the-same-class-as">As a “mockist” TDD practitioner, should I mock other methods in the same class as the method under test?</a>, <a href="https://stackoverflow.com/users/20487/avdi">Avdi</a> answered "Personally I think that mocking on self is almost always a code smell. It's testing the implementation rather than the behavior." He may be right, but often I can't distinguish between the implementation and the behavior.</p>
<p>I have another example (in Python-style pseudo-code) that may lead to helpful answers:</p>
<pre><code>class Consumer:
def spec_dirpath:
client = VCS.get_connection(self.vcs_client_name)
client.sync()
return client.dirpath()
def spec_filepath:
filepath = os.path.join(spec_dirpath(), self.spec_filename)
if not os.path.exists(filepath):
raise ConsumerException
return filepath
def get_components:
return Components.get_components_from_spec_file(self.spec_filepath())
</code></pre>
<p>The idea here is that the get_components method calls the spec_filepath method in order to get a path to a file that the get_components_from_spec_file Components class method will read a list of components from. The spec_filepath method in turn calls spec_dirpath, which syncs the directory containing the spec file from the VCS system and returns the path to that directory. (Try not to look for bugs in this code--it's pseudo-code, after all.)</p>
<p>I'm looking for advice on how to test these methods...</p>
<p>Testing spec_dirpath should be quite straightforward. I can mock the VCS class and have it return a mock object and confirm the appropriate methods are called (and that the spec_dirpath method returns what the mock's dirpath method returns).</p>
<p>But if I don't mock spec_dirpath while testing spec_filepath, how do I avoid duplicating the same test code from the spec_dirpath code in the spec_filepath test? And if I don't mock spec_filepath while testing get_components, how do I avoid duplicating the test code from both spec_filepath <em>and</em> spec_dirpath?</p>
|
[
{
"answer_id": 224821,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "<p>This is not an actual answer to your question, but you might find some clues in this <a href=\"http://ekkescorner.wordpress.com/blog-series/osgi-apps/\" rel=\"nofollow noreferrer\">set of articles by ekke</a>.</p>\n\n<p>I suppose you read already \"<a href=\"http://www.eclipsezone.com/eclipse/forums/t99588.html\" rel=\"nofollow noreferrer\">Using Log4J in Eclipse Equinox/OSGi</a>\":</p>\n\n<p>Did you launch an osgi session in a console mode ?</p>\n\n<pre><code>java -jar org.eclipse.osgi_3.3.0.v20070530.jar -console -noExit -clean\n</code></pre>\n\n<p>That way, you may test log4j in a pure osgi environment and check if it works there.</p>\n\n<p>Let use know if you find a solution (publish it as an answer), and I will vote it up ;)</p>\n"
},
{
"answer_id": 235532,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 6,
"selected": true,
"text": "<p>3 days later...</p>\n\n<p>I found the problem! There were two things I needed to do, first off, there was a problem with one MANIFEST.MF file:</p>\n\n<p>I had the following in the MANIFEST.MF for one bundle:</p>\n\n<pre><code>Bundle-ClassPath: lib/jena.jar,\n .,\n org.apache.log4j-1.2.12.jar,\n lib/google-collect-snapshot.jar\nImport-Package: com.acme.client.translation,\n com.acme.translation.interfaces,\n com.acme.shared.osgi,\n com.acme.utilities\n</code></pre>\n\n<p>That <em>should</em> have been this:</p>\n\n<pre><code>Bundle-ClassPath: lib/jena.jar,\n .,\n lib/google-collect-snapshot.jar\nImport-Package: com.acme.client.translation,\n com.acme.client.translation.interfaces,\n com.acme.shared.osgi,\n com.acme.utilities,\n org.apache.log4j\n</code></pre>\n\n<p>The key difference is that the log4j was being used as a package, when it should have been used as a bundle. (I had a log4j jar in my lib dir from when I had expected Log4j to \"just work\" with OSGi.) The jar <em>does</em> work, sort-of. It evidently found some eclipse-level log4j configuration, and made use of that. Since it was just a jar (not a bundle) it didn't make use of any fragments that could specify a custom logging config, which leads us to the other thing that had to happen:</p>\n\n<p>I needed to set up a bundle fragment to specify the logging config. <a href=\"http://www.eclipsezone.com/eclipse/forums/t99588.html\" rel=\"nofollow noreferrer\">This link</a> from <a href=\"https://stackoverflow.com/questions/223875/logging-in-eclipseosgi-plugins#224821\">VonC</a> gave me the info to do that. That entailed doing a number of things, unfortunately, the package with the incorrect MANIFEST.MF still had the log4j jar specified in the Bundle-ClassPath, and that seems to override the Import-Package list.</p>\n\n<p>I finally figured out what was going on when I needed to log in another bundle (I had just given up at this point, and went back to using logs at the Warn level and higher.) This new bundle couldn't find a logging config! (so then I had three bundles running in the same OSGi environment, each with different log4j behavior -- one using my fragment settings, another using some random Eclipse logging settings, and finally the new bundle that didn't have any logging config.) Detailed comparisons of these three bundles revealed the difference in the Manifest.MF files, and now they all use the fragment bundle.</p>\n\n<p>I owe a <em>huge</em> thanks to the authors of much of <a href=\"http://www.eclipsezone.com/eclipse/forums/t99588.html\" rel=\"nofollow noreferrer\">Eclipse Zone</a>, <a href=\"https://stackoverflow.com/questions/223875/logging-in-eclipseosgi-plugins#224821\">VonC</a>, <a href=\"http://ekkes-corner.blogspot.com/2008/09/logging-in-osgi-enterprise-applications.html\" rel=\"nofollow noreferrer\">Ekkes</a>, and everyone in #eclipse on freenode for their help and patience :)</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
In my question [As a “mockist” TDD practitioner, should I mock other methods in the same class as the method under test?](https://stackoverflow.com/questions/184729/as-a-mockist-tdd-practitioner-should-i-mock-other-methods-in-the-same-class-as), [Avdi](https://stackoverflow.com/users/20487/avdi) answered "Personally I think that mocking on self is almost always a code smell. It's testing the implementation rather than the behavior." He may be right, but often I can't distinguish between the implementation and the behavior.
I have another example (in Python-style pseudo-code) that may lead to helpful answers:
```
class Consumer:
def spec_dirpath:
client = VCS.get_connection(self.vcs_client_name)
client.sync()
return client.dirpath()
def spec_filepath:
filepath = os.path.join(spec_dirpath(), self.spec_filename)
if not os.path.exists(filepath):
raise ConsumerException
return filepath
def get_components:
return Components.get_components_from_spec_file(self.spec_filepath())
```
The idea here is that the get\_components method calls the spec\_filepath method in order to get a path to a file that the get\_components\_from\_spec\_file Components class method will read a list of components from. The spec\_filepath method in turn calls spec\_dirpath, which syncs the directory containing the spec file from the VCS system and returns the path to that directory. (Try not to look for bugs in this code--it's pseudo-code, after all.)
I'm looking for advice on how to test these methods...
Testing spec\_dirpath should be quite straightforward. I can mock the VCS class and have it return a mock object and confirm the appropriate methods are called (and that the spec\_dirpath method returns what the mock's dirpath method returns).
But if I don't mock spec\_dirpath while testing spec\_filepath, how do I avoid duplicating the same test code from the spec\_dirpath code in the spec\_filepath test? And if I don't mock spec\_filepath while testing get\_components, how do I avoid duplicating the test code from both spec\_filepath *and* spec\_dirpath?
|
3 days later...
I found the problem! There were two things I needed to do, first off, there was a problem with one MANIFEST.MF file:
I had the following in the MANIFEST.MF for one bundle:
```
Bundle-ClassPath: lib/jena.jar,
.,
org.apache.log4j-1.2.12.jar,
lib/google-collect-snapshot.jar
Import-Package: com.acme.client.translation,
com.acme.translation.interfaces,
com.acme.shared.osgi,
com.acme.utilities
```
That *should* have been this:
```
Bundle-ClassPath: lib/jena.jar,
.,
lib/google-collect-snapshot.jar
Import-Package: com.acme.client.translation,
com.acme.client.translation.interfaces,
com.acme.shared.osgi,
com.acme.utilities,
org.apache.log4j
```
The key difference is that the log4j was being used as a package, when it should have been used as a bundle. (I had a log4j jar in my lib dir from when I had expected Log4j to "just work" with OSGi.) The jar *does* work, sort-of. It evidently found some eclipse-level log4j configuration, and made use of that. Since it was just a jar (not a bundle) it didn't make use of any fragments that could specify a custom logging config, which leads us to the other thing that had to happen:
I needed to set up a bundle fragment to specify the logging config. [This link](http://www.eclipsezone.com/eclipse/forums/t99588.html) from [VonC](https://stackoverflow.com/questions/223875/logging-in-eclipseosgi-plugins#224821) gave me the info to do that. That entailed doing a number of things, unfortunately, the package with the incorrect MANIFEST.MF still had the log4j jar specified in the Bundle-ClassPath, and that seems to override the Import-Package list.
I finally figured out what was going on when I needed to log in another bundle (I had just given up at this point, and went back to using logs at the Warn level and higher.) This new bundle couldn't find a logging config! (so then I had three bundles running in the same OSGi environment, each with different log4j behavior -- one using my fragment settings, another using some random Eclipse logging settings, and finally the new bundle that didn't have any logging config.) Detailed comparisons of these three bundles revealed the difference in the Manifest.MF files, and now they all use the fragment bundle.
I owe a *huge* thanks to the authors of much of [Eclipse Zone](http://www.eclipsezone.com/eclipse/forums/t99588.html), [VonC](https://stackoverflow.com/questions/223875/logging-in-eclipseosgi-plugins#224821), [Ekkes](http://ekkes-corner.blogspot.com/2008/09/logging-in-osgi-enterprise-applications.html), and everyone in #eclipse on freenode for their help and patience :)
|
223,902 |
<p>Take the following generics example</p>
<pre><code>import java.util.List;
import java.util.ArrayList;
public class GenericsTest {
private List<Animal> myList;
public static void main(String args[]) {
new GenericsTest(new ArrayList<Animal>()).add(new Dog());
}
public GenericsTest(List<Animal> list) {
myList = list;
}
public void add(Animal a) {
myList.add(a);
}
public interface Animal {}
public static class Dog implements Animal {}
public static class Cat implements Animal {}
}
</code></pre>
<p>It works fine. But as you know, you cannot construct it with</p>
<pre><code>new GenericsTest(new ArrayList<Dog>());
</code></pre>
<p>because, as you know, the add(Animal) would make possible to add <code>Cat</code>s. The <em>suggested</em> way of solving this problem, i.e. wildcarding does not work either, because, yes, you can change every <code>List<Animal></code> in <code>List<? extends Animal></code> but it has the same problem: you can create the <code>GenericsTest</code> with <code>List<Cat></code> and then add <code>Dog</code>s.</p>
<p>So my question is: is there a convenient way to write this class once, and then use it for all the possible <code>Animals</code>? Of course it should solve straightforwardly the above mentioned problem. </p>
|
[
{
"answer_id": 223923,
"author": "Greg Cottman",
"author_id": 10496,
"author_profile": "https://Stackoverflow.com/users/10496",
"pm_score": 4,
"selected": true,
"text": "<p>If I understand what you're trying to do then you need to put the generic type at class level:</p>\n\n<pre><code>public class GenericsTest<T extends Animal>\n{\n private List<T> myList;\n\n public static void main(String args[])\n {\n new GenericsTest<Dog>(new ArrayList<Dog>());\n }\n\n public GenericsTest(List<T> list)\n {\n myList = list;\n }\n\n public void add(T a)\n {\n myList.add(a);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 223932,
"author": "Diastrophism",
"author_id": 18093,
"author_profile": "https://Stackoverflow.com/users/18093",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to make the <strong>whole</strong> class generic rather than only the parameters:</p>\n\n<pre><code>import java.util.List;\nimport java.util.ArrayList;\n\npublic class GenericsTest<T extends Animal> {\n private final List<T> myList;\n\n public static void main(final String args[]) {\n new GenericsTest<Animal>(new ArrayList<Animal>()).add(new Dog());\n new GenericsTest<Dog>(new ArrayList<Dog>()).add(new Dog());\n new GenericsTest<Cat>(new ArrayList<Cat>()).add(new Cat());\n }\n\n public GenericsTest(final List<T> list) {\n myList = list;\n }\n\n public void add(final T a) {\n myList.add(a);\n }\n}\n\n// Can't nest as Animal needs to be in scope of class declaration\ninterface Animal {}\nclass Dog implements Animal {}\nclass Cat implements Animal {}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] |
Take the following generics example
```
import java.util.List;
import java.util.ArrayList;
public class GenericsTest {
private List<Animal> myList;
public static void main(String args[]) {
new GenericsTest(new ArrayList<Animal>()).add(new Dog());
}
public GenericsTest(List<Animal> list) {
myList = list;
}
public void add(Animal a) {
myList.add(a);
}
public interface Animal {}
public static class Dog implements Animal {}
public static class Cat implements Animal {}
}
```
It works fine. But as you know, you cannot construct it with
```
new GenericsTest(new ArrayList<Dog>());
```
because, as you know, the add(Animal) would make possible to add `Cat`s. The *suggested* way of solving this problem, i.e. wildcarding does not work either, because, yes, you can change every `List<Animal>` in `List<? extends Animal>` but it has the same problem: you can create the `GenericsTest` with `List<Cat>` and then add `Dog`s.
So my question is: is there a convenient way to write this class once, and then use it for all the possible `Animals`? Of course it should solve straightforwardly the above mentioned problem.
|
If I understand what you're trying to do then you need to put the generic type at class level:
```
public class GenericsTest<T extends Animal>
{
private List<T> myList;
public static void main(String args[])
{
new GenericsTest<Dog>(new ArrayList<Dog>());
}
public GenericsTest(List<T> list)
{
myList = list;
}
public void add(T a)
{
myList.add(a);
}
}
```
|
223,918 |
<p>We all know you can't do the following because of <code>ConcurrentModificationException</code>:</p>
<pre><code>for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
</code></pre>
<p>But this apparently works sometimes, but not always. Here's some specific code:</p>
<pre class="lang-java prettyprint-override"><code>public static void main(String[] args) {
Collection<Integer> l = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
l.add(4);
l.add(5);
l.add(6);
}
for (int i : l) {
if (i == 5) {
l.remove(i);
}
}
System.out.println(l);
}
</code></pre>
<p>This, of course, results in:</p>
<pre><code>Exception in thread "main" java.util.ConcurrentModificationException
</code></pre>
<p>Even though multiple threads aren't doing it. Anyway.</p>
<p>What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?</p>
<p>I'm also using an arbitrary <code>Collection</code> here, not necessarily an <code>ArrayList</code>, so you can't rely on <code>get</code>.</p>
|
[
{
"answer_id": 223927,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 8,
"selected": false,
"text": "<p>This works:</p>\n\n<pre><code>Iterator<Integer> iter = l.iterator();\nwhile (iter.hasNext()) {\n if (iter.next() == 5) {\n iter.remove();\n }\n}\n</code></pre>\n\n<p>I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this <code>.remove()</code> functionality.</p>\n"
},
{
"answer_id": 223929,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 12,
"selected": true,
"text": "<p><a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--\" rel=\"noreferrer\"><code>Iterator.remove()</code></a> is safe, you can use it like this:</p>\n\n<pre><code>List<String> list = new ArrayList<>();\n\n// This is a clever way to create the iterator and call iterator.hasNext() like\n// you would do in a while-loop. It would be the same as doing:\n// Iterator<String> iterator = list.iterator();\n// while (iterator.hasNext()) {\nfor (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {\n String string = iterator.next();\n if (string.isEmpty()) {\n // Remove the current element from the iterator and the list.\n iterator.remove();\n }\n}\n</code></pre>\n\n<p>Note that <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--\" rel=\"noreferrer\"><code>Iterator.remove()</code></a> is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified <strong>in any other way</strong> while the iteration is in progress.</p>\n\n<p>Source:<a href=\"http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html\" rel=\"noreferrer\"> docs.oracle > The Collection Interface</a></p>\n\n<hr>\n\n<p>And similarly, if you have a <code>ListIterator</code> and want to <em>add</em> items, you can use <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#add-E-\" rel=\"noreferrer\"><code>ListIterator#add</code></a>, for the same reason you can use <code>Iterator#remove</code> — it's designed to allow it.</p>\n\n<hr>\n\n<p>In your case you tried to remove from a list, but the same restriction applies if trying to <code>put</code> into a <code>Map</code> while iterating its content. </p>\n"
},
{
"answer_id": 223942,
"author": "RodeoClown",
"author_id": 943,
"author_profile": "https://Stackoverflow.com/users/943",
"pm_score": 5,
"selected": false,
"text": "<p>You can either use the iterator directly like you mentioned, or else keep a second collection and add each item you want to remove to the new collection, then removeAll at the end. This allows you to keep using the type-safety of the for-each loop at the cost of increased memory use and cpu time (shouldn't be a huge problem unless you have really, really big lists or a really old computer)</p>\n\n<pre><code>public static void main(String[] args)\n{\n Collection<Integer> l = new ArrayList<Integer>();\n Collection<Integer> itemsToRemove = new ArrayList<>();\n for (int i=0; i < 10; i++) {\n l.add(Integer.of(4));\n l.add(Integer.of(5));\n l.add(Integer.of(6));\n }\n for (Integer i : l)\n {\n if (i.intValue() == 5) {\n itemsToRemove.add(i);\n }\n }\n\n l.removeAll(itemsToRemove);\n System.out.println(l);\n}\n</code></pre>\n"
},
{
"answer_id": 2841570,
"author": "Ashish",
"author_id": 275264,
"author_profile": "https://Stackoverflow.com/users/275264",
"pm_score": 5,
"selected": false,
"text": "<p>Since the question has been already answered i.e. the best way is to use the remove method of the iterator object, I would go into the specifics of the place where the error <code>\"java.util.ConcurrentModificationException\"</code> is thrown.</p>\n\n<p>Every collection class has a private class which implements the Iterator interface and provides methods like <code>next()</code>, <code>remove()</code> and <code>hasNext()</code>.</p>\n\n<p>The code for next looks something like this...</p>\n\n<pre><code>public E next() {\n checkForComodification();\n try {\n E next = get(cursor);\n lastRet = cursor++;\n return next;\n } catch(IndexOutOfBoundsException e) {\n checkForComodification();\n throw new NoSuchElementException();\n }\n}\n</code></pre>\n\n<p>Here the method <code>checkForComodification</code> is implemented as </p>\n\n<pre><code>final void checkForComodification() {\n if (modCount != expectedModCount)\n throw new ConcurrentModificationException();\n}\n</code></pre>\n\n<p>So, as you can see, if you explicitly try to remove an element from the collection. It results in <code>modCount</code> getting different from <code>expectedModCount</code>, resulting in the exception <code>ConcurrentModificationException</code>.</p>\n"
},
{
"answer_id": 11201224,
"author": "Priyank Doshi",
"author_id": 1392956,
"author_profile": "https://Stackoverflow.com/users/1392956",
"pm_score": 4,
"selected": false,
"text": "<p>Make a copy of existing list and iterate over new copy.</p>\n\n<pre><code>for (String str : new ArrayList<String>(listOfStr)) \n{\n listOfStr.remove(/* object reference or index */);\n}\n</code></pre>\n"
},
{
"answer_id": 13943008,
"author": "Donald Raab",
"author_id": 1570415,
"author_profile": "https://Stackoverflow.com/users/1570415",
"pm_score": 4,
"selected": false,
"text": "<p>With <a href=\"https://www.eclipse.org/collections/\" rel=\"nofollow noreferrer\">Eclipse Collections</a>, the method <code>removeIf</code> defined on <a href=\"https://github.com/eclipse/eclipse-collections/blob/master/eclipse-collections-api/src/main/java/org/eclipse/collections/api/collection/MutableCollection.java#L236\" rel=\"nofollow noreferrer\">MutableCollection</a> will work:</p>\n\n<pre><code>MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);\nlist.removeIf(Predicates.lessThan(3));\nAssert.assertEquals(Lists.mutable.of(3, 4, 5), list);\n</code></pre>\n\n<p>With Java 8 Lambda syntax this can be written as follows:</p>\n\n<pre><code>MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);\nlist.removeIf(Predicates.cast(integer -> integer < 3));\nAssert.assertEquals(Lists.mutable.of(3, 4, 5), list);\n</code></pre>\n\n<p>The call to <code>Predicates.cast()</code> is necessary here because a default <code>removeIf</code> method was added on the <code>java.util.Collection</code> interface in Java 8. </p>\n\n<p><strong>Note:</strong> I am a committer for <a href=\"https://www.eclipse.org/collections/\" rel=\"nofollow noreferrer\">Eclipse Collections</a>.</p>\n"
},
{
"answer_id": 18357676,
"author": "Antzi",
"author_id": 1485230,
"author_profile": "https://Stackoverflow.com/users/1485230",
"pm_score": 4,
"selected": false,
"text": "<p>Same answer as <a href=\"https://stackoverflow.com/a/223927/1433392\">Claudius</a> with a for loop:</p>\n\n<pre><code>for (Iterator<Object> it = objects.iterator(); it.hasNext();) {\n Object object = it.next();\n if (test) {\n it.remove();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19330700,
"author": "ajax333221",
"author_id": 908879,
"author_profile": "https://Stackoverflow.com/users/908879",
"pm_score": -1,
"selected": false,
"text": "<p>this might not be the best way, but for most of the small cases this should acceptable:</p>\n\n<blockquote>\n <p><em>\"create a second empty-array and add only the ones you want to keep\"</em></p>\n</blockquote>\n\n<p><sub>I don't remeber where I read this from... for justiness I will make this wiki in hope someone finds it or just to don't earn rep I don't deserve.</sub></p>\n"
},
{
"answer_id": 20067507,
"author": "Nandhan Thiravia",
"author_id": 1711555,
"author_profile": "https://Stackoverflow.com/users/1711555",
"pm_score": 0,
"selected": false,
"text": "<p>I have a suggestion for the problem above. No need of secondary list or any extra time. Please find an example which would do the same stuff but in a different way.</p>\n\n<pre><code>//\"list\" is ArrayList<Object>\n//\"state\" is some boolean variable, which when set to true, Object will be removed from the list\nint index = 0;\nwhile(index < list.size()) {\n Object r = list.get(index);\n if( state ) {\n list.remove(index);\n index = 0;\n continue;\n }\n index += 1;\n}\n</code></pre>\n\n<p>\nThis would avoid the Concurrency Exception.</p>\n"
},
{
"answer_id": 23908758,
"author": "assylias",
"author_id": 829571,
"author_profile": "https://Stackoverflow.com/users/829571",
"pm_score": 8,
"selected": false,
"text": "<p>With Java 8 you can use <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-\" rel=\"noreferrer\">the new <code>removeIf</code> method</a>. Applied to your example:</p>\n\n<pre><code>Collection<Integer> coll = new ArrayList<>();\n//populate\n\ncoll.removeIf(i -> i == 5);\n</code></pre>\n"
},
{
"answer_id": 25565900,
"author": "Landei",
"author_id": 375232,
"author_profile": "https://Stackoverflow.com/users/375232",
"pm_score": 4,
"selected": false,
"text": "<p>In such cases a common trick is (was?) to go backwards:</p>\n\n<pre><code>for(int i = l.size() - 1; i >= 0; i --) {\n if (l.get(i) == 5) {\n l.remove(i);\n }\n}\n</code></pre>\n\n<p>That said, I'm more than happy that you have better ways in Java 8, e.g. <code>removeIf</code> or <code>filter</code> on streams.</p>\n"
},
{
"answer_id": 35207600,
"author": "Nurlan",
"author_id": 2807072,
"author_profile": "https://Stackoverflow.com/users/2807072",
"pm_score": -1,
"selected": false,
"text": "<p>In case <strong>ArrayList:remove(int index)</strong>- if(index is last element's position) it avoids without <code>System.arraycopy()</code> and takes not time for this.</p>\n\n<p>arraycopy time increases if(index decreases), by the way elements of list also decreases!</p>\n\n<p>the best effective remove way is- removing its elements in descending order:\n<code>while(list.size()>0)list.remove(list.size()-1);</code>//takes O(1)\n<code>while(list.size()>0)list.remove(0);</code>//takes O(factorial(n))</p>\n\n<pre><code>//region prepare data\nArrayList<Integer> ints = new ArrayList<Integer>();\nArrayList<Integer> toRemove = new ArrayList<Integer>();\nRandom rdm = new Random();\nlong millis;\nfor (int i = 0; i < 100000; i++) {\n Integer integer = rdm.nextInt();\n ints.add(integer);\n}\nArrayList<Integer> intsForIndex = new ArrayList<Integer>(ints);\nArrayList<Integer> intsDescIndex = new ArrayList<Integer>(ints);\nArrayList<Integer> intsIterator = new ArrayList<Integer>(ints);\n//endregion\n\n// region for index\nmillis = System.currentTimeMillis();\nfor (int i = 0; i < intsForIndex.size(); i++) \n if (intsForIndex.get(i) % 2 == 0) intsForIndex.remove(i--);\nSystem.out.println(System.currentTimeMillis() - millis);\n// endregion\n\n// region for index desc\nmillis = System.currentTimeMillis();\nfor (int i = intsDescIndex.size() - 1; i >= 0; i--) \n if (intsDescIndex.get(i) % 2 == 0) intsDescIndex.remove(i);\nSystem.out.println(System.currentTimeMillis() - millis);\n//endregion\n\n// region iterator\nmillis = System.currentTimeMillis();\nfor (Iterator<Integer> iterator = intsIterator.iterator(); iterator.hasNext(); )\n if (iterator.next() % 2 == 0) iterator.remove();\nSystem.out.println(System.currentTimeMillis() - millis);\n//endregion\n</code></pre>\n\n<ul>\n<li>for index loop: 1090 msec</li>\n<li>for desc index: <strong>519</strong> msec---the best</li>\n<li>for iterator: 1043 msec</li>\n</ul>\n"
},
{
"answer_id": 37990142,
"author": "Yessy",
"author_id": 6456129,
"author_profile": "https://Stackoverflow.com/users/6456129",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html\" rel=\"nofollow\">ConcurrentHashMap</a> or <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html\" rel=\"nofollow\">ConcurrentLinkedQueue</a> or <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentSkipListMap.html\" rel=\"nofollow\">ConcurrentSkipListMap</a> may be another option, because they will never throw any ConcurrentModificationException, even if you remove or add item.</p>\n"
},
{
"answer_id": 38116468,
"author": "Srinivasan Thoyyeti",
"author_id": 4952219,
"author_profile": "https://Stackoverflow.com/users/4952219",
"pm_score": 0,
"selected": false,
"text": "<pre><code>for (Integer i : l)\n{\n if (i.intValue() == 5){\n itemsToRemove.add(i);\n break;\n }\n}\n</code></pre>\n\n<p>The catch is the after removing the element from the list if you skip the internal iterator.next() call. it still works! Though I dont propose to write code like this it helps to understand the concept behind it :-)</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 43441822,
"author": "from56",
"author_id": 7690376,
"author_profile": "https://Stackoverflow.com/users/7690376",
"pm_score": 3,
"selected": false,
"text": "<p>With a traditional for loop</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>ArrayList<String> myArray = new ArrayList<>();\n\nfor (int i = 0; i < myArray.size(); ) {\n String text = myArray.get(i);\n if (someCondition(text))\n myArray.remove(i);\n else\n i++; \n}\n</code></pre>\n"
},
{
"answer_id": 46733073,
"author": "james.garriss",
"author_id": 584674,
"author_profile": "https://Stackoverflow.com/users/584674",
"pm_score": 2,
"selected": false,
"text": "<p>A <code>ListIterator</code> allows you to add or remove items in the list. Suppose you have a list of <code>Car</code> objects:</p>\n\n<pre><code>List<Car> cars = ArrayList<>();\n// add cars here...\n\nfor (ListIterator<Car> carIterator = cars.listIterator(); carIterator.hasNext(); )\n{\n if (<some-condition>)\n { \n carIterator().remove()\n }\n else if (<some-other-condition>)\n { \n carIterator().add(aNewCar);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49335224,
"author": "John",
"author_id": 866333,
"author_profile": "https://Stackoverflow.com/users/866333",
"pm_score": 3,
"selected": false,
"text": "<p>People are asserting one <strong>can't</strong> remove from a Collection being iterated by a foreach loop. I just wanted to point out that is <em>technically</em> incorrect and describe exactly (I know the OP's question is so advanced as to obviate knowing this) the code behind that assumption:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (TouchableObj obj : untouchedSet) { // <--- This is where ConcurrentModificationException strikes\n if (obj.isTouched()) {\n untouchedSet.remove(obj);\n touchedSt.add(obj);\n break; // this is key to avoiding returning to the foreach\n }\n}\n</code></pre>\n\n<p>It isn't that you can't remove from the iterated <code>Colletion</code> rather that you can't then continue iteration once you do. Hence the <code>break</code> in the code above.</p>\n\n<p>Apologies if this answer is a somewhat specialist use-case and more suited to the original <a href=\"https://stackoverflow.com/questions/1110404/remove-elements-from-a-hashset-while-iterating\">thread</a> I arrived here from, that one is marked as a duplicate (despite this thread appearing more nuanced) of this and locked.</p>\n"
},
{
"answer_id": 50161275,
"author": "jagdish khetre",
"author_id": 6715431,
"author_profile": "https://Stackoverflow.com/users/6715431",
"pm_score": 0,
"selected": false,
"text": "<p>The best way (recommended) is use of <code>java.util.concurrent</code> package. By\nusing this package you can easily avoid this exception. Refer\nModified Code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Collection<Integer> l = new CopyOnWriteArrayList<Integer>();\n \n for (int i=0; i < 10; ++i) {\n l.add(new Integer(4));\n l.add(new Integer(5));\n l.add(new Integer(6));\n }\n \n for (Integer i : l) {\n if (i.intValue() == 5) {\n l.remove(i);\n }\n }\n \n System.out.println(l);\n}\n</code></pre>\n"
},
{
"answer_id": 52364161,
"author": "Yazon2006",
"author_id": 2557258,
"author_profile": "https://Stackoverflow.com/users/2557258",
"pm_score": 0,
"selected": false,
"text": "<p>Example of thread safe collection modification:</p>\n\n<pre><code>public class Example {\n private final List<String> queue = Collections.synchronizedList(new ArrayList<String>());\n\n public void removeFromQueue() {\n synchronized (queue) {\n Iterator<String> iterator = queue.iterator();\n String string = iterator.next();\n if (string.isEmpty()) {\n iterator.remove();\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 52525447,
"author": "pedram bashiri",
"author_id": 2695227,
"author_profile": "https://Stackoverflow.com/users/2695227",
"pm_score": 1,
"selected": false,
"text": "<p>I know this question is too old to be about Java 8, but for those using Java 8 you can easily use removeIf():</p>\n\n<pre><code>Collection<Integer> l = new ArrayList<Integer>();\n\nfor (int i=0; i < 10; ++i) {\n l.add(new Integer(4));\n l.add(new Integer(5));\n l.add(new Integer(6));\n}\n\nl.removeIf(i -> i.intValue() == 5);\n</code></pre>\n"
},
{
"answer_id": 53860666,
"author": "cellepo",
"author_id": 1357094,
"author_profile": "https://Stackoverflow.com/users/1357094",
"pm_score": 0,
"selected": false,
"text": "<p>I know this question assumes just a <code>Collection</code>, and not more specifically any <code>List</code>. But <strong>for those reading this question who are indeed working with a <code>List</code> reference, you can avoid <code>ConcurrentModificationException</code> with a <code>while</code>-loop (while modifying within it) instead if you want to avoid <code>Iterator</code></strong> (either if you want to avoid it in general, or avoid it specifically to achieve a looping order different from start-to-end stopping at each element [which I believe is the only order <code>Iterator</code> itself can do]):</p>\n\n<p><strong>*Update: See comments below that clarify the analogous is also achievable with the <em>traditional</em>-for-loop.</strong></p>\n\n<pre><code>final List<Integer> list = new ArrayList<>();\nfor(int i = 0; i < 10; ++i){\n list.add(i);\n}\n\nint i = 1;\nwhile(i < list.size()){\n if(list.get(i) % 2 == 0){\n list.remove(i++);\n\n } else {\n i += 2;\n }\n}\n</code></pre>\n\n<p><em>No ConcurrentModificationException from that code.</em></p>\n\n<p>There we see looping not start at the beginning, and not stop at <em>every</em> element (which I believe <code>Iterator</code> itself can't do).</p>\n\n<p>FWIW we also see <code>get</code> being called on <code>list</code>, which could not be done if its reference was just <code>Collection</code> (instead of the more specific <code>List</code>-type of <code>Collection</code>) - <code>List</code> interface includes <code>get</code>, but <code>Collection</code> interface does not. If not for that difference, then the <code>list</code> reference could instead be a <code>Collection</code> [and therefore technically this Answer would then be a direct Answer, instead of a tangential Answer].</p>\n\n<p>FWIWW same code still works after modified to start at beginning at stop at every element (just like <code>Iterator</code> order):</p>\n\n<pre><code>final List<Integer> list = new ArrayList<>();\nfor(int i = 0; i < 10; ++i){\n list.add(i);\n}\n\nint i = 0;\nwhile(i < list.size()){\n if(list.get(i) % 2 == 0){\n list.remove(i);\n\n } else {\n ++i;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55161143,
"author": "Nestor Milyaev",
"author_id": 5778099,
"author_profile": "https://Stackoverflow.com/users/5778099",
"pm_score": 2,
"selected": false,
"text": "<p>Another way is to use a copy of your arrayList just for iteration:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List<Object> l = ...\n \nList<Object> iterationList = ImmutableList.copyOf(l);\n \nfor (Object curr : iterationList) {\n if (condition(curr)) {\n l.remove(curr);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 57298240,
"author": "Rahul Vala",
"author_id": 7584019,
"author_profile": "https://Stackoverflow.com/users/7584019",
"pm_score": 0,
"selected": false,
"text": "<p>One solution could be to rotate the list and remove the first element to avoid the ConcurrentModificationException or IndexOutOfBoundsException</p>\n\n<pre><code>int n = list.size();\nfor(int j=0;j<n;j++){\n //you can also put a condition before remove\n list.remove(0);\n Collections.rotate(list, 1);\n}\nCollections.rotate(list, -1);\n</code></pre>\n"
},
{
"answer_id": 58844056,
"author": "Oleg Tatarchuk",
"author_id": 8483269,
"author_profile": "https://Stackoverflow.com/users/8483269",
"pm_score": 0,
"selected": false,
"text": "<p>Try this one (removes all elements in the list that equal <code>i</code>):</p>\n\n<pre><code>for (Object i : l) {\n if (condition(i)) {\n l = (l.stream().filter((a) -> a != i)).collect(Collectors.toList());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 62195755,
"author": "Firas Chebbah",
"author_id": 5913870,
"author_profile": "https://Stackoverflow.com/users/5913870",
"pm_score": -1,
"selected": false,
"text": "<p>you can also use <strong>Recursion</strong></p>\n\n<p>Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.</p>\n"
},
{
"answer_id": 64011786,
"author": "Adil Karaöz",
"author_id": 705908,
"author_profile": "https://Stackoverflow.com/users/705908",
"pm_score": 1,
"selected": false,
"text": "<p>Now, You can remove with the following code</p>\n<pre><code>l.removeIf(current -> current == 5);\n</code></pre>\n"
},
{
"answer_id": 65476338,
"author": "Oguzhan Cevik",
"author_id": 7927573,
"author_profile": "https://Stackoverflow.com/users/7927573",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a while loop.</p>\n<pre><code>Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();\nwhile(iterator.hasNext()){\n Map.Entry<String, String> entry = iterator.next();\n if(entry.getKey().equals("test")) {\n iterator.remove();\n } \n}\n</code></pre>\n"
},
{
"answer_id": 66889350,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Java Concurrent Modification Exception</strong></p>\n<ol>\n<li>Single thread</li>\n</ol>\n<pre><code>Iterator<String> iterator = list.iterator();\nwhile (iterator.hasNext()) {\n String value = iter.next()\n if (value == "A") {\n list.remove(it.next()); //throws ConcurrentModificationException\n }\n}\n</code></pre>\n<p>Solution: iterator <code>remove()</code> method</p>\n<pre><code>Iterator<String> iterator = list.iterator();\nwhile (iterator.hasNext()) {\n String value = iter.next()\n if (value == "A") {\n it.remove()\n }\n}\n</code></pre>\n<ol start=\"2\">\n<li>Multi thread</li>\n</ol>\n<ul>\n<li>copy/convert and iterate over another one collection. For small collections</li>\n<li><code>synchronize</code><a href=\"https://stackoverflow.com/a/59500618/4770877\"><sup>[About]</sup></a></li>\n<li>thread safe collection<a href=\"https://stackoverflow.com/a/65410514/4770877\"><sup>[About]</sup></a></li>\n</ul>\n"
},
{
"answer_id": 68239250,
"author": "Alferd Nobel",
"author_id": 4005379,
"author_profile": "https://Stackoverflow.com/users/4005379",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up with this <code>ConcurrentModificationException</code>, while iterating the list using <code>stream().map()</code> method. However the <code>for(:)</code> did not throw the exception while iterating and modifying the the list.</p>\n<p>Here is code snippet , if its of help to anyone:\nhere I'm iterating on a <code>ArrayList<BuildEntity></code> , and modifying it using the list.remove(obj)</p>\n<pre><code> for(BuildEntity build : uniqueBuildEntities){\n if(build!=null){\n if(isBuildCrashedWithErrors(build)){\n log.info("The following build crashed with errors , will not be persisted -> \\n{}"\n ,build.getBuildUrl());\n uniqueBuildEntities.remove(build);\n if (uniqueBuildEntities.isEmpty()) return EMPTY_LIST;\n }\n }\n }\n if(uniqueBuildEntities.size()>0) {\n dbEntries.addAll(uniqueBuildEntities);\n }\n</code></pre>\n"
},
{
"answer_id": 70142023,
"author": "SM. Hosseini",
"author_id": 8423371,
"author_profile": "https://Stackoverflow.com/users/8423371",
"pm_score": 0,
"selected": false,
"text": "<p>If using HashMap, in newer versions of Java (8+) you can select each of 3 options:</p>\n<pre><code>public class UserProfileEntity {\n private String Code;\n private String mobileNumber;\n private LocalDateTime inputDT;\n // getters and setters here\n}\nHashMap<String, UserProfileEntity> upMap = new HashMap<>();\n\n\n// remove by value\nupMap.values().removeIf(value -> !value.getCode().contains("0005"));\n\n// remove by key\nupMap.keySet().removeIf(key -> key.contentEquals("testUser"));\n\n// remove by entry / key + value\nupMap.entrySet().removeIf(entry -> (entry.getKey().endsWith("admin") || entry.getValue().getInputDT().isBefore(LocalDateTime.now().minusMinutes(3)));\n</code></pre>\n"
},
{
"answer_id": 74542733,
"author": "Saeed Ir",
"author_id": 1375876,
"author_profile": "https://Stackoverflow.com/users/1375876",
"pm_score": 0,
"selected": false,
"text": "<p><em><strong>Iterators</strong></em> are not always helpful when another thread also modifies the collection. I had tried many ways but then realized traversing the collection manually is much safer (backward for removal):</p>\n<pre><code>for (i in myList.size-1 downTo 0) {\n myList.getOrNull(i)?.also {\n if (it == 5)\n myList.remove(it)\n }\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
We all know you can't do the following because of `ConcurrentModificationException`:
```
for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
```
But this apparently works sometimes, but not always. Here's some specific code:
```java
public static void main(String[] args) {
Collection<Integer> l = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
l.add(4);
l.add(5);
l.add(6);
}
for (int i : l) {
if (i == 5) {
l.remove(i);
}
}
System.out.println(l);
}
```
This, of course, results in:
```
Exception in thread "main" java.util.ConcurrentModificationException
```
Even though multiple threads aren't doing it. Anyway.
What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?
I'm also using an arbitrary `Collection` here, not necessarily an `ArrayList`, so you can't rely on `get`.
|
[`Iterator.remove()`](https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--) is safe, you can use it like this:
```
List<String> list = new ArrayList<>();
// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
// Iterator<String> iterator = list.iterator();
// while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String string = iterator.next();
if (string.isEmpty()) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
```
Note that [`Iterator.remove()`](https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--) is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified **in any other way** while the iteration is in progress.
Source: [docs.oracle > The Collection Interface](http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html)
---
And similarly, if you have a `ListIterator` and want to *add* items, you can use [`ListIterator#add`](http://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#add-E-), for the same reason you can use `Iterator#remove` — it's designed to allow it.
---
In your case you tried to remove from a list, but the same restriction applies if trying to `put` into a `Map` while iterating its content.
|
223,919 |
<p>I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files.</p>
<p>Here is how I have the library and application folders set up. (I'm not sure if this is right)</p>
<pre><code>AppFolder
App.sln
App.ncb
*.h
*.cpp
Debug
*.obj
App.exe
</code></pre>
<p>and somewhere else on the hard drive...</p>
<pre><code>LibraryFolder
lib
Library.lib
include
LibrarySolutionFolder
Library.sln
Library.ncb
*.h
*.cpp
Debug
*.obj
Library.lib
</code></pre>
<p>I've been #including the library *.h files from my app's cpp files, and everything compiles fine. It's just when it links I get a list of all the .lib
files that are being searched, and Library.lib isn't on there even though I have it listed in VC++ directories.
How can I get this to link? (And am I structuring the library folders correctly?)</p>
|
[
{
"answer_id": 223943,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 4,
"selected": true,
"text": "<p>On the project properties:</p>\n\n<p>Configuration Properties -> Linker -> Input -> Additional Dependancies</p>\n\n<p>Add it in there.</p>\n\n<p>Or, in your .h file for the library, add:</p>\n\n<pre><code>#pragma comment(lib, \"Library\")\n</code></pre>\n\n<p>This will do it automatically for you.</p>\n"
},
{
"answer_id": 223947,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 0,
"selected": false,
"text": "<p>VC does not simply link the library if you include the header-file.</p>\n\n<p>You have to tell the linker to use the library. For good reasons: You alredy have thousands of libs in your library folder. If MSVC had to search all of them each time you link your program it would have to wade through hundrets of megabytes of data. </p>\n\n<p>That would take quite a while, therefore it's not done by default.</p>\n\n<p>For VC you can also give a hint to the linker inside your source. To do so you add the following line somewhere in your source-code (the header of the lib may be a good place).</p>\n\n<pre><code>#pragma comment(lib,\"c:\\\\path_to_library\\\\libname.lib\")\n</code></pre>\n\n<p>That's not platform independet but the most convenient way to get a lib automatically linked to a project using MSVC.</p>\n\n<p>Another way is to simply add the linker to the project settings. The relevant info can be found lin the linker settings of your project. Don't forget to add the lib to the release and debug configurations.</p>\n"
},
{
"answer_id": 223950,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 2,
"selected": false,
"text": "<p>The VC++ directories is the list of directory locations to searched during linking. It is not a list of libraries to be linked in.</p>\n\n<p>You need to add the lib file to the <strong><em>Additional Dependencies</em></strong> field of the <strong><em>Project Linker</em></strong> settings.</p>\n"
},
{
"answer_id": 223961,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 1,
"selected": false,
"text": "<p>To link against a library, you can either:</p>\n\n<ul>\n<li>List it in Project-> Properties...->Linker, Input->Additional Dependancies\n (VC++ directories only lets you use just the .lib name rather the full path),</li>\n<li>Add the library project to your app. solution (On solution, right click -> Add -> Existing Project...), then use Project -> Project Dependancies..., then check your library project (make sure the application project is selected in the drop-down). This is probably the best way to go if you are editting both projects, as VC++ will rebuild the library if it has changed before building your app.</li>\n<li><p>If you are sure you will only use VC++, </p>\n\n<pre><code> #pragma comment(lib,\"C:\\\\path\\\\to\\\\library.lib\")`\n</code></pre>\n\n<p>(Thanks @Nils)</p></li>\n</ul>\n\n<p>NB: It seems very odd to have your library solution folder inside an 'include' directory: which are really intended for *.h (or other <code>#include</code>d files).</p>\n"
},
{
"answer_id": 224501,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 1,
"selected": false,
"text": "<p>From the command line:</p>\n\n<blockquote>\n <p>cl /EHsc {objfiles}+ /link\n /LIBPATH:LibraryFolder Library.lib</p>\n</blockquote>\n\n<p>Where {objfiles}+ means one or more object or cpp files. </p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2222/"
] |
I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files.
Here is how I have the library and application folders set up. (I'm not sure if this is right)
```
AppFolder
App.sln
App.ncb
*.h
*.cpp
Debug
*.obj
App.exe
```
and somewhere else on the hard drive...
```
LibraryFolder
lib
Library.lib
include
LibrarySolutionFolder
Library.sln
Library.ncb
*.h
*.cpp
Debug
*.obj
Library.lib
```
I've been #including the library \*.h files from my app's cpp files, and everything compiles fine. It's just when it links I get a list of all the .lib
files that are being searched, and Library.lib isn't on there even though I have it listed in VC++ directories.
How can I get this to link? (And am I structuring the library folders correctly?)
|
On the project properties:
Configuration Properties -> Linker -> Input -> Additional Dependancies
Add it in there.
Or, in your .h file for the library, add:
```
#pragma comment(lib, "Library")
```
This will do it automatically for you.
|
223,921 |
<p>How do you get Pro*c to work within MSVC 6?</p>
<p>In otherwords compile a .pc file into a .cpp file.</p>
|
[
{
"answer_id": 223956,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<p>Visual C++/Visual Studio won't be a big help other than being an editor, but you should be able to get this to work with a Makefile project.</p>\n"
},
{
"answer_id": 225067,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it (unfortunatley I'm not going to be much help as it has been many years since I last used VC6.)\nAccording to my failing memory, we set up the file type '.pc' (in the tools section of VC?) so that VC knew to call proC to generate a .c or .cpp version of the file.<br>\nI believe we included both the (source) .pc and (generated) .cpp file in the project (there is probably a better way to do this) so that we could easily edit the proC file in VC.<br>\n(I can't remember how we told VC that the cpp file was dependent on the pc file)<br>\nBest of luck.</p>\n"
},
{
"answer_id": 225140,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not familiar with Pro*C, but in general it is possible, using a custom build step in MSVC. If you add the .pc file to your project, then view the Project Settings dialog for that file, on the Custom Build tab you can specify the command(s) needed to compile the .pc file to .cpp. You should also enter the name of the output .cpp in the Output section, so that the build system understands the file dependencies, and add the output .cpp to your project, of course.</p>\n"
},
{
"answer_id": 285934,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 1,
"selected": true,
"text": "<p>In the <strong>custom build tab</strong> for the <strong>.pc</strong> file. </p>\n\n<p>I pop this in the <strong>outputs</strong>. The output of <strong>proc</strong>, is a cpp file</p>\n\n<pre><code>$(ProjDir)\\$(InputName).cpp\n</code></pre>\n\n<p>There are 2 lines in the <strong>commands</strong> window. One to set the MSVC 6 environment. The other to invoke proc on the .pc file.</p>\n\n<pre><code>call vcvars32.bat \nproc sqlcheck=semantics userid=scott/tiger@instance code=cpp char_map=string sqlcheck=semantics parse=partial mode=ansi $(ProjDir)\\$(InputName).pc include=c:\\ora920\\oci\\include include=\"%MSVCDIR%\\include\" include=\"$(MSDEVDIR)\\..\\vc\\include\" include=\"$(MSDEVDIR)\\..\\..\\vc98\\include\"\n</code></pre>\n\n<p>You must add the .cpp file to your project in order to compile it. If you need to debug, set your breakpoints in the .cpp file. </p>\n\n<p>That pretty much covers it.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734/"
] |
How do you get Pro\*c to work within MSVC 6?
In otherwords compile a .pc file into a .cpp file.
|
In the **custom build tab** for the **.pc** file.
I pop this in the **outputs**. The output of **proc**, is a cpp file
```
$(ProjDir)\$(InputName).cpp
```
There are 2 lines in the **commands** window. One to set the MSVC 6 environment. The other to invoke proc on the .pc file.
```
call vcvars32.bat
proc sqlcheck=semantics userid=scott/tiger@instance code=cpp char_map=string sqlcheck=semantics parse=partial mode=ansi $(ProjDir)\$(InputName).pc include=c:\ora920\oci\include include="%MSVCDIR%\include" include="$(MSDEVDIR)\..\vc\include" include="$(MSDEVDIR)\..\..\vc98\include"
```
You must add the .cpp file to your project in order to compile it. If you need to debug, set your breakpoints in the .cpp file.
That pretty much covers it.
|
223,931 |
<p>What are your favorite ways to encapsulate LINQ to SQL entity classes and data-context classes into business objects?</p>
<p>What have you found to work in a given situation?</p>
<p>Have you invented or taken to any specific patterns?</p>
|
[
{
"answer_id": 224929,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 1,
"selected": false,
"text": "<p>Right now I'm trying to use LINQ to SQL entity classes as business objects, to pass them around between functions and services.</p>\n\n<p>Of course, you should have <strong>separate entity classes for database access</strong>, so your database layout can change without changing the business objects!</p>\n\n<p>I'd be most interested in a good solution for this, too!</p>\n"
},
{
"answer_id": 225808,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 0,
"selected": false,
"text": "<p>I did some experimentation using Entity Framework and Linq to Entities as a way to further separate my client code from the database, but I found it clumsy to use and was worried about the performance. </p>\n\n<p>In my current project I use Linq to SQL as my data layer, but have separate classes where I implement all Linq queries. The classes return entities defined in my Linq to SQL context, but the queries are hidden in methods. </p>\n"
},
{
"answer_id": 227645,
"author": "calebt",
"author_id": 7525,
"author_profile": "https://Stackoverflow.com/users/7525",
"pm_score": 1,
"selected": false,
"text": "<p>Check out the source code for the MVC Sample app that Rob Conery is putting together:</p>\n\n<p><a href=\"http://www.codeplex.com/mvcsamples/\" rel=\"nofollow noreferrer\">http://www.codeplex.com/mvcsamples/</a></p>\n\n<p>He has a separate entity layer that maps to the LINQ to SQL classes.</p>\n"
},
{
"answer_id": 229669,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 2,
"selected": false,
"text": "<p>I tend to use the Repository pattern to encapsulate DataContexts.</p>\n\n<p><a href=\"http://aspalliance.com/1672_Implementing_the_Repository_Pattern_with_LINQtoSQL.3\" rel=\"nofollow noreferrer\">Repository Pattern</a></p>\n\n<p>I would like to find a better way to emit POCO objects from my data layer while using LINQ2SQL though.</p>\n"
},
{
"answer_id": 231594,
"author": "Jeremy Holt",
"author_id": 30046,
"author_profile": "https://Stackoverflow.com/users/30046",
"pm_score": 0,
"selected": false,
"text": "<p>I found the articles by <a href=\"http://codebetter.com/blogs/ian_cooper/archive/2008/07/01/architecting-linq-to-sql-part-10.aspx#184170\" rel=\"nofollow noreferrer\">Ian Cooper on CodeBetter.com</a> and <a href=\"http://feeds.feedburner.com/StephenWalther\" rel=\"nofollow noreferrer\">Stephen Walther</a> series invaluable in understanding the need to write the POCO entities first and then map them to the database rather than doing it the other way around (which is what I always used to do).</p>\n"
},
{
"answer_id": 231627,
"author": "Albert",
"author_id": 24065,
"author_profile": "https://Stackoverflow.com/users/24065",
"pm_score": 0,
"selected": false,
"text": "<p>I'm playing around with the idea to have a separate layer of OO model (better support for OO practices), but that use LINQ to SQL under the hood. The idea is to have an xml file that a custom tool will use to generate the code. \nSince LINQ to SQL entites are too cluttered for my preferences, I will auto-generate new classes to use as my entities and of course the DataContext will be completely hidden for the client code.\nDo the short answer is: Create new entity classes but use the underlying LINQ to SQL entities and DataContext.</p>\n"
},
{
"answer_id": 1495281,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 3,
"selected": true,
"text": "<p>I've found a pattern which I think works best--In my case, at least.\n<br /><br /><br />\nI extend entity classes using partial classes. I use partial classes so the signature of the entity does not change (see the <code>DeleteOnSubmit</code> call in the <code>Delete</code> method).</p>\n\n<p>I've cooked up a a small example. Here's an image of the database and LINQ to SQL class setup:</p>\n\n<p><img src=\"https://i.stack.imgur.com/WqEHH.png\" />\n<br /><br />\nAnd here's the partial class in which I implement business logic:</p>\n\n<pre><code>/// <summary>\n/// This class extends BusinessLogicDataContext.Products entity class\n/// </summary>\npublic partial class Product\n{\n /// <summary>\n /// New up a product by column: dbo.Products.ProductId in database\n /// </summary>\n public Product(Int32 id)\n {\n var dc = new BusinessLogicDataContext();\n\n // query database for the product\n var query = (\n from p in dc.Products \n where p.ProductId == id \n select p\n ).FirstOrDefault();\n\n // if database-entry does not exist in database, exit\n if (query == null) return;\n\n /* if product exists, populate self (this._ProductId and\n this._ProductName are both auto-generated private\n variables of the entity class which corresponds to the\n auto-generated public properties: ProductId and ProductName) */\n this._ProductId = query.ProductId;\n this._ProductName = query.ProductName;\n }\n\n\n /// <summary>\n /// Delete product\n /// </summary>\n public void Delete()\n {\n // if self is not poulated, exit\n if (this._ProductId == 0) return;\n\n var dc = new BusinessLogicDataContext();\n\n // delete entry in database\n dc.Products.DeleteOnSubmit(this);\n dc.SubmitChanges();\n\n // reset self (you could implement IDisposable here)\n this._ProductId = 0;\n this._ProductName = \"\";\n }\n}\n</code></pre>\n\n<p>Using the implemented business logic:</p>\n\n<pre><code>// new up a product\nvar p = new Product(1); // p.ProductId: 1, p.ProductName: \"A car\"\n\n// delete the product\np.Delete(); // p.ProductId: 0, p.ProductName: \"\"\n</code></pre>\n\n<p>Furthermore: LINQ to SQL entity classes are very open in nature. This means that the property corresponding to the <em>dbo.Products.ProductId</em> column implements both a getter and a setter--this field should not be changeable.</p>\n\n<p>To my knowledge you can't override properties using partial classes, so what I usually do is implement a manager which narrows the object using an interface:</p>\n\n<pre><code>public interface IProduct\n{\n Int32 ProductId { get; }\n\n void Delete();\n}\n</code></pre>\n"
},
{
"answer_id": 2443832,
"author": "Daniel",
"author_id": 169388,
"author_profile": "https://Stackoverflow.com/users/169388",
"pm_score": 2,
"selected": false,
"text": "<p>I just published a sample of how you can structure your application that uses Linq to Sql for storage, using IoC and T4-templates.</p>\n\n<p><a href=\"http://daniel.wertheim.se/2010/03/14/linq-to-sql-how-to-separate-the-entities-and-the-datacontext/\" rel=\"nofollow noreferrer\">http://daniel.wertheim.se/2010/03/14/linq-to-sql-how-to-separate-the-entities-and-the-datacontext/</a></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
What are your favorite ways to encapsulate LINQ to SQL entity classes and data-context classes into business objects?
What have you found to work in a given situation?
Have you invented or taken to any specific patterns?
|
I've found a pattern which I think works best--In my case, at least.
I extend entity classes using partial classes. I use partial classes so the signature of the entity does not change (see the `DeleteOnSubmit` call in the `Delete` method).
I've cooked up a a small example. Here's an image of the database and LINQ to SQL class setup:

And here's the partial class in which I implement business logic:
```
/// <summary>
/// This class extends BusinessLogicDataContext.Products entity class
/// </summary>
public partial class Product
{
/// <summary>
/// New up a product by column: dbo.Products.ProductId in database
/// </summary>
public Product(Int32 id)
{
var dc = new BusinessLogicDataContext();
// query database for the product
var query = (
from p in dc.Products
where p.ProductId == id
select p
).FirstOrDefault();
// if database-entry does not exist in database, exit
if (query == null) return;
/* if product exists, populate self (this._ProductId and
this._ProductName are both auto-generated private
variables of the entity class which corresponds to the
auto-generated public properties: ProductId and ProductName) */
this._ProductId = query.ProductId;
this._ProductName = query.ProductName;
}
/// <summary>
/// Delete product
/// </summary>
public void Delete()
{
// if self is not poulated, exit
if (this._ProductId == 0) return;
var dc = new BusinessLogicDataContext();
// delete entry in database
dc.Products.DeleteOnSubmit(this);
dc.SubmitChanges();
// reset self (you could implement IDisposable here)
this._ProductId = 0;
this._ProductName = "";
}
}
```
Using the implemented business logic:
```
// new up a product
var p = new Product(1); // p.ProductId: 1, p.ProductName: "A car"
// delete the product
p.Delete(); // p.ProductId: 0, p.ProductName: ""
```
Furthermore: LINQ to SQL entity classes are very open in nature. This means that the property corresponding to the *dbo.Products.ProductId* column implements both a getter and a setter--this field should not be changeable.
To my knowledge you can't override properties using partial classes, so what I usually do is implement a manager which narrows the object using an interface:
```
public interface IProduct
{
Int32 ProductId { get; }
void Delete();
}
```
|
223,940 |
<p>I researched this a while ago and can't remember how to do it. I want to be able to prevent Firefox from running it's spell-checking functionality on certain input fields from within the page. I know it's possible but can't remember how to set it up.</p>
|
[
{
"answer_id": 223948,
"author": "Wilco",
"author_id": 5291,
"author_profile": "https://Stackoverflow.com/users/5291",
"pm_score": 7,
"selected": true,
"text": "<p>Talk about having a big \"duh\" moment! I found the answer after some trial & error:</p>\n\n<pre><code><textarea spellcheck=\"false\"></textarea>\n</code></pre>\n"
},
{
"answer_id": 635873,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The \"spellcheck\" attribute is currently an extra feature available only in Firefox, but it is being <a href=\"http://blog.whatwg.org/the-road-to-html-5-spellchecking\" rel=\"noreferrer\">considered for inclusion in HTML5</a>.</p>\n"
},
{
"answer_id": 739021,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The downside of this is that the W3 strict validator gives - Attribute \"spellcheck\" is not a valid attribute. Bad news for those of us with OCD that love to see 0 errors in validating our sites.</p>\n"
},
{
"answer_id": 3296150,
"author": "Wileez",
"author_id": 397485,
"author_profile": "https://Stackoverflow.com/users/397485",
"pm_score": 3,
"selected": false,
"text": "<p>add the attribute using JQuery $('.textarea_className').attr('spellcheck',false); </p>\n\n<p>This will allow you to return a valid XHTML mark up. =)</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
I researched this a while ago and can't remember how to do it. I want to be able to prevent Firefox from running it's spell-checking functionality on certain input fields from within the page. I know it's possible but can't remember how to set it up.
|
Talk about having a big "duh" moment! I found the answer after some trial & error:
```
<textarea spellcheck="false"></textarea>
```
|
223,946 |
<p>I have two LINQ objects which have exactly the same columns and I would like to be able to update one with the fields from the other. I first create a new object from some data in a file, then I query the database for an existing item with the same ID. What I would like to be able to do is update the existing objects details with the newly created objects details. </p>
<p>So far the way I have been doing it is to list all the columns and update them manually but as you can see this can cause maintenance headaches.</p>
<pre><code> With OldCaller
.ADDRESS = NewCaller.ADDRESS
.COMPANY = NewCaller.COMPANY
.CONTACT_HOURS = NewCaller.CONTACT_HOURS
.CONTACT_NAME = NewCaller.CONTACT_NAME
.CUSTOMER_ID = NewCaller.CUSTOMER_ID
.EMAIL_ADDRESS = NewCaller.EMAIL_ADDRESS
.FAX_NUMBER = NewCaller.FAX_NUMBER
.FAX_TYPE = NewCaller.FAX_TYPE
.MOBILE = NewCaller.MOBILE
.POSTCODE = NewCaller.POSTCODE
.PUBLIC_ADDRESS = NewCaller.PUBLIC_ADDRESS
.PUBLIC_TELEPHONE = NewCaller.PUBLIC_TELEPHONE
.STATE = NewCaller.STATE
.SUBURB = NewCaller.SUBURB
.TELEPHONE = NewCaller.TELEPHONE
End With
</code></pre>
<p>I would like to be able to find a way to clean this up a bit. Does anyone know of a better way to do what I need.</p>
|
[
{
"answer_id": 223980,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": true,
"text": "<p>I do this sort of thing when I create an instance of an object from a template. Basically I have a method that iterates over the public properties of the template, finds the corresponding property in the object being created, and invokes the property setter on the new object, all via reflection.</p>\n"
},
{
"answer_id": 228465,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't tested this yet but this is what I have come up with.</p>\n\n<pre><code> Dim _OldCallerProperties = OldCaller.GetType().GetProperties(Reflection.BindingFlags.Public)\n Dim _NewCallerProperties = NewCaller.GetType.GetProperties(Reflection.BindingFlags.Public)\n\n For Each Prop In _OldCallerProperties\n Dim _matchingProperty = _NewCallerProperties.Where(Function(p) p.Name = Prop.Name).FirstOrDefault\n Dim _newvalue = _matchingProperty.GetValue(_matchingProperty, Nothing)\n Prop.SetValue(Prop, _newvalue, Nothing)\n Next\n</code></pre>\n\n<p>Like I said I haven't tested it but I'm sure it should work.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
I have two LINQ objects which have exactly the same columns and I would like to be able to update one with the fields from the other. I first create a new object from some data in a file, then I query the database for an existing item with the same ID. What I would like to be able to do is update the existing objects details with the newly created objects details.
So far the way I have been doing it is to list all the columns and update them manually but as you can see this can cause maintenance headaches.
```
With OldCaller
.ADDRESS = NewCaller.ADDRESS
.COMPANY = NewCaller.COMPANY
.CONTACT_HOURS = NewCaller.CONTACT_HOURS
.CONTACT_NAME = NewCaller.CONTACT_NAME
.CUSTOMER_ID = NewCaller.CUSTOMER_ID
.EMAIL_ADDRESS = NewCaller.EMAIL_ADDRESS
.FAX_NUMBER = NewCaller.FAX_NUMBER
.FAX_TYPE = NewCaller.FAX_TYPE
.MOBILE = NewCaller.MOBILE
.POSTCODE = NewCaller.POSTCODE
.PUBLIC_ADDRESS = NewCaller.PUBLIC_ADDRESS
.PUBLIC_TELEPHONE = NewCaller.PUBLIC_TELEPHONE
.STATE = NewCaller.STATE
.SUBURB = NewCaller.SUBURB
.TELEPHONE = NewCaller.TELEPHONE
End With
```
I would like to be able to find a way to clean this up a bit. Does anyone know of a better way to do what I need.
|
I do this sort of thing when I create an instance of an object from a template. Basically I have a method that iterates over the public properties of the template, finds the corresponding property in the object being created, and invokes the property setter on the new object, all via reflection.
|
223,964 |
<p>Note: I am just consuming webservice I have no control over webservice code.</p>
<p>So in .net 2.0 I reference the webservice and see a class in the webservice namespace, say foobar. It's defined as:</p>
<pre><code>public class foobar : System.Web.Services.Protocols.SoapHttpClientProtocol
</code></pre>
<p>but in .net 3.5 when i add a reference to the same webservice I no longer have this foobar class available. I do see foobarSoap which is an interface which exposes all of the methods in the foobar class above. It's defined as:</p>
<pre><code>public interface foobarSoap
</code></pre>
<p>However it doesn't expose the properties (for obvious reasons).</p>
<p>I need to access these properties. How do I do it?</p>
|
[
{
"answer_id": 223979,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 1,
"selected": false,
"text": "<p>You can try using the <strong>Web Service Description Language Tool</strong> (<code>Wsdl.exe</code>) to generate an actual class file:</p>\n\n<blockquote>\n <p><code>wsdl.exe /language:cs http://www.example.com/FooService.wsdl</code></p>\n</blockquote>\n\n<p>You can get more information about the <a href=\"http://msdn.microsoft.com/en-us/library/7h3ystb6.aspx\" rel=\"nofollow noreferrer\" title=\"Web Services Description Language Tool (Wsdl.exe)\"><strong>WSDL Tool</strong></a> on it's <a href=\"http://msdn.microsoft.com/en-us/library/7h3ystb6.aspx\" rel=\"nofollow noreferrer\" title=\"Web Services Description Language Tool (Wsdl.exe)\">MSDN Page</a>.</p>\n"
},
{
"answer_id": 224174,
"author": "smaclell",
"author_id": 22914,
"author_profile": "https://Stackoverflow.com/users/22914",
"pm_score": 0,
"selected": false,
"text": "<p>I have a sneaky feeling that the properties will not be part of the service definition (WSDL) which would mean you may not be able to use them. If possible try to convince who ever maintains the service to expose the properties as actual methods.</p>\n\n<p>It is quite likely that you will be unable to access the properties in which case you may just be out of luck. Sorry.</p>\n\n<p>I am going to try exposing a property and then I will report the results back here.</p>\n\n<p>EDIT: Cannot expose an interface property using WCF, it simply will not compile</p>\n\n<pre><code>[ServiceContract]\npublic interface IFooService\n{\n [OperationContract] // This is not allowed, it will not compile\n string Name { get; set; }\n}\n</code></pre>\n\n<p>EDIT: Cannot be done using ASMX web services either. : (</p>\n\n<pre><code>[WebService(Namespace = \"http://tempuri.org/\")]\npublic class FooService : System.Web.Services.WebService\n{\n [WebMethod] // This is not allowed, it will not compile\n string Name { get; set; }\n}\n</code></pre>\n"
},
{
"answer_id": 224192,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 0,
"selected": false,
"text": "<p>I just created a sample project and created a web proxy to the service, using the Add Service Reference menu:</p>\n\n<pre><code>http://www.xmlme.com/WSShakespeare.asmx\n</code></pre>\n\n<p>Visual Studio 2008 generated an interface and a proxy class based on the WSDL. For example, I have a class ShakespeareSoapClient that implements an interface ShakespeareSoap.</p>\n\n<p>It seems to work fine. Am I missing something.</p>\n"
},
{
"answer_id": 369492,
"author": "hmcclungiii",
"author_id": 24333,
"author_profile": "https://Stackoverflow.com/users/24333",
"pm_score": 1,
"selected": true,
"text": "<p>I had a similar problem when I upgraded from 2005 to 2008. I think what you are missing, when you click \"Add Service Reference\", a newer dialog comes up. click the Advanced button at the bottom, then on the next dialog that comes up, click the Add Web Reference button at the bottom, in the compatibility section. Then you'll get the dialog that you are most likely used to, and will have standard 2.0 proxy classes.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Note: I am just consuming webservice I have no control over webservice code.
So in .net 2.0 I reference the webservice and see a class in the webservice namespace, say foobar. It's defined as:
```
public class foobar : System.Web.Services.Protocols.SoapHttpClientProtocol
```
but in .net 3.5 when i add a reference to the same webservice I no longer have this foobar class available. I do see foobarSoap which is an interface which exposes all of the methods in the foobar class above. It's defined as:
```
public interface foobarSoap
```
However it doesn't expose the properties (for obvious reasons).
I need to access these properties. How do I do it?
|
I had a similar problem when I upgraded from 2005 to 2008. I think what you are missing, when you click "Add Service Reference", a newer dialog comes up. click the Advanced button at the bottom, then on the next dialog that comes up, click the Add Web Reference button at the bottom, in the compatibility section. Then you'll get the dialog that you are most likely used to, and will have standard 2.0 proxy classes.
|
223,990 |
<p>I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:</p>
<pre><code>queryset = Modelclass.objects.filter(somekey=foo)
</code></pre>
<p>In my template I would like to do</p>
<pre><code>{% for object in data.somekey_set.FILTER %}
</code></pre>
<p>but I just can't seem to find out how to write FILTER.</p>
|
[
{
"answer_id": 224003,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 8,
"selected": true,
"text": "<p>You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.</p>\n\n<p>So you have several options. The easiest is to do the filtering, then pass the result to <code>render_to_response</code>. Or you could write a method in your model so that you can say <code>{% for object in data.filtered_set %}</code>. Finally, you could write your own template tag, although in this specific case I would advise against that.</p>\n"
},
{
"answer_id": 230615,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 4,
"selected": false,
"text": "<p>I run into this problem on a regular basis and often use the \"add a method\" solution. However, there are definitely cases where \"add a method\" or \"compute it in the view\" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.</p>\n\n<p>Some other possible solutions:</p>\n\n<ol>\n<li><p>Use the {% expr <expression> as <var_name> %} template tag found at <a href=\"http://www.djangosnippets.org/snippets/9/\" rel=\"noreferrer\">http://www.djangosnippets.org/snippets/9/</a> The expression is any legal Python expression with your template's Context as your local scope.</p></li>\n<li><p>Change your template processor. Jinja2 (<a href=\"http://jinja.pocoo.org/2/\" rel=\"noreferrer\">http://jinja.pocoo.org/2/</a>) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that <em>you</em> are working on, but use Django's \"safer\" templates for designer-maintained pages.</p></li>\n</ol>\n"
},
{
"answer_id": 12350892,
"author": "mrmagooey",
"author_id": 599251,
"author_profile": "https://Stackoverflow.com/users/599251",
"pm_score": 4,
"selected": false,
"text": "<p>The other option is that if you have a filter that you always want applied, to add a <a href=\"https://docs.djangoproject.com/en/1.4/topics/db/managers/#custom-managers\">custom manager</a> on the model in question which always applies the filter to the results returned.</p>\n\n<p>A good example of this is a <code>Event</code> model, where for 90% of the queries you do on the model you are going to want something like <code>Event.objects.filter(date__gte=now)</code>, i.e. you're normally interested in <code>Events</code> that are upcoming. This would look like:</p>\n\n<pre><code>class EventManager(models.Manager):\n def get_query_set(self):\n now = datetime.now()\n return super(EventManager,self).get_query_set().filter(date__gte=now)\n</code></pre>\n\n<p>And in the model:</p>\n\n<pre><code>class Event(models.Model):\n ...\n objects = EventManager()\n</code></pre>\n\n<p>But again, this applies the same filter against all default queries done on the <code>Event</code> model and so isn't as flexible some of the techniques described above. </p>\n"
},
{
"answer_id": 14010929,
"author": "chrisv",
"author_id": 683808,
"author_profile": "https://Stackoverflow.com/users/683808",
"pm_score": 3,
"selected": false,
"text": "<p>This can be solved with an assignment tag:</p>\n<pre><code>from django import template\n\nregister = template.Library()\n\[email protected]_tag\ndef query(qs, **kwargs):\n """ template tag which allows queryset filtering. Usage:\n {% query books author=author as mybooks %}\n {% for book in mybooks %}\n ...\n {% endfor %}\n """\n return qs.filter(**kwargs)\n</code></pre>\n<p><strong>EDIT:</strong> assignment_tag was removed in Django 2.0, this will no longer work.</p>\n"
},
{
"answer_id": 16429027,
"author": "tobych",
"author_id": 76452,
"author_profile": "https://Stackoverflow.com/users/76452",
"pm_score": 6,
"selected": false,
"text": "<p>I just add an extra template tag like this:</p>\n\n<pre><code>@register.filter\ndef in_category(things, category):\n return things.filter(category=category)\n</code></pre>\n\n<p>Then I can do:</p>\n\n<pre><code>{% for category in categories %}\n {% for thing in things|in_category:category %}\n {{ thing }}\n {% endfor %}\n{% endfor %}\n</code></pre>\n"
},
{
"answer_id": 61519890,
"author": "Krzysztof Szumko",
"author_id": 11370030,
"author_profile": "https://Stackoverflow.com/users/11370030",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone looking for an answer in 2020.\nThis worked for me.</p>\n\n<p>In Views:</p>\n\n<pre><code> class InstancesView(generic.ListView):\n model = AlarmInstance\n context_object_name = 'settings_context'\n queryset = Group.objects.all()\n template_name = 'insta_list.html'\n\n @register.filter\n def filter_unknown(self, aVal):\n result = aVal.filter(is_known=False)\n return result\n\n @register.filter\n def filter_known(self, aVal):\n result = aVal.filter(is_known=True)\n return result\n</code></pre>\n\n<p>In template:</p>\n\n<pre><code>{% for instance in alarm.qar_alarm_instances|filter_unknown:alarm.qar_alarm_instances %}\n</code></pre>\n\n<p>In pseudocode:</p>\n\n<pre><code>For each in model.child_object|view_filter:filter_arg\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 74538591,
"author": "Pol Clota",
"author_id": 11455992,
"author_profile": "https://Stackoverflow.com/users/11455992",
"pm_score": 0,
"selected": false,
"text": "<p>This is my approach:</p>\n<pre><code>@register.filter()\ndef query_filter(value, attr):\n return value.filter(**eval(attr))\n</code></pre>\n<p>In the template:</p>\n<pre><code>{{ queryset|query_filter:'{"cod_tipoinmueble":1,"des_operacion": "alquiler"}'|length }}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11527/"
] |
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:
```
queryset = Modelclass.objects.filter(somekey=foo)
```
In my template I would like to do
```
{% for object in data.somekey_set.FILTER %}
```
but I just can't seem to find out how to write FILTER.
|
You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.
So you have several options. The easiest is to do the filtering, then pass the result to `render_to_response`. Or you could write a method in your model so that you can say `{% for object in data.filtered_set %}`. Finally, you could write your own template tag, although in this specific case I would advise against that.
|
223,991 |
<p>Because of several iframes, XUL browser elements, and so forth, I have a number of window objects in my XULRunner application. I'm looking for the best way to find the window object that a specified node belongs to using JavaScript.</p>
<p>So, to be more specific, given node x, I need to find the specific window object that contains x.</p>
|
[
{
"answer_id": 224002,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to use <strong>self</strong>. self is a reference to the current document.</p>\n\n<p><strong>From within the iframe:</strong></p>\n\n<pre><code><body>\n<div id=\"example\">Example!</div>\n<script type=\"text/javascript\">\n window.onload = function () {\n var exampleNode = document.getElementById('example');\n exampleNode.bar = function () {\n // The highest window object:\n top;\n // The parent node:\n self;\n // The parent node ( except in IE );\n this.ownerDocument.defaultView;\n };\n };\n</script>\n</body>\n</code></pre>\n\n<p><strong>Traversing Multiple Window Objects:</strong></p>\n\n<p>Within the browser object model, the primary window object is referred to as <strong>top</strong>. Other global objects are arranged in a tree structure which stems from top. With a reference to <strong>top</strong>, you can navigate to the other global objects in the tree by using their <strong>names and relationships</strong>, much in the same way as you <strong>traverse the DOM</strong>.</p>\n\n<p>When you have multiple window objects, as you do in the case of an iframe (of with old school framesets), the frame has a <strong>name attribute</strong>. Given the objects position relative to the top window object, you can use the name of the child to access the object.</p>\n\n<p><code><iframe src =\"/default.html\" name=\"advertisement\"></iframe></code></p>\n\n<p>and then from the context of the top window:</p>\n\n<p><code>self.advertisement</code> </p>\n"
},
{
"answer_id": 224036,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 2,
"selected": false,
"text": "<p>I found the combination of properties I was after:</p>\n\n<p>node.ownerDocument.defaultView</p>\n\n<p>That returns the window object that the node belongs to. Note that this does not work in IE.</p>\n"
},
{
"answer_id": 2728464,
"author": "Marco Demaio",
"author_id": 260080,
"author_profile": "https://Stackoverflow.com/users/260080",
"pm_score": 5,
"selected": true,
"text": "<p>+1 to your question, it was exactly what I was looking for and thanks for the hint given directly by answering yourself.</p>\n\n<p>I Googled a bit and according to <a href=\"http://www.quirksmode.org/dom/w3c_html.html\" rel=\"noreferrer\">http://www.quirksmode.org/dom/w3c_html.html</a> cross-browsers tables I think the right answer is:</p>\n\n<pre><code>function GetOwnerWindow(html_node)\n{\n /*\n ownerDocument is cross-browser, \n but defaultView works on all browsers except Opera/IE that use parentWinow\n */\n return (html_node.ownerDocument.defaultView) ?\n html_node.ownerDocument.defaultView : \n html_node.ownerDocument.parentWindow;\n}\n</code></pre>\n\n<p>Or maybe even better:</p>\n\n<pre><code>return html_node.ownerDocument.defaultView || html_node.ownerDocument.parentWindow;\n</code></pre>\n\n<p>Plz let me know your thoughts.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7441/"
] |
Because of several iframes, XUL browser elements, and so forth, I have a number of window objects in my XULRunner application. I'm looking for the best way to find the window object that a specified node belongs to using JavaScript.
So, to be more specific, given node x, I need to find the specific window object that contains x.
|
+1 to your question, it was exactly what I was looking for and thanks for the hint given directly by answering yourself.
I Googled a bit and according to <http://www.quirksmode.org/dom/w3c_html.html> cross-browsers tables I think the right answer is:
```
function GetOwnerWindow(html_node)
{
/*
ownerDocument is cross-browser,
but defaultView works on all browsers except Opera/IE that use parentWinow
*/
return (html_node.ownerDocument.defaultView) ?
html_node.ownerDocument.defaultView :
html_node.ownerDocument.parentWindow;
}
```
Or maybe even better:
```
return html_node.ownerDocument.defaultView || html_node.ownerDocument.parentWindow;
```
Plz let me know your thoughts.
|
223,993 |
<p>I'm in the process of trying to move our company from SalesForce to SugarCRM, but I've run in to a nasty bug (the moment I add a custom field to Accounts, all accounts stop showing up). We've paid for support from the SugarCRM people, but they only have take-forever-then-get-a-worthless-response-level tech support for the open-source version (and we avoid proprietary software like the plague). Oh, and did I mention our Salesforce contract expires at the end of the week?</p>
<p>So, long story short, I'm stuck debugging the SugarCRM app myself. I'm an decently experienced programmer, and I have baseline PHP competency, but I don't even know where to being trying to solve this issue. Can any Sugar developers out there recommend any kind of process for debugging Sugar? Are there any resources out there that would help me to understand what the different PHP files do, or how the Sugar system works overall? </p>
<p>Just as an example of the sort of thing I'm talking about: I figured out how to get sugar to print stack traces, and by following several I noticed a pattern with all the problem lines involving <pre>$this->_tpl_vars</pre>
I'd love to try and figure out why that method call isn't working, but I don't know:</p>
<p>A) what <code>_tpl_vars</code> is supposed to do<br/>
B) where <code>_tpl_vars</code> is defined<br/>
C) what <code>$this</code> is supposed to be<br/>
D) where in the framework <code>$this</code> gets set<br/>
etc.</p>
<p>So if anyone can help explain how/where I would start finding answers to these questions, I'd be incredibly grateful.</p>
|
[
{
"answer_id": 231775,
"author": "machineghost",
"author_id": 5921,
"author_profile": "https://Stackoverflow.com/users/5921",
"pm_score": 3,
"selected": true,
"text": "<p>Although it's not a perfect answer to my question, this article:</p>\n\n<p><a href=\"http://developers.sugarcrm.com/wordpress/2008/09/26/where-is-the-code-for-x/\" rel=\"nofollow noreferrer\">http://developers.sugarcrm.com/wordpress/2008/09/26/where-is-the-code-for-x/</a></p>\n\n<p>did help a bit. Also when I looked further through the official Sugar docs I found that the Developer Guide does contain some explanation of how Sugar works (although obviously it's not as focused on how Sugar works so much as it's focused on how to make Sugar do new things).</p>\n\n<p>Hope that helps any other burgeoning Sugar devs out there.</p>\n"
},
{
"answer_id": 234267,
"author": "Nack",
"author_id": 28314,
"author_profile": "https://Stackoverflow.com/users/28314",
"pm_score": 4,
"selected": false,
"text": "<p>I worked with SugarCRM a couple years ago, and although I loved what I saw on the surface, I ended up rejecting it for our project because of what you are experiencing now. The internals of the product are woefully underdocumented. I had envisioned writing a bunch of slick modules for the product, but the resources just don't exist. You'll spend all your time digging through code, pouring over forum posts, and trying to find examples of what you're trying to accomplish. Doesn't sound like things have gotten much better.</p>\n\n<p>Given that your PHP experience is less-than-guru level, and you're undoubtedly busy with a lot of other tasks and deadlines, I think you should maybe reconsider this transition if it's not too late, at least until you get a better comfort level with Sugar. If you're forced to move to Sugar because of an expiring contract with Salesforce, I think you might be in for some serious heartburn!</p>\n"
},
{
"answer_id": 238875,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 0,
"selected": false,
"text": "<p><code>$this</code> is a reference to the current object. </p>\n\n<pre><code>class Test {\n\n var $tmp;\n\n function __construct() {\n $this->tmp = 42; \n }\n}\n</code></pre>\n"
},
{
"answer_id": 1686333,
"author": "Leon",
"author_id": 204606,
"author_profile": "https://Stackoverflow.com/users/204606",
"pm_score": 2,
"selected": false,
"text": "<p>These code are coming from Smarty lib, not coming from SugarCRM directly.</p>\n\n<p>Maybe this chm doc will be a little helpful, <a href=\"http://code.google.com/p/sugardoc/downloads/list\" rel=\"nofollow noreferrer\">http://code.google.com/p/sugardoc/downloads/list</a>.</p>\n"
},
{
"answer_id": 1688398,
"author": "webXL",
"author_id": 203891,
"author_profile": "https://Stackoverflow.com/users/203891",
"pm_score": 2,
"selected": false,
"text": "<p>You can also try installing xdebug (PHP extension) and stepping through the code with a compatible IDE such as eclipse or Komodo. </p>\n\n<p>The URL tells you which module directory is being accessed and which action/view. There's a \"views\" folder under most modules. If it's not there, it's either using the default MVC view in the include folder in conjunction with the metadata layout, or it's using the classic view architecture: index.php (listview), DetailView.php, and EditView.php and templates. </p>\n\n<p>A lot has changed for the better in the last couple years, so I'm not sure the first answer (Nack) is still relevant. It's still pretty rough around the edges, but the new Sugar framework is a PHP hacker's best friend (really easy to override stuff in an upgrade-friendly manner). It's great for companies who happen to already have PHP hackers and only need a few enhancements. And finding affordable PHP contractors to help out isn't that hard (disclaimer: I am one). I think it's a great tool if you're into open source, just need basic CRM and have fewer than 100 users. </p>\n"
},
{
"answer_id": 2403469,
"author": "p3drosola",
"author_id": 249161,
"author_profile": "https://Stackoverflow.com/users/249161",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest making sure that it really is a code bug and not just a miss config. Are you adding the field through Admin > Studio > Contacts > Fields or through the SOAP API ?</p>\n\n<p>Are you using the latest version of Sugar?</p>\n\n<p>I really agree that the project it horribly under-documented and lacking in tutorials and examples.</p>\n\n<p>I myself am experiencing the pains of outdated / missing documentation. \nGood luck! </p>\n"
},
{
"answer_id": 3958388,
"author": "Eitrix",
"author_id": 521216,
"author_profile": "https://Stackoverflow.com/users/521216",
"pm_score": 2,
"selected": false,
"text": "<p>tpl is smarty template files. They are used when displaying data on screen. How i do my debuging proces is create a lot of var dumps to error lof or just print them on screen.</p>\n\n<p>Also get xdebug on the server, this will help you a lot. Sugar is mvc platform so get knowing how that works, and will be much easier then.</p>\n\n<p>take a look at some snippets i post at www.eontek.rs</p>\n"
},
{
"answer_id": 7578205,
"author": "sikk",
"author_id": 964730,
"author_profile": "https://Stackoverflow.com/users/964730",
"pm_score": 2,
"selected": false,
"text": "<p>If I encountered the same problem, when the detail page of the account wasn't displayed and gave 500 internal error. I checked that it was not generated by the TPL. At first I checked the permissions on that folder, in my case they were all set. So I took the backup of cache\\modules\\accounts\\DetailView.tpl and manually added the field, after that everything worked. Every time in the developer mode there's a need to manually copy this file. It's a pain, but there's still no answer. I have asked this in forums, Bug, Twitter, no help. By the way, we are using Sugar Professional.</p>\n"
},
{
"answer_id": 7770002,
"author": "dkinzer",
"author_id": 256854,
"author_profile": "https://Stackoverflow.com/users/256854",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <a href=\"http://krumo.sourceforge.net/\" rel=\"nofollow noreferrer\">Krumo</a> library to help. It's super easy and way better than <code>var_dump</code> or <code>print_r</code>.</p>\n\n<p>Simply download the source code and add it somewhere in your custom folder. I use the custom/include folder.</p>\n\n<p>Then override a View or whatever you need to look at. Include the path to file class.krumo.php file, and krumo whatever object you want to take a look at:</p>\n\n<p>Quick example - </p>\n\n<pre><code><?php\n require_once('include/MVC/View/views/view.detail.php');\n require_once('custom/include/krumo/class.krumo.php');\n class AccountsViewDetail extends ViewDetail {\n\n function AccountsViewDetail() {\n parent::ViewDetail();\n }\n\n // Override the parent function \"preDisplay\" to add our own template\n function preDisplay(){\n krumo($this->bean);\n $metadataFile = $this->getMetaDataFile();\n $this->dv = new DetailView2();\n $this->dv->ss =& $this->ss;\n $this->dv->setup($this->module, $this->bean, $metadataFile, 'custom/modules/Accounts/tpls/AccountsDetailView.tpl');\n }\n\n\n }\n?>\n</code></pre>\n\n<p>You'll get a nice object on the page that you can drill into.</p>\n\n<p><img src=\"https://i.stack.imgur.com/NWNdJ.png\" alt=\"enter image description here\"></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/223993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5921/"
] |
I'm in the process of trying to move our company from SalesForce to SugarCRM, but I've run in to a nasty bug (the moment I add a custom field to Accounts, all accounts stop showing up). We've paid for support from the SugarCRM people, but they only have take-forever-then-get-a-worthless-response-level tech support for the open-source version (and we avoid proprietary software like the plague). Oh, and did I mention our Salesforce contract expires at the end of the week?
So, long story short, I'm stuck debugging the SugarCRM app myself. I'm an decently experienced programmer, and I have baseline PHP competency, but I don't even know where to being trying to solve this issue. Can any Sugar developers out there recommend any kind of process for debugging Sugar? Are there any resources out there that would help me to understand what the different PHP files do, or how the Sugar system works overall?
Just as an example of the sort of thing I'm talking about: I figured out how to get sugar to print stack traces, and by following several I noticed a pattern with all the problem lines involving
```
$this->_tpl_vars
```
I'd love to try and figure out why that method call isn't working, but I don't know:
A) what `_tpl_vars` is supposed to do
B) where `_tpl_vars` is defined
C) what `$this` is supposed to be
D) where in the framework `$this` gets set
etc.
So if anyone can help explain how/where I would start finding answers to these questions, I'd be incredibly grateful.
|
Although it's not a perfect answer to my question, this article:
<http://developers.sugarcrm.com/wordpress/2008/09/26/where-is-the-code-for-x/>
did help a bit. Also when I looked further through the official Sugar docs I found that the Developer Guide does contain some explanation of how Sugar works (although obviously it's not as focused on how Sugar works so much as it's focused on how to make Sugar do new things).
Hope that helps any other burgeoning Sugar devs out there.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.