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 |
|---|---|---|---|---|---|---|
142,845 | <p>I'm working on an application that consists of an overall Quartz-based scheduler and "CycledJob" run using CronTriggers. The purpose of the application is to process inputs from different email inboxes based on the source country. </p>
<p>Based on the country that it comes in from (i.e. US, UK, FR, etc.) the application triggers one job thread to run each country's processing cycle, so there would be a UK Worker thread, one for US, France, etc. When formatting the output to log4j, I'm using the thread parameter, so it emits [ApplicationName_Worker-1], [ApplicationName_Worker-2] etc. Try as I might, I can't find a way to name the threads since they're pulled out of Quartz's Thread Pools. Although I could possibly go so far as to extend Quartz, I'd like to work out a different solution instead of messing with the standard library.</p>
<p>Here's the problem: When using log4j, I'd like to have all log items from the US thread output to a US only file, likewise for each of the country threads. I don't care if they stay in one unified ConsoleAppender, the FileAppender split is what I'm after here. I already know how to specify multiple file appenders and such, my issue is I can't differentiate based on country. There are 20+ classes within the application that can be on the execution chain, very few of which I want to burden with the knowledge of passing an extra "context" parameter through EVERY method... I've considered a Strategy pattern extending a log4j wrapper class, but unless I can let every class in the chain know which thread it's on to parameterize the logger call, that seems impossible. Without being able to name the thread also creates a challenge (or else this would be easy!).</p>
<p>So here's the question: What would be a suggested approach to allow many subordinate classes in an application that are each used for every different thread to process the input know that they are within the context of a particular country thread when they are logging?</p>
<p>Good luck understanding, and please ask clarifying questions! I hope someone is able to help me figure out a decent way to tackle this. All suggestions welcome.</p>
| [
{
"answer_id": 142920,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 2,
"selected": false,
"text": "<p>I wish I could be a bit more helpful than this, but you may want to investigate using some filters? Perhaps your logging c... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18402/"
] | I'm working on an application that consists of an overall Quartz-based scheduler and "CycledJob" run using CronTriggers. The purpose of the application is to process inputs from different email inboxes based on the source country.
Based on the country that it comes in from (i.e. US, UK, FR, etc.) the application triggers one job thread to run each country's processing cycle, so there would be a UK Worker thread, one for US, France, etc. When formatting the output to log4j, I'm using the thread parameter, so it emits [ApplicationName\_Worker-1], [ApplicationName\_Worker-2] etc. Try as I might, I can't find a way to name the threads since they're pulled out of Quartz's Thread Pools. Although I could possibly go so far as to extend Quartz, I'd like to work out a different solution instead of messing with the standard library.
Here's the problem: When using log4j, I'd like to have all log items from the US thread output to a US only file, likewise for each of the country threads. I don't care if they stay in one unified ConsoleAppender, the FileAppender split is what I'm after here. I already know how to specify multiple file appenders and such, my issue is I can't differentiate based on country. There are 20+ classes within the application that can be on the execution chain, very few of which I want to burden with the knowledge of passing an extra "context" parameter through EVERY method... I've considered a Strategy pattern extending a log4j wrapper class, but unless I can let every class in the chain know which thread it's on to parameterize the logger call, that seems impossible. Without being able to name the thread also creates a challenge (or else this would be easy!).
So here's the question: What would be a suggested approach to allow many subordinate classes in an application that are each used for every different thread to process the input know that they are within the context of a particular country thread when they are logging?
Good luck understanding, and please ask clarifying questions! I hope someone is able to help me figure out a decent way to tackle this. All suggestions welcome. | At the top of each country's processing thread, put the country code into Log4j's mapped diagnostic context (MDC). This uses a ThreadLocal variable so that you don't have to pass the country up and down the call stack explicitly. Then create a custom filter that looks at the MDC, and filters out any events that don't contain the current appender's country code.
In your `Job`:
```
...
public static final String MDC_COUNTRY = "com.y.foo.Country";
public void execute(JobExecutionContext context)
/* Just guessing that you have the country in your JobContext. */
MDC.put(MDC_COUNTRY, context.get(MDC_COUNTRY));
try {
/* Perform your job here. */
...
} finally {
MDC.remove(MDC_COUNTRY);
}
}
...
```
Write a custom [Filter](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html):
```
package com.y.log4j;
import org.apache.log4j.spi.LoggingEvent;
/**
* This is a general purpose filter. If its "value" property is null,
* it requires only that the specified key be set in the MDC. If its
* value is not null, it further requires that the value in the MDC
* is equal.
*/
public final class ContextFilter extends org.apache.log4j.spi.Filter {
public int decide(LoggingEvent event) {
Object ctx = event.getMDC(key);
if (value == null)
return (ctx != null) ? NEUTRAL : DENY;
else
return value.equals(ctx) ? NEUTRAL : DENY;
}
private String key;
private String value;
public void setContextKey(String key) { this.key = key; }
public String getContextKey() { return key; }
public void setValue(String value) { this.value = value; }
public String getValue() { return value; }
}
```
In your log4j.xml:
```
<appender name="fr" class="org.apache.log4j.FileAppender">
<param name="file" value="france.log"/>
...
<filter class="com.y.log4j.ContextFilter">
<param name="key" value="com.y.foo.Country" />
<param name="value" value="fr" />
</filter>
</appender>
``` |
142,863 | <p><em>Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate? I also believe the question, detail, and response is much better than the referenced question.</em></p>
<p>I've been a C++ programmer for quite a while but I'm new to Java and new to Eclipse. I want to use the <a href="http://sourceforge.net/project/showfiles.php?group_id=30469&package_id=23976" rel="nofollow noreferrer">touch graph "Graph Layout" code</a> to visualize some data I'm working with.</p>
<p>This code is organized like this:</p>
<pre><code>./com
./com/touchgraph
./com/touchgraph/graphlayout
./com/touchgraph/graphlayout/Edge.java
./com/touchgraph/graphlayout/GLPanel.java
./com/touchgraph/graphlayout/graphelements
./com/touchgraph/graphlayout/graphelements/GESUtils.java
./com/touchgraph/graphlayout/graphelements/GraphEltSet.java
./com/touchgraph/graphlayout/graphelements/ImmutableGraphEltSet.java
./com/touchgraph/graphlayout/graphelements/Locality.java
./com/touchgraph/graphlayout/graphelements/TGForEachEdge.java
./com/touchgraph/graphlayout/graphelements/TGForEachNode.java
./com/touchgraph/graphlayout/graphelements/TGForEachNodePair.java
./com/touchgraph/graphlayout/graphelements/TGNodeQueue.java
./com/touchgraph/graphlayout/graphelements/VisibleLocality.java
./com/touchgraph/graphlayout/GraphLayoutApplet.java
./com/touchgraph/graphlayout/GraphListener.java
./com/touchgraph/graphlayout/interaction
./com/touchgraph/graphlayout/interaction/DragAddUI.java
./com/touchgraph/graphlayout/interaction/DragMultiselectUI.java
./com/touchgraph/graphlayout/interaction/DragNodeUI.java
./com/touchgraph/graphlayout/interaction/GLEditUI.java
./com/touchgraph/graphlayout/interaction/GLNavigateUI.java
./com/touchgraph/graphlayout/interaction/HVRotateDragUI.java
./com/touchgraph/graphlayout/interaction/HVScroll.java
./com/touchgraph/graphlayout/interaction/HyperScroll.java
./com/touchgraph/graphlayout/interaction/LocalityScroll.java
./com/touchgraph/graphlayout/interaction/RotateScroll.java
./com/touchgraph/graphlayout/interaction/TGAbstractClickUI.java
./com/touchgraph/graphlayout/interaction/TGAbstractDragUI.java
./com/touchgraph/graphlayout/interaction/TGAbstractMouseMotionUI.java
./com/touchgraph/graphlayout/interaction/TGAbstractMousePausedUI.java
./com/touchgraph/graphlayout/interaction/TGSelfDeactivatingUI.java
./com/touchgraph/graphlayout/interaction/TGUIManager.java
./com/touchgraph/graphlayout/interaction/TGUserInterface.java
./com/touchgraph/graphlayout/interaction/ZoomScroll.java
./com/touchgraph/graphlayout/LocalityUtils.java
./com/touchgraph/graphlayout/Node.java
./com/touchgraph/graphlayout/TGAbstractLens.java
./com/touchgraph/graphlayout/TGException.java
./com/touchgraph/graphlayout/TGLayout.java
./com/touchgraph/graphlayout/TGLensSet.java
./com/touchgraph/graphlayout/TGPaintListener.java
./com/touchgraph/graphlayout/TGPanel.java
./com/touchgraph/graphlayout/TGPoint2D.java
./com/touchgraph/graphlayout/TGScrollPane.java
./TG-APACHE-LICENSE.txt
./TGGL ReleaseNotes.txt
./TGGraphLayout.html
./TGGraphLayout.jar
</code></pre>
<p>How do I add this project in Eclipse and get it compiling and running quickly?</p>
| [
{
"answer_id": 142880,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 4,
"selected": false,
"text": "<p>This assumes Eclipse and an appropriate JDK are installed on your system</p>\n\n<ol>\n<li>Open Eclipse and create a new... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22917/"
] | *Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate? I also believe the question, detail, and response is much better than the referenced question.*
I've been a C++ programmer for quite a while but I'm new to Java and new to Eclipse. I want to use the [touch graph "Graph Layout" code](http://sourceforge.net/project/showfiles.php?group_id=30469&package_id=23976) to visualize some data I'm working with.
This code is organized like this:
```
./com
./com/touchgraph
./com/touchgraph/graphlayout
./com/touchgraph/graphlayout/Edge.java
./com/touchgraph/graphlayout/GLPanel.java
./com/touchgraph/graphlayout/graphelements
./com/touchgraph/graphlayout/graphelements/GESUtils.java
./com/touchgraph/graphlayout/graphelements/GraphEltSet.java
./com/touchgraph/graphlayout/graphelements/ImmutableGraphEltSet.java
./com/touchgraph/graphlayout/graphelements/Locality.java
./com/touchgraph/graphlayout/graphelements/TGForEachEdge.java
./com/touchgraph/graphlayout/graphelements/TGForEachNode.java
./com/touchgraph/graphlayout/graphelements/TGForEachNodePair.java
./com/touchgraph/graphlayout/graphelements/TGNodeQueue.java
./com/touchgraph/graphlayout/graphelements/VisibleLocality.java
./com/touchgraph/graphlayout/GraphLayoutApplet.java
./com/touchgraph/graphlayout/GraphListener.java
./com/touchgraph/graphlayout/interaction
./com/touchgraph/graphlayout/interaction/DragAddUI.java
./com/touchgraph/graphlayout/interaction/DragMultiselectUI.java
./com/touchgraph/graphlayout/interaction/DragNodeUI.java
./com/touchgraph/graphlayout/interaction/GLEditUI.java
./com/touchgraph/graphlayout/interaction/GLNavigateUI.java
./com/touchgraph/graphlayout/interaction/HVRotateDragUI.java
./com/touchgraph/graphlayout/interaction/HVScroll.java
./com/touchgraph/graphlayout/interaction/HyperScroll.java
./com/touchgraph/graphlayout/interaction/LocalityScroll.java
./com/touchgraph/graphlayout/interaction/RotateScroll.java
./com/touchgraph/graphlayout/interaction/TGAbstractClickUI.java
./com/touchgraph/graphlayout/interaction/TGAbstractDragUI.java
./com/touchgraph/graphlayout/interaction/TGAbstractMouseMotionUI.java
./com/touchgraph/graphlayout/interaction/TGAbstractMousePausedUI.java
./com/touchgraph/graphlayout/interaction/TGSelfDeactivatingUI.java
./com/touchgraph/graphlayout/interaction/TGUIManager.java
./com/touchgraph/graphlayout/interaction/TGUserInterface.java
./com/touchgraph/graphlayout/interaction/ZoomScroll.java
./com/touchgraph/graphlayout/LocalityUtils.java
./com/touchgraph/graphlayout/Node.java
./com/touchgraph/graphlayout/TGAbstractLens.java
./com/touchgraph/graphlayout/TGException.java
./com/touchgraph/graphlayout/TGLayout.java
./com/touchgraph/graphlayout/TGLensSet.java
./com/touchgraph/graphlayout/TGPaintListener.java
./com/touchgraph/graphlayout/TGPanel.java
./com/touchgraph/graphlayout/TGPoint2D.java
./com/touchgraph/graphlayout/TGScrollPane.java
./TG-APACHE-LICENSE.txt
./TGGL ReleaseNotes.txt
./TGGraphLayout.html
./TGGraphLayout.jar
```
How do I add this project in Eclipse and get it compiling and running quickly? | 1. Create a new Java project in Eclipse. This will create a src folder (to contain your source files).
2. Also create a lib folder (the name isn't that important, but it follows standard conventions).
3. Copy the `./com/*` folders into the `/src` folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).
4. Copy any dependencies (`jar` files that your project itself depends on) into `/lib` (note that this **should NOT** include the `TGGL jar` - *thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!*)
5. Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app)
6. Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents.
7. The content of the `/src` folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). **If you have dependencies** (which you don't in your current project, but I'll include this here for completeness), **the compile will fail initially because you are missing the dependency `jar files` from the project classpath.**
8. Finally, open the `/lib` folder in Eclipse, `right click` on each required `jar file` and choose `Build Path->Add` to build path.
That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it. |
142,868 | <p>How do I change Oracle from port 8080? My Eclipse is using 8080, so I can't use that.</p>
| [
{
"answer_id": 142889,
"author": "Brad Bruce",
"author_id": 5008,
"author_profile": "https://Stackoverflow.com/users/5008",
"pm_score": 3,
"selected": false,
"text": "<p>I assume you're talking about the Apache server that Oracle installs. Look for the file httpd.conf. </p>\n\n<p>Open ... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22916/"
] | How do I change Oracle from port 8080? My Eclipse is using 8080, so I can't use that. | From Start | Run open a command window.
Assuming your environmental variables are set correctly start with the following:
```
C:\>sqlplus /nolog
SQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008
Copyright (c) 1982, 2005, Oracle. All rights reserved.
SQL> connect
Enter user-name: system
Enter password: <enter password if will not be visible>
Connected.
SQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port]
PL/SQL procedure successfully completed.
SQL>quit
```
then open browser and use 3010 port. |
142,877 | <p>I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore. </p>
<p>There are several places in the codebase where it would clean up the code substantially if only there were a way to make the pre-processor ignore certain <code>#includes</code> if the file didn't exist in the current folder. Does anyone know a way to achieve that?</p>
<p>Presently, we use an <code>#ifdef</code> around the <code>#include</code> in the shared file, with a second project-specific file that #defines whether or not the <code>#include</code> exists in the project. This works, but it's ugly. People often forget to properly update the definitions when they add or remove files from the project. I've contemplated writing a pre-build tool to keep this file up to date, but if there's a platform-independent way to do this with the preprocessor I'd much rather do it that way instead. Any ideas?</p>
| [
{
"answer_id": 142884,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You could have a pre-build step run that generates an include file that contains a list of #defines that represent the... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore.
There are several places in the codebase where it would clean up the code substantially if only there were a way to make the pre-processor ignore certain `#includes` if the file didn't exist in the current folder. Does anyone know a way to achieve that?
Presently, we use an `#ifdef` around the `#include` in the shared file, with a second project-specific file that #defines whether or not the `#include` exists in the project. This works, but it's ugly. People often forget to properly update the definitions when they add or remove files from the project. I've contemplated writing a pre-build tool to keep this file up to date, but if there's a platform-independent way to do this with the preprocessor I'd much rather do it that way instead. Any ideas? | Generally this is done by using a script that tries running the preprocessor on an attempt at including the file. Depending on if the preprocessor returns an error, the script updates a generated .h file with an appropriate #define (or #undef). In bash, the script might look vaguely like this:
```
cat > .test.h <<'EOM'
#include <asdf.h>
EOM
if gcc -E .test.h
then
echo '#define HAVE_ASDF_H 1' >> config.h
else
echo '#ifdef HAVE_ASDF_H' >> config.h
echo '# undef HAVE_ASDF_H' >> config.h
echo '#endif' >> config.h
fi
```
A pretty thorough framework for portably working with portability checks like this (as well as thousands others) is [autoconf](http://www.gnu.org/software/autoconf/). |
142,903 | <p>I started playing around with Linq today and ran into a problem I couldn't find an answer to. I was querying a simple SQL Server database that had some employee records. One of the fields is the full name (cn). I thought it would be interesting to group by the first name by splitting the full name at the first space. I tried</p>
<pre><code>group by person.cn.Split(separators)[0]
</code></pre>
<p>but ran into a lengthy runtime exception (looked a lot like a C++ template instantiation error).</p>
<p>Then I tried grouping by a few letters of the first name:</p>
<pre><code>group by person.cn.Substring(0,5)
</code></pre>
<p>and that worked fine but is not what I want.</p>
<p>I'm wondering about two things:</p>
<ul>
<li>Why does the first example not work when it looks so close to the second?</li>
<li>Knowing that behind the scenes it's SQL stuff going on, what's a good way to do this kind of thing efficiently</li>
</ul>
<p>Thanks,</p>
<p>Andrew</p>
| [
{
"answer_id": 143078,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "<p>Split has no translation into SQL.</p>\n\n<p>So, how to do this string manipulation without split? Cheat like hell (untest... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18321/"
] | I started playing around with Linq today and ran into a problem I couldn't find an answer to. I was querying a simple SQL Server database that had some employee records. One of the fields is the full name (cn). I thought it would be interesting to group by the first name by splitting the full name at the first space. I tried
```
group by person.cn.Split(separators)[0]
```
but ran into a lengthy runtime exception (looked a lot like a C++ template instantiation error).
Then I tried grouping by a few letters of the first name:
```
group by person.cn.Substring(0,5)
```
and that worked fine but is not what I want.
I'm wondering about two things:
* Why does the first example not work when it looks so close to the second?
* Knowing that behind the scenes it's SQL stuff going on, what's a good way to do this kind of thing efficiently
Thanks,
Andrew | Split has no translation into SQL.
So, how to do this string manipulation without split? Cheat like hell (untested):
```
string oneSpace = " ";
string fiftySpace = " ";
var query =
from person in db.Persons
let lastname = person.cn.Replace(oneSpace, fiftySpace).SubString(0, 50).Trim()
group person by lastname into g
select new { Key = g.Key, Count = g.Count };
``` |
142,944 | <p>I remember seeing the code for a Highpass filter a few days back somewhere in the samples, however I can't find it anywhere now! Could someone remember me where the Highpass filter implementation code was?</p>
<p>Or better yet post the algorithm?</p>
<p>Thanks!</p>
| [
{
"answer_id": 142962,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://idevkit.com/forums/tutorials-code-samples-sdk/171-accelerometer-high-pass-filter-incorrect-apple-code.... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | I remember seeing the code for a Highpass filter a few days back somewhere in the samples, however I can't find it anywhere now! Could someone remember me where the Highpass filter implementation code was?
Or better yet post the algorithm?
Thanks! | [From the idevkit.com forums:](http://idevkit.com/forums/tutorials-code-samples-sdk/171-accelerometer-high-pass-filter-incorrect-apple-code.html)
```
#define kFilteringFactor 0.1
static UIAccelerationValue rollingX=0, rollingY=0, rollingZ=0;
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
// Calculate low pass values
rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));
rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor));
rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor));
// Subtract the low-pass value from the current value to get a simplified high-pass filter
float accelX = acceleration.x - rollingX;
float accelY = acceleration.y - rollingY;
float accelZ = acceleration.z - rollingZ;
// Use the acceleration data.
}
``` |
142,965 | <p>An existing Java site is designed to run under "/" on tomcat and there are many specific references to fixed absolute paths like "/dir/dir/page".</p>
<p>Want to migrate this to Java EE packaging, where the site will need to run under a context-root e.g. "/dir/dir/page" becomes "/my-context-root/dir/dir/page"</p>
<p>Now, the context-root can be easily with ServletRequest.getContextPath(), but that still means a lot of code changes to migrate a large code base. Most of these references are in literal HTML.</p>
<p>I've experimented with using servlet filters to do rewrites on the oubound HTML, and that seems to work fine. But it does introduce some overhead, and I wouldn't see it as a permanent solution. (see <a href="http://github.com/tardate/sources/tree/master%2FEnforceContextRootFilter-1.0-src.zip?raw=true" rel="nofollow noreferrer">EnforceContextRootFilter-1.0-src.zip</a> for the servlet filter approach).</p>
<p>Are there any better approaches to solving this problem? Anything obvious I'm missing? All comments appreciated!</p>
| [
{
"answer_id": 143115,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>the apache world used Redirects(mod_rewrite) to do the same.</p>\n\n<p>The Servlet world started using filters</p>\n\n<p... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6329/"
] | An existing Java site is designed to run under "/" on tomcat and there are many specific references to fixed absolute paths like "/dir/dir/page".
Want to migrate this to Java EE packaging, where the site will need to run under a context-root e.g. "/dir/dir/page" becomes "/my-context-root/dir/dir/page"
Now, the context-root can be easily with ServletRequest.getContextPath(), but that still means a lot of code changes to migrate a large code base. Most of these references are in literal HTML.
I've experimented with using servlet filters to do rewrites on the oubound HTML, and that seems to work fine. But it does introduce some overhead, and I wouldn't see it as a permanent solution. (see [EnforceContextRootFilter-1.0-src.zip](http://github.com/tardate/sources/tree/master%2FEnforceContextRootFilter-1.0-src.zip?raw=true) for the servlet filter approach).
Are there any better approaches to solving this problem? Anything obvious I'm missing? All comments appreciated! | Check out a related [question](https://stackoverflow.com/questions/125359/any-clever-ways-of-handling-the-context-in-a-web-app)
Also consider [URLRewriteFilter](http://tuckey.org/urlrewrite/)
Another thing (I keep editing this darn post). If you're using JSP (versus static HTML or something else) you could also create a Tag File to replace the common html tags with links (notably a, img, form). So <a href="/root/path">link</a> can become <t:a href="/root/path">link</t:a>. Then the tag can do the translation for you.
This change can be easily done "en masse", using something like sed.
```
sed -e 's/<a/<t:a/g' -e 's/<\/a>/<\/t:a>/g' old/x.jsp > new/x.jsp
```
Form actions may be a bit trickier than sed, but you get the idea. |
142,972 | <p>I have a series of ASCII flat files coming in from a mainframe to be processed by a C# application. A new feed has been introduced with a Packed Decimal (COMP-3) field, which needs to be converted to a numerical value.</p>
<p>The files are being transferred via FTP, using ASCII transfer mode. I am concerned that the binary field may contain what will be interpreted as very-low ASCII codes or control characters instead of a value - Or worse, may be lost in the FTP process.</p>
<p>What's more, the fields are being read as strings. I may have the flexibility to work around this part (i.e. a stream of some sort), but the business will give me pushback.</p>
<p>The requirement read "Convert from HEX to ASCII", but clearly that didn't yield the correct values. Any help would be appreciated; it need not be language-specific as long as you can explain the logic of the conversion process.</p>
| [
{
"answer_id": 143001,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 2,
"selected": false,
"text": "<p>I apologize if I am way off base here, but perhaps this code sample I'll paste here could help you. This came f... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11112/"
] | I have a series of ASCII flat files coming in from a mainframe to be processed by a C# application. A new feed has been introduced with a Packed Decimal (COMP-3) field, which needs to be converted to a numerical value.
The files are being transferred via FTP, using ASCII transfer mode. I am concerned that the binary field may contain what will be interpreted as very-low ASCII codes or control characters instead of a value - Or worse, may be lost in the FTP process.
What's more, the fields are being read as strings. I may have the flexibility to work around this part (i.e. a stream of some sort), but the business will give me pushback.
The requirement read "Convert from HEX to ASCII", but clearly that didn't yield the correct values. Any help would be appreciated; it need not be language-specific as long as you can explain the logic of the conversion process. | First of all you must eliminate the end of line (EOL) translation problems that will be caused by ASCII transfer mode. You are absolutely right to be concerned about data corruption when the BCD values happen to correspond to EOL characters. The worst aspect of this problem is that it will occur rarely and unexpectedly.
The best solution is to change the transfer mode to BIN. This is appropriate since the data you are transferring is binary. If it is not possible to use the correct FTP transfer mode, you can undo the ASCII mode damage in code. All you have to do is convert \r\n pairs back to \n. If I were you I would make sure this is well tested.
Once you've dealt with the EOL problem, the COMP-3 conversion is pretty straigtforward. I was able to find [this article](http://support.microsoft.com/kb/65323) in the MS knowledgebase with sample code in BASIC. See below for a VB.NET port of this code.
Since you're dealing with COMP-3 values, the file format you're reading almost surely has fixed record sizes with fixed field lengths. If I were you, I would get my hands of a file format specification before you go any further with this. You should be using a BinaryReader to work with this data. If someone is pushing back on this point, I would walk away. Let them find someone else to indulge their folly.
Here's a VB.NET port of the BASIC sample code. I haven't tested this because I don't have access to a COMP-3 file. If this doesn't work, I would refer back to the original MS sample code for guidance, or to references in the other answers to this question.
```
Imports Microsoft.VisualBasic
Module Module1
'Sample COMP-3 conversion code
'Adapted from http://support.microsoft.com/kb/65323
'This code has not been tested
Sub Main()
Dim Digits%(15) 'Holds the digits for each number (max = 16).
Dim Basiceqv#(1000) 'Holds the Basic equivalent of each COMP-3 number.
'Added to make code compile
Dim MyByte As Char, HighPower%, HighNibble%
Dim LowNibble%, Digit%, E%, Decimal%, FileName$
'Clear the screen, get the filename and the amount of decimal places
'desired for each number, and open the file for sequential input:
FileName$ = InputBox("Enter the COBOL data file name: ")
Decimal% = InputBox("Enter the number of decimal places desired: ")
FileOpen(1, FileName$, OpenMode.Binary)
Do Until EOF(1) 'Loop until the end of the file is reached.
Input(1, MyByte)
If MyByte = Chr(0) Then 'Check if byte is 0 (ASC won't work on 0).
Digits%(HighPower%) = 0 'Make next two digits 0. Increment
Digits%(HighPower% + 1) = 0 'the high power to reflect the
HighPower% = HighPower% + 2 'number of digits in the number
'plus 1.
Else
HighNibble% = Asc(MyByte) \ 16 'Extract the high and low
LowNibble% = Asc(MyByte) And &HF 'nibbles from the byte. The
Digits%(HighPower%) = HighNibble% 'high nibble will always be a
'digit.
If LowNibble% <= 9 Then 'If low nibble is a
'digit, assign it and
Digits%(HighPower% + 1) = LowNibble% 'increment the high
HighPower% = HighPower% + 2 'power accordingly.
Else
HighPower% = HighPower% + 1 'Low nibble was not a digit but a
Digit% = 0 '+ or - signals end of number.
'Start at the highest power of 10 for the number and multiply
'each digit by the power of 10 place it occupies.
For Power% = (HighPower% - 1) To 0 Step -1
Basiceqv#(E%) = Basiceqv#(E%) + (Digits%(Digit%) * (10 ^ Power%))
Digit% = Digit% + 1
Next
'If the sign read was negative, make the number negative.
If LowNibble% = 13 Then
Basiceqv#(E%) = Basiceqv#(E%) - (2 * Basiceqv#(E%))
End If
'Give the number the desired amount of decimal places, print
'the number, increment E% to point to the next number to be
'converted, and reinitialize the highest power.
Basiceqv#(E%) = Basiceqv#(E%) / (10 ^ Decimal%)
Print(Basiceqv#(E%))
E% = E% + 1
HighPower% = 0
End If
End If
Loop
FileClose() 'Close the COBOL data file, and end.
End Sub
End Module
``` |
143,025 | <pre><code>struct a
{
char *c;
char b;
};
</code></pre>
<p>What is sizeof(a)? </p>
| [
{
"answer_id": 143026,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 0,
"selected": false,
"text": "<p>I assume you mean struct and not strict, but on a 32-bit system it'll be either 5 or 8 bytes, depending on if t... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
struct a
{
char *c;
char b;
};
```
What is sizeof(a)? | ```
#include <stdio.h>
typedef struct { char* c; char b; } a;
int main()
{
printf("sizeof(a) == %d", sizeof(a));
}
```
I get "sizeof(a) == 8", on a 32-bit machine. The total size of the structure will depend on the packing: In my case, the default packing is 4, so 'c' takes 4 bytes, 'b' takes one byte, leaving 3 padding bytes to bring it to the next multiple of 4: 8. If you want to alter this packing, most compilers have a way to alter it, for example, on MSVC:
```
#pragma pack(1)
typedef struct { char* c; char b; } a;
```
gives sizeof(a) == 5. If you do this, be careful to reset the packing before any library headers! |
143,058 | <p>ToolStripItems show Active highlighting when you mouse over them, even if the form they are in is not in focus. They do not, however, show their tooltips, unless the form is focused. I have seen the <a href="http://blogs.msdn.com/rickbrew/archive/2006/01/09/511003.aspx" rel="noreferrer">ToolStrip 'click-though' hack</a>. Anyone know how to make a ToolStripButton show its tooltip when its parent form is not in focus?</p>
<p>Thanks!</p>
| [
{
"answer_id": 145483,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps one of the two approaches in this code will kick you off in the right direction...</p>\n\n<pre><code>p... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22539/"
] | ToolStripItems show Active highlighting when you mouse over them, even if the form they are in is not in focus. They do not, however, show their tooltips, unless the form is focused. I have seen the [ToolStrip 'click-though' hack](http://blogs.msdn.com/rickbrew/archive/2006/01/09/511003.aspx). Anyone know how to make a ToolStripButton show its tooltip when its parent form is not in focus?
Thanks! | The problem is that the ToolStrip "controls" like ToolStripButton or ToolStripDropDownButton don't inherit from Control. For now I addressed the problem by focusing the ToolStrip whenever a user hovers over a button. The button's MouseHover event is fired too late -- after the "show tooltip" code would have been run, so I extended the ToolStripDropDownButton class and used my new button. This method should work for any of the other button-like classes inheriting from ToolStripItem
```
public class ToolStripDropDownEx : ToolStripDropDownButton
{
public ToolStripDropDownEx(string text)
{
}
protected override void OnMouseHover(EventArgs e)
{
if (this.Parent != null)
Parent.Focus();
base.OnMouseHover(e);
}
}
``` |
143,063 | <p>I've recently seen the light of EventWaitHandle's powerful behavior in C# and decided to move some functionality in a sister application to do the same. The only problem is that the sister app is written in C.</p>
<p>No big deal, I'm using pthreads, which have a pthread_cond_t datatype that allows for signalling. My only question is, is it possible for a cond to be 'signalled' before something is waiting on it?</p>
<p>Right now my testing says no. That is, if ThreadA fires a signal before ThreadB is waiting, ThreadB will wait indefinately. Is there another pthread type that I can use that behaves closer to the functionality of the EventWaitHandle in C#? An object is signalled, meaning that the first thread to wait on it, will pass immediately, and set it to unsignalled.</p>
<p>Wrapping the pthread_cond into another data structure wouldn't be too hard to achieve this. But again, is this functionality already available in the pthread library?</p>
| [
{
"answer_id": 143161,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "<p>If you're using condition variables correctly, this won't matter.</p>\n\n<p>The basic flow of your code should be (in pseu... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8945/"
] | I've recently seen the light of EventWaitHandle's powerful behavior in C# and decided to move some functionality in a sister application to do the same. The only problem is that the sister app is written in C.
No big deal, I'm using pthreads, which have a pthread\_cond\_t datatype that allows for signalling. My only question is, is it possible for a cond to be 'signalled' before something is waiting on it?
Right now my testing says no. That is, if ThreadA fires a signal before ThreadB is waiting, ThreadB will wait indefinately. Is there another pthread type that I can use that behaves closer to the functionality of the EventWaitHandle in C#? An object is signalled, meaning that the first thread to wait on it, will pass immediately, and set it to unsignalled.
Wrapping the pthread\_cond into another data structure wouldn't be too hard to achieve this. But again, is this functionality already available in the pthread library? | If you're using condition variables correctly, this won't matter.
The basic flow of your code should be (in pseudocode):
```
lock(lockobj);
while (!signalled) {
wait(condvar);
}
signalled = false;
unlock(lockobj);
```
on the waiting side, and:
```
lock(lockobj);
signalled = true;
notify(condvar);
unlock(lockobj);
```
on the signalling side. (Of course, the lock object and condition variable used have to be the same on both sides.) Hope this helps! |
143,075 | <p>I'm trying to print out the date in a certain format:</p>
<pre><code>NSDate *today = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateStr = [dateFormatter stringFromDate:today];
</code></pre>
<p>If the iPhone is set to 24 hour time, this works fine, if on the other hand the user has set it to 24 hour time, then back to AM/PM (it works fine until you toggle this setting) then it appends the AM/PM on the end even though I didn't ask for it:</p>
<pre><code>20080927030337 PM
</code></pre>
<p>Am I doing something wrong or is this a bug with firmware 2.1?</p>
<p>Edit 1: Made description clearer</p>
<p>Edit 2 workaround: It turns out this is a bug, to fix it I set the AM and PM characters to "":</p>
<pre><code>[dateFormatter setAMSymbol:@""];
[dateFormatter setPMSymbol:@""];
</code></pre>
| [
{
"answer_id": 143114,
"author": "Mike McMaster",
"author_id": 544,
"author_profile": "https://Stackoverflow.com/users/544",
"pm_score": 5,
"selected": true,
"text": "<p>Using the code you posted on both the simulator and a phone with the 2.1 firmware and 24-hour time set to off, I never... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] | I'm trying to print out the date in a certain format:
```
NSDate *today = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateStr = [dateFormatter stringFromDate:today];
```
If the iPhone is set to 24 hour time, this works fine, if on the other hand the user has set it to 24 hour time, then back to AM/PM (it works fine until you toggle this setting) then it appends the AM/PM on the end even though I didn't ask for it:
```
20080927030337 PM
```
Am I doing something wrong or is this a bug with firmware 2.1?
Edit 1: Made description clearer
Edit 2 workaround: It turns out this is a bug, to fix it I set the AM and PM characters to "":
```
[dateFormatter setAMSymbol:@""];
[dateFormatter setPMSymbol:@""];
``` | Using the code you posted on both the simulator and a phone with the 2.1 firmware and 24-hour time set to off, I never had an AM/PM appended to dateStr when I do:
```
NSLog(@"%@", dateStr);
```
Are you doing anything else with dateStr that you didn't post here? How are you checking the value?
**Follow up**
>
> Try turning the am/pm setting on then off. I didn't have the problem either, until I did that. I am printing it out the same way you are.
>
>
>
Okay, I see it when I do this also. It's gotta be a bug. I recommend you [file a bug report](https://bugreport.apple.com/) and just check for and filter out the unwanted characters in the meantime. |
143,084 | <p>Let's say I have one class <code>Foo</code> that has a bunch of logic in it and another class <code>Bar</code> which is essentially the same. However, as <code>Foo</code> and <code>Bar</code> are different (but related) entities I need the difference to be apparent from my code (i.e. I can tell whether an instance is a <code>Foo</code> or a <code>Bar</code>)</p>
<p>As I was whacking this together without much thought I ended up with the following:</p>
<pre><code>public class Foo {
/* constructors, fields, method, logic and what-not */
}
public class Bar extends Foo {
/* nothing here but constructors */
}
</code></pre>
<p>Is this OK? Is it better to make <code>Bar</code> a composite class? e.g:</p>
<pre><code>public class Bar {
private Foo foo;
/* constructors and a bunch of wrapper methods that call
into foo */
}
</code></pre>
<p>Or even, while we're at it, something much more low-tech:</p>
<pre><code>public class Foo {
/* constructors, fields, method, logic and what-not */
private boolean isABar; // Could be an enum
}
</code></pre>
<p>What do you think? <strong>How do you deal with these 'marker classes'?</strong></p>
<hr>
<p>As an example of how my code may wish to treat <code>Foo</code> and <code>Bar</code> differently, my code would need to be able to do stuff like <code>List<Foo></code> and <code>List<Bar></code>. A <code>Foo</code> couldn't go in a <code>List<Bar></code> and vice versa.</p>
| [
{
"answer_id": 143091,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "<p>In my opinion, it's best if <code>Foo</code> and <code>Bar</code> subclass off a common ancestor class (maybe <code>Abstra... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | Let's say I have one class `Foo` that has a bunch of logic in it and another class `Bar` which is essentially the same. However, as `Foo` and `Bar` are different (but related) entities I need the difference to be apparent from my code (i.e. I can tell whether an instance is a `Foo` or a `Bar`)
As I was whacking this together without much thought I ended up with the following:
```
public class Foo {
/* constructors, fields, method, logic and what-not */
}
public class Bar extends Foo {
/* nothing here but constructors */
}
```
Is this OK? Is it better to make `Bar` a composite class? e.g:
```
public class Bar {
private Foo foo;
/* constructors and a bunch of wrapper methods that call
into foo */
}
```
Or even, while we're at it, something much more low-tech:
```
public class Foo {
/* constructors, fields, method, logic and what-not */
private boolean isABar; // Could be an enum
}
```
What do you think? **How do you deal with these 'marker classes'?**
---
As an example of how my code may wish to treat `Foo` and `Bar` differently, my code would need to be able to do stuff like `List<Foo>` and `List<Bar>`. A `Foo` couldn't go in a `List<Bar>` and vice versa. | In my opinion, it's best if `Foo` and `Bar` subclass off a common ancestor class (maybe `AbstractFoo`), which has all the functionality. What difference in behaviour should exist between `Foo` and `Bar`? Code that difference as an abstract method in `AbstractFoo`, not by using a `if` statement in your code.
Example: Rather than this:
```
if (foo instanceof Bar) {
// Do Bar-specific things
}
```
Do this instead:
```
class Bar extends AbstractFoo {
public void specialOp() {
// Do Bar-specific things
}
}
// ...
foo.specialOp();
```
The benefit of this approach is that if you need a third class, that's much like `Foo` but has just a little bit of difference, you don't have to go through all your code and add edit all the `if` statements. :-) |
143,122 | <p>Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?</p>
<p>I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.</p>
<p>I've done it using the <a href="http://us3.php.net/manual/en/book.domxml.php" rel="noreferrer">DOMDocument functions</a>, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)</p>
| [
{
"answer_id": 143192,
"author": "DreamWerx",
"author_id": 15487,
"author_profile": "https://Stackoverflow.com/users/15487",
"pm_score": 8,
"selected": true,
"text": "<p>Sure you can. Eg.</p>\n\n<pre><code><?php\n$newsXML = new SimpleXMLElement(\"<news></news>\");\n$newsX... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20903/"
] | Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?
I figured out that you can use simplexml\_load\_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.
I've done it using the [DOMDocument functions](http://us3.php.net/manual/en/book.domxml.php), although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-) | Sure you can. Eg.
```
<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
```
Output
```
<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>
```
Have fun. |
143,123 | <p>Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method. What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character?</p>
| [
{
"answer_id": 143127,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 5,
"selected": true,
"text": "<p>BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3484/"
] | Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method. What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character? | BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is an example:
```
#define MY_BUFFER_SIZE 1024
char mybuffer[MY_BUFFER_SIZE];
int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);
``` |
143,171 | <p>I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names. When I try to string together <code>find</code> and <code>grep</code> with <code>xargs</code>, I get the following error:</p>
<pre><code>find .|grep "FooBar"|xargs -I{} cp "{}" ~/foo/bar
xargs: unterminated quote
</code></pre>
<p>Any suggestions for a more robust usage of xargs?</p>
<p>This is on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="noreferrer">Mac OS X 10.5.3</a> (Leopard) with BSD <code>xargs</code>.</p>
| [
{
"answer_id": 143172,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 7,
"selected": false,
"text": "<p><code>find . -print0 | grep --null 'FooBar' | xargs -0 ...</code></p>\n\n<p>I don't know about whether <code>grep</code> ... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17339/"
] | I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names. When I try to string together `find` and `grep` with `xargs`, I get the following error:
```
find .|grep "FooBar"|xargs -I{} cp "{}" ~/foo/bar
xargs: unterminated quote
```
Any suggestions for a more robust usage of xargs?
This is on [Mac OS X 10.5.3](http://en.wikipedia.org/wiki/Mac_OS_X_Leopard) (Leopard) with BSD `xargs`. | You can combine all of that into a single `find` command:
```
find . -iname "*foobar*" -exec cp -- "{}" ~/foo/bar \;
```
This will handle filenames and directories with spaces in them. You can use `-name` to get case-sensitive results.
Note: The `--` flag passed to `cp` prevents it from processing files starting with `-` as options. |
143,174 | <p>Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)</p>
<p>(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)</p>
| [
{
"answer_id": 143177,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 3,
"selected": false,
"text": "<p>For Win32 <a href=\"http://msdn.microsoft.com/en-us/library/aa364934(VS.85).aspx\" rel=\"noreferrer\">GetCu... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)
(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.) | Here's code to get the full path to the executing app:
Variable declarations:
```
char pBuf[256];
size_t len = sizeof(pBuf);
```
Windows:
```
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
```
Linux:
```
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;
``` |
143,181 | <p>If you have a project, that releases a library and an application, how you handle version-numbers between the two.</p>
<p>Example: Your project delivers a library, that convert different file-formats into each other. The library is released for inclusion into other applications. But you also release a command-line-application, that uses this library and implements an interface to the functionality.</p>
<p>New releases of the library lead to new releases of the application (to make use of all new features), but new releases of the application may not trigger new releases of the library. Now how are the versions numbers handled: Completely independent or should library- and application-version be dependent in some way?</p>
| [
{
"answer_id": 143185,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Completely independent version numbers, but the command line (or any other dependent) app should say which versio... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] | If you have a project, that releases a library and an application, how you handle version-numbers between the two.
Example: Your project delivers a library, that convert different file-formats into each other. The library is released for inclusion into other applications. But you also release a command-line-application, that uses this library and implements an interface to the functionality.
New releases of the library lead to new releases of the application (to make use of all new features), but new releases of the application may not trigger new releases of the library. Now how are the versions numbers handled: Completely independent or should library- and application-version be dependent in some way? | I'd say use separate version numbers, and of course document what minimum library version is required for each release of the app. If they always have the same version number, and you only ever test the app against the equal-numbered library version, then they aren't really separate components, so don't say they are. Release the whole lot as one lump.
If you make them separate, you can still give them the same version number when it's appropriate - for example after a major compatibility break you might release Version 2.0 of both simultaneously.
The following example illustrates: xsltproc (a command-line app) is released as part of libxslt (a library), so doesn't have its own version number. But libxslt depends on two other libraries, and the version numbers of those are independent.
```
$ xsltproc --version
Using libxml 20628, libxslt 10120 and libexslt 813
xsltproc was compiled against libxml 20628, libxslt 10120 and libexslt 813
libxslt 10120 was compiled against libxml 20628
libexslt 813 was compiled against libxml 20628
``` |
143,194 | <p>I have a pretty complicated Linq query that I can't seem to get into a LinqDataSsource for use in a GridView:</p>
<pre><code>IEnumerable<ticket> tikPart = (
from p in db.comments where
p.submitter == me.id &&
p.ticket.closed == DateTime.Parse("1/1/2001") &&
p.ticket.originating_group != me.sub_unit
select p.ticket
).Distinct();
</code></pre>
<p>How can I get this into a GridView? Thank you!</p>
| [
{
"answer_id": 143195,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "<pre><code>gridview.DataSource = tikPart.ToList();\ngridview.DataBind();\n</code></pre>\n"
},
{
"answer_id": 143196... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14777/"
] | I have a pretty complicated Linq query that I can't seem to get into a LinqDataSsource for use in a GridView:
```
IEnumerable<ticket> tikPart = (
from p in db.comments where
p.submitter == me.id &&
p.ticket.closed == DateTime.Parse("1/1/2001") &&
p.ticket.originating_group != me.sub_unit
select p.ticket
).Distinct();
```
How can I get this into a GridView? Thank you! | You can setup your Gridview with no Datasource. Setup the gridview columns, and in codebehind bind that result to the grid view. |
143,206 | <p>I want to obtain the current number of window handles and the system-wide window handle limit in C#. How do I go about this?</p>
| [
{
"answer_id": 143220,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 2,
"selected": false,
"text": "<p>As Raymond Chen put it some time ago, if you're thinking about window handle limits, you're probably doing somethin... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I want to obtain the current number of window handles and the system-wide window handle limit in C#. How do I go about this? | If you read Raymond Chen's post, you'll probably find it as annoying as I did. You're only "probably doing something wrong" because you're doing something Windows isn't capable of.
In my application, the first time a user visits a tab page, I create and lay out all the controls on that page. This takes a noticeable amount of time - there can easily be 50 controls on a page. So I don't discard the controls on a tab page after populating it, if it's at all possible, and leave closing sets of tab pages up to the user.
As it happens, some users never want to close *any* sets of tab pages. Why should I be forcing them to? With my UI, they can navigate very quickly to any one of the 300+ sets of transactions that they're responsible for managing. Their machines are fast enough, and have enough memory, to make this all very responsive. The only problem is that Windows can't support it.
Why am I using controls, and not some other UI technology? Because they *work*. I need to support focus events, tab order, validation events, dynamic layout, and data binding - the users are actually managing thousands of records, in dozens of tables, in an in-memory DataSet. The amount of development I'd have to do to - say - implement something using windowless controls is astronomical.
I'm only "doing it wrong" because Windows has a hard limit on the number of window handles that it can support. That hard limit is based on a bunch of decade-old assumptions about how a computer's UI might be built. It's not me who's "doing something wrong."
At any rate, my solution to this is in two parts.
First, a class that can tell you how many window handles your process is using:
```
using System;
using System.Runtime.InteropServices;
namespace StreamWrite.Proceedings.Client
{
public class HWndCounter
{
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("user32.dll")]
private static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags);
private enum ResourceType
{
Gdi = 0,
User = 1
}
public static int GetWindowHandlesForCurrentProcess(IntPtr hWnd)
{
IntPtr processHandle = GetCurrentProcess();
uint gdiObjects = GetGuiResources(processHandle, (uint)ResourceType.Gdi);
uint userObjects = GetGuiResources(processHandle, (uint)ResourceType.User);
return Convert.ToInt32(gdiObjects + userObjects);
}
}
}
```
Second, I maintain a least-recently-used cache of my tab page objects. The .NET framework doesn't provide a generic LRU cache class, so I built one, which you can get [here](http://csharp-lru-cache.googlecode.com) if you need one. Every time the user visits a tab page, I add it to the LRU Cache. Then I check to see if I'm running low on window handles. If I am, I throw away the controls on the least-recently-used tab page, and keep doing that until I have enough window handles again. |
143,215 | <p>I've been trying to display text using a Quartz context, but no matter what I've tried I simply haven't had luck getting the text to display (I'm able to display all sorts of other Quartz objects though). Anybody knows what I might be doing wrong?</p>
<p>example:</p>
<pre><code>-(void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSelectFont(context, "Arial", 24, kCGEncodingFontSpecific);
CGContextSetTextPosition(context,80,80);
CGContextShowText(context, "hello", 6);
//not even this works
CGContextShowTextAtPoint(context, 1,1, "hello", 6);
}
</code></pre>
| [
{
"answer_id": 143352,
"author": "Darron",
"author_id": 22704,
"author_profile": "https://Stackoverflow.com/users/22704",
"pm_score": 4,
"selected": true,
"text": "<p>Here is a fragment of code that I'm using.</p>\n\n<pre><code>UIColor *mainTextColor = [UIColor whiteColor];\n[mainTextCol... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | I've been trying to display text using a Quartz context, but no matter what I've tried I simply haven't had luck getting the text to display (I'm able to display all sorts of other Quartz objects though). Anybody knows what I might be doing wrong?
example:
```
-(void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSelectFont(context, "Arial", 24, kCGEncodingFontSpecific);
CGContextSetTextPosition(context,80,80);
CGContextShowText(context, "hello", 6);
//not even this works
CGContextShowTextAtPoint(context, 1,1, "hello", 6);
}
``` | Here is a fragment of code that I'm using.
```
UIColor *mainTextColor = [UIColor whiteColor];
[mainTextColor set];
drawTextLjust(@"Sample Text", 8, 50, 185, 18, 16);
```
And:
```
static void drawTextLjust(NSString* text, CGFloat y, CGFloat left, CGFloat right,
int maxFontSize, int minFontSize) {
CGPoint point = CGPointMake(left, y);
UIFont *font = [UIFont systemFontOfSize:maxFontSize];
[text drawAtPoint:point forWidth:right - left withFont:font
minFontSize:minFontSize actualFontSize:NULL
lineBreakMode:UILineBreakModeTailTruncation
baselineAdjustment:UIBaselineAdjustmentAlignBaselines];
}
``` |
143,226 | <p>let's assume i have a self referencing hierarchical table build the classical way like this one:</p>
<pre><code>CREATE TABLE test
(name text,id serial primary key,parent_id integer
references test);
insert into test (name,id,parent_id) values
('root1',1,NULL),('root2',2,NULL),('root1sub1',3,1),('root1sub2',4,1),('root
2sub1',5,2),('root2sub2',6,2);
testdb=# select * from test;
name | id | parent_id
-----------+----+-----------
root1 | 1 |
root2 | 2 |
root1sub1 | 3 | 1
root1sub2 | 4 | 1
root2sub1 | 5 | 2
root2sub2 | 6 | 2
</code></pre>
<p>What i need now is a function (preferrably in plain sql) that would take the id of a test record and
clone all attached records (including the given one). The cloned records need to have new ids of course. The desired result
would like this for example:</p>
<pre><code>Select * from cloningfunction(2);
name | id | parent_id
-----------+----+-----------
root2 | 7 |
root2sub1 | 8 | 7
root2sub2 | 9 | 7
</code></pre>
<p>Any pointers? Im using PostgreSQL 8.3.</p>
| [
{
"answer_id": 143313,
"author": "njr101",
"author_id": 9625,
"author_profile": "https://Stackoverflow.com/users/9625",
"pm_score": 3,
"selected": false,
"text": "<p>Pulling this result in recursively is tricky (although possible). However, it's typically not very efficient and there is ... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | let's assume i have a self referencing hierarchical table build the classical way like this one:
```
CREATE TABLE test
(name text,id serial primary key,parent_id integer
references test);
insert into test (name,id,parent_id) values
('root1',1,NULL),('root2',2,NULL),('root1sub1',3,1),('root1sub2',4,1),('root
2sub1',5,2),('root2sub2',6,2);
testdb=# select * from test;
name | id | parent_id
-----------+----+-----------
root1 | 1 |
root2 | 2 |
root1sub1 | 3 | 1
root1sub2 | 4 | 1
root2sub1 | 5 | 2
root2sub2 | 6 | 2
```
What i need now is a function (preferrably in plain sql) that would take the id of a test record and
clone all attached records (including the given one). The cloned records need to have new ids of course. The desired result
would like this for example:
```
Select * from cloningfunction(2);
name | id | parent_id
-----------+----+-----------
root2 | 7 |
root2sub1 | 8 | 7
root2sub2 | 9 | 7
```
Any pointers? Im using PostgreSQL 8.3. | Pulling this result in recursively is tricky (although possible). However, it's typically not very efficient and there is a *much* better way to solve this problem.
Basically, you augment the table with an extra column which traces the tree to the top - I'll call it the "Upchain". It's just a long string that looks something like this:
```
name | id | parent_id | upchain
root1 | 1 | NULL | 1:
root2 | 2 | NULL | 2:
root1sub1 | 3 | 1 | 1:3:
root1sub2 | 4 | 1 | 1:4:
root2sub1 | 5 | 2 | 2:5:
root2sub2 | 6 | 2 | 2:6:
root1sub1sub1 | 7 | 3 | 1:3:7:
```
It's very easy to keep this field updated by using a trigger on the table. (Apologies for terminology but I have always done this with SQL Server). Every time you add or delete a record, or update the parent\_id field, you just need to update the upchain field on that part of the tree. That's a trivial job because you just take the upchain of the parent record and append the id of the current record. All child records are easily identified using LIKE to check for records with the starting string in their upchain.
What you're doing effectively is trading a bit of extra write activity for a *big* saving when you come to read the data.
When you want to select a complete branch in the tree it's trivial. Suppose you want the branch under node 1. Node 1 has an upchain '1:' so you know that any node in the branch of the tree under that node must have an upchain starting '1:...'. So you just do this:
```
SELECT *
FROM table
WHERE upchain LIKE '1:%'
```
This is *extremely* fast (index the upchain field of course). As a bonus it also makes a lot of activities extremely simple, such as finding partial trees, level within the tree, etc.
I've used this in applications that track large employee reporting hierarchies but you can use it for pretty much any tree structure (parts breakdown, etc.)
Notes (for anyone who's interested):
* I haven't given a step-by-step of the SQL code but once you get the principle, it's pretty simple to implement. I'm not a great programmer so I'm speaking from experience.
* If you already have data in the table you need to do a one time update to get the upchains synchronised initially. Again, this isn't difficult as the code is very similar to the UPDATE code in the triggers.
* This technique is also a good way to identify circular references which can otherwise be tricky to spot. |
143,234 | <p>In Lua, using the = operator without an l-value seems to be equivalent to a print(r-value), here are a few examples run in the Lua standalone interpreter:</p>
<pre><code>> = a
nil
> a = 8
> = a
8
> = 'hello'
hello
> = print
function: 003657C8
</code></pre>
<p>And so on...</p>
<p>My question is : where can I find a detailed description of this use for the = operator? How does it work? Is it by implying a special default l-value? I guess the root of my problem is that I have no clue what to type in Google to find info about it :-)</p>
<p><strong>edit</strong>:</p>
<p>Thanks for the answers, you are right it's a feature of the interpreter. Silly question, for I don't know which reason I completely overlooked the obvious. I should avoid posting before the morning coffee :-) For completeness, here is the code dealing with this in the interpreter:</p>
<pre><code>while ((status = loadline(L)) != -1) {
if (status == 0) status = docall(L, 0, 0);
report(L, status);
if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
lua_getglobal(L, "print");
lua_insert(L, 1);
if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
l_message(progname, lua_pushfstring(L,
"error calling " LUA_QL("print") " (%s)",
lua_tostring(L, -1)));
}
}
</code></pre>
<p><strong>edit2</strong>:</p>
<p>To be really complete, the whole trick about pushing values on the stack is in the "pushline" function:</p>
<pre><code>if (firstline && b[0] == '=') /* first line starts with `=' ? */
lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
</code></pre>
| [
{
"answer_id": 143252,
"author": "Arle Nadja",
"author_id": 17774,
"author_profile": "https://Stackoverflow.com/users/17774",
"pm_score": 2,
"selected": false,
"text": "<p>I think that must be a feature of the stand alone interpreter. I can't make that work on anything I have compiled lu... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12291/"
] | In Lua, using the = operator without an l-value seems to be equivalent to a print(r-value), here are a few examples run in the Lua standalone interpreter:
```
> = a
nil
> a = 8
> = a
8
> = 'hello'
hello
> = print
function: 003657C8
```
And so on...
My question is : where can I find a detailed description of this use for the = operator? How does it work? Is it by implying a special default l-value? I guess the root of my problem is that I have no clue what to type in Google to find info about it :-)
**edit**:
Thanks for the answers, you are right it's a feature of the interpreter. Silly question, for I don't know which reason I completely overlooked the obvious. I should avoid posting before the morning coffee :-) For completeness, here is the code dealing with this in the interpreter:
```
while ((status = loadline(L)) != -1) {
if (status == 0) status = docall(L, 0, 0);
report(L, status);
if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
lua_getglobal(L, "print");
lua_insert(L, 1);
if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
l_message(progname, lua_pushfstring(L,
"error calling " LUA_QL("print") " (%s)",
lua_tostring(L, -1)));
}
}
```
**edit2**:
To be really complete, the whole trick about pushing values on the stack is in the "pushline" function:
```
if (firstline && b[0] == '=') /* first line starts with `=' ? */
lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
``` | Quoting the [man page](http://www.lua.org/manual/5.1/lua.html):
>
> In interactive mode ... If a line starts with '=', then lua displays the values of all the expressions in the remainder of the line. The expressions must be separated by commas.
>
>
> |
143,285 | <p>For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++</p>
| [
{
"answer_id": 143291,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 0,
"selected": false,
"text": "<p>No, an enum is generally the same size as an int, same as boolean.</p>\n"
},
{
"answer_id": 143298,
... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++ | In Java, an [`enum` is a full-blown class](http://download.oracle.com/javase/tutorial/java/javaOO/enum.html):
>
> Java programming language enum types
> are much more powerful than their
> counterparts in other languages. The
> enum declaration defines a class
> (called an enum type). The enum class
> body can include methods and other
> fields.
>
>
>
In order to see the actual size of each `enum`, let's make an actual `enum` and examine the contents of the `class` file it creates.
Let's say we have the following `Constants` enum class:
```
public enum Constants {
ONE,
TWO,
THREE;
}
```
Compiling the above `enum` and disassembling resulting `class` file with `javap` gives the following:
```
Compiled from "Constants.java"
public final class Constants extends java.lang.Enum{
public static final Constants ONE;
public static final Constants TWO;
public static final Constants THREE;
public static Constants[] values();
public static Constants valueOf(java.lang.String);
static {};
}
```
The disassembly shows that that each field of an `enum` is an instance of the `Constants` `enum` class. (Further analysis with `javap` will reveal that each field is initialized by creating a new object by calling the `new Constants(String)` constructor in the static initialization block.)
Therefore, we can tell that each `enum` field that we create will be at least as much as the overhead of creating an object in the JVM. |
143,296 | <p>I've got such a simple code:</p>
<pre><code><div class="div1">
<div class="div2">Foo</div>
<div class="div3">
<div class="div4">
<div class="div5">
Bar
</div>
</div>
</div>
</div>
</code></pre>
<p>and this CSS:</p>
<pre class="lang-css prettyprint-override"><code>.div1{
position: relative;
}
.div1 .div3 {
position: absolute;
top: 30px;
left: 0px;
width: 250px;
display: none;
}
.div1:hover .div3 {
display: block;
}
.div2{
width: 200px;
height: 30px;
background: red;
}
.div4 {
background-color: green;
color: #000;
}
.div5 {}
</code></pre>
<p>The problem is: When I move the cursor from <code>.div2</code> to <code>.div3</code> (<code>.div3</code> should stay visible because it's the child of <code>.div1</code>) then the hover is disabled. I'm testing it in IE7, in FF it works fine. What am I doing wrong? I've also realized that when i remove <code>.div5</code> tag than it's working. Any ideas?</p>
| [
{
"answer_id": 143309,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>I found that this solution worked better and was a bit cleaner:</p>\n\n<pre><code> <style type=\"text/css\">\n ... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20403/"
] | I've got such a simple code:
```
<div class="div1">
<div class="div2">Foo</div>
<div class="div3">
<div class="div4">
<div class="div5">
Bar
</div>
</div>
</div>
</div>
```
and this CSS:
```css
.div1{
position: relative;
}
.div1 .div3 {
position: absolute;
top: 30px;
left: 0px;
width: 250px;
display: none;
}
.div1:hover .div3 {
display: block;
}
.div2{
width: 200px;
height: 30px;
background: red;
}
.div4 {
background-color: green;
color: #000;
}
.div5 {}
```
The problem is: When I move the cursor from `.div2` to `.div3` (`.div3` should stay visible because it's the child of `.div1`) then the hover is disabled. I'm testing it in IE7, in FF it works fine. What am I doing wrong? I've also realized that when i remove `.div5` tag than it's working. Any ideas? | IE7 won't allow you to apply `:hover` pseudo-classes to non-anchor elements unless you explicitly specify a doctype. Just add a doctype declaration to your page and it should work perfectly.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
```
More on IE7/quirks mode can be found on [this blog post](http://www.bernzilla.com/item.php?id=762). |
143,365 | <p>I have a flash application running Flash 9 (CS3). Application is able to control the Softkeys when this flash application is loaded in the supported mobile device. But, the application doesn't have control when the same is embedded in HTML page and browsed via supported mobile device. Any ideas how to make this work?</p>
<p>Thanks
Keerthi</p>
| [
{
"answer_id": 144130,
"author": "fenomas",
"author_id": 10651,
"author_profile": "https://Stackoverflow.com/users/10651",
"pm_score": 1,
"selected": false,
"text": "<p>There is no special way to receive soft key events when embedded in HTML - if the browser/OS gives the events to Flash,... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a flash application running Flash 9 (CS3). Application is able to control the Softkeys when this flash application is loaded in the supported mobile device. But, the application doesn't have control when the same is embedded in HTML page and browsed via supported mobile device. Any ideas how to make this work?
Thanks
Keerthi | There is no special way to receive soft key events when embedded in HTML - if the browser/OS gives the events to Flash, then you can catch them like any other key event:
```
var myListener = new Object();
myListener.onKeyDown = function() {
var code = Key.getCode();
if (code==ExtendedKey.SOFT1) {
trace("I got a soft key event");
}
}
Key.addListener(myListener);
```
However, you'll find that most phones/browsers will not give you soft key events when your SWF is embedded in HTML. This isn't part of the Flash Lite spec - strictly speaking I believe they could give you those events if they wanted to, but most phones simply use those keys for browser functions, and consume them before they get to Flash.
Note that you can check at runtime whether or not softkeys are available:
```
trace(System.capabilities.hasMappableSoftKeys);
trace(System.capabilities.softKeyCount);
``` |
143,374 | <p>A long time ago I had an apple ][ . </p>
<p>I remember the command call – 151
But I can not remember what it did ? </p>
| [
{
"answer_id": 143383,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 6,
"selected": true,
"text": "<p>CALL -151</p>\n\n<p>Enter the machine code monitor -</p>\n\n<p><a href=\"http://www.skepticfiles.org/cowtext/apple/memorytx.htm\... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560/"
] | A long time ago I had an apple ][ .
I remember the command call – 151
But I can not remember what it did ? | CALL -151
Enter the machine code monitor -
<http://www.skepticfiles.org/cowtext/apple/memorytx.htm>
**Update:**
That link appears to be dead, here's a Wayback Machine alternative:
>
> <http://web.archive.org/web/20090315100335/http://www.skepticfiles.org/cowtext/apple/memorytx.htm>
>
>
>
Here's the full article just in case Wayback goes away:
```
APPLE CALL, PEEK, POKE LIST CALL 144 SCAN THE INPUT BUFFER CALL 151 ENTER THE MONITOR NORM
APPLE CALL, PEEK, POKE LIST
------------------------------------------------------------------------------
CALL -144 SCAN THE INPUT BUFFER
CALL -151 ENTER THE MONITOR NORMALLY
CALL -155 ENTER THE MONITOR & SOUND BELL
CALL -167 ENTER MONITOR AND RESET
CALL -198 RING BELL (SIMULATE CONTROL G)
CALL -211 PRINT "ERR" AND RING BELL
CALL -259 READ FROM TAPE
CALL -310 WRITE TO TAPE
CALL -321 DISPLAYS A, S, Y, P, & S REGISTERS
CALL -380 SET NORMAL VIDEO MODE
CALL -384 SET INVERSE VIDEO MODE
CALL -415 DISASSEMBLE 20 INSTRUCTIONS
CALL -458 VERIFY (COMPARE & LIST DIFFERENCES)
CALL -468 MEMORY MOVE AFTER POKING 60,61 OLD START - 62,63 OLD END
64,65 NEW END - 66,67 NEW STAR
CALL -484 MOVE
CALL -517 DISPLAY CHARACTER & UPDATE SCREEN LOCATION
CALL -531 DISPLAY CHARACTER, MASK CONTROL CHAR., & SAVE 7 REG. & ACCU
CALL -550 DISPLAY HEX VALUE OF A-REGISTER (ACCUMULATOR)
CALL -656 RING BELL AND WAIT FOR A CARRIAGE RETURN
CALL -657 GET LINE OF INPUT, NO PROMPT, NO L/F, & WAIT(COMMA,COLON OK
CALL -662 GET LINE OF INPUT, WITH PROMPT, NO L/F, & WAIT
CALL -665 GET LINE OF INPUT, WITH PROMPT, LINE FEED, & WAIT
THE ABOVE 3 CALLS (-657, -662, -665) REFER TO THE INPUT BUFFER FROM 512-767
CALL -715 GET CHARACTER
CALL -756 WAIT FOR KEY PRESS
CALL -856 TIME DELAY (POKE 69,XX TO SET TIME OF DELAY)
CALL -868 CLEARS CURSOR LINE FROM CURSOR TO END OF LINE
CALL -912 SCROLLS TEXT UP 1 LINE
CALL -922 LINE FEED
CALL -936 CLEAR SCREEN (HOME)
CALL -958 CLEAR SCREEN FROM CURSOR TO BOTTOM OF SCREEN
CALL -998 MOVES CURSOR UP 1 LINE
CALL -1008 MOVES CURSOR BACKWARD 1 SPACE
CALL -1024 DISPLAY CHARACTER ONLY
CALL -1036 MOVES CURSOR FORWARD 1 SPACE
CALL -1063 SEND BELL TO CURRENT OUTPUT DEVICE
CALL -1216 TEXT & GRAPHICS MODE
CALL -1233 MOVE CURSOR TO BOTTOM OF SCREEN
CALL -1321 CONTROL E
CALL -1717 MOVES CURSOR DOWN 5 LINES
CALL -1840 DISASSEMBLE 1 INSTRUCTION
CALL -1953 CHANGE COLOR BY +3
CALL -1994 CLEAR LO-RES SCREEN (TOP 40 LINES)
CALL -1998 CLEAR GRAPHIC SCREEN (LO-RES)
CALL -2007 VERTICAL LINE
CALL -2023 HORIZONTAL LINE
CALL -2458 ENTER MINI ASSEMBLER
CALL -3100 TURNS ON HIRES PAGE 1, WITHOUT CLEARING IT
CALL -3776 SAVE INTEGER
CALL -3973 LOAD INTEGER
CALL -6090 RUN INTEGER
CALL -8117 LIST INTEGER
CALL -8189 ENTER BASIC & CONTINUE
CALL -8192 ENTER BASIC AND RESET (INTEGER BASIC KILL)
CALL -16303 TEXT MODE
CALL -16304 GRAPHICS MODE
CALL -16336 TOGGLE SPEAKER
CALL 42350 CATALOGS DISK
CALL 54915 CLEANS STACK, CLEARS THE "OUT OF MEMORY" ERROR
CALL 64166 INITIATES A COLD START (BOOT OF THE DISK)
CALL 64246 BRAND NEW-YOU FIGURE IT OUT
CALL 64367 SCANS MEMORY LOC 1010 & 1011 & POKES VALUE INTO LOCATIONS
1012 THAT IS EQUAL TO (PEEK(1011)-165)
------------------------------------------------------------------------------
PEEK 33 WIDTH OF TEXT WINDOW (1-40)
PEEK 34 TOP EDGE OF TEXT WINDOW (0-22)
PEEK 35 BOTTOM OF TEXT WINDOW (1-24)
PEEK 36 HORIZONTAL CURSOR POSITION (0-39)
PEEK 37 VERTICAL CURSOR POSITION (0-23)
PEEK 43 BOOT SLOT X 16 (AFTER BOOT)
PEEK 44 END POINT OF LAST HLIN, VLIN, OR PLOT
PEEK 48 LO-RES COLOR VALUE X 17
PEEK 50 TEXT OUTPUT FORMAT: 63=INVERSE 255=NORMAL
127=FLASH ( WITH PEEK 243 SET TO 64)
PEEK 51 PROMPT CHARACTER
PEEK 74,75 LOMEM ADDRESS (INT)
PEEK 76,77 HIMEM ADDRESS (INT)
PEEK 103,104 FP PROGRAM STARTING ADDRESS
PEEK 104 IF 8 IS RETURNED, THEN FP IS IN ROM
PEEK 105,106 FP VARIABLE SPACE STARTING ADDRESS
PEEK 107,108 FP ARRAY STARTING ADDRESS
PEEK 109,110 FP END OF NUMERIC STORAGE ADDRESS
PEEK 111,112 FP STRING STORAGE STARTING ADDRESS
PEEK 115,116 FP HIMEM ADDRESS
PEEK 117,118 FP LINE NUMBER BEING EXECUTED
PEEK 119,120 FP LINE WHERE PROGRAM STOPPED
PEEK 121,122 FP LINE BEING EXECUTED ADDRESS
PEEK 123,124 LINE WHERE DATA BEING READ
PEEK 125,126 DATA LOCATION ADDRESS
PEEK 127,128 INPUT OR DATA ADDRESS
PEEK 129,130 FP LAST USED VARIABLE NAME
PEEK 131,132 FP LAST USED VARIABLE ADDRESS
PEEK 175,176 FP END OF PROGRAM ADDRESS
PEEK 202,203 INT PROGRAM STARTING ADDRESS
PEEK 204,205 INT END OF VARIABLE STORAGE
PEEK 214 FP RUN FLAG (AUTO-RUN IF >127)
PEEK 216 ONERR FLAG (>127 IF ONERR IS ACTIVE)
PEEK 218,219 LINE WHERE ONERR OCCURED
PEEK 222 ONERR ERROR CODE
PEEK 224,225 X-COORDINATE OF LAST HPLOT
PEEK 226 Y-COORDINATE OF LAST HPLOT
PEEK 228 HCOLOR VALUE 0=0 85=2 128=4 213=6
42=1 127=3 170=5 255=7
PEEK 230 HI-RES PLOTING PAGE (32=PAGE 1 64=PAGE 2 96=PAGE 3)
PEEK 231 SCALE VALUE
PEEK 232,233 SHAPE TABLE STARTING ADDRESS
PEEK 234 HI-RES COLLISION COUNTER
PEEK 241 256 MINUS SPEED VALUE
PEEK 243 FLASH MASK (64=FLASH WHEN PEEK 50 SET TO 127)
PEEK 249 ROT VLAUE
PEEK 976-978 DOS RE-ENTRY VECTOR
PEEK 1010-1012 RESET VECTOR
PEEK 1013-1015 AMPERSAND (&) VECTOR
PEEK 1016-1018 CONTROL-Y VECTOR
PEEK 43140-43271 DOS COMMAND TABLE
PEEK 43378-43582 DOS ERROR MESSAGE TABLE
PEEK 43607 MAXFILES VALUE
PEEK 43616,46617 LENGTH OF LAST BLOAD
PEEK 43624 DRIVE NUMBER
PEEK 43626 SLOT NUMBER
PEEK 43634,43635 STARTING ADDRESS OF LAST BLOAD
PEEK 43697 MAXFILES DEFAULT VALUE
PEEK 43698 DOS COMMAND CHARACTER
PEEK 43702 BASIC FLAG (0=INT 64=FP ROM 128=FP RAM)
PEEK 44033 CATALOG TRACK NUMBER (17 IS STANDARD)
PEEK 44567 NUMBER OF CHARACTERS MINUS 1 IN CATALOG FILE NAMES
PEEK 44611 NUMBER OF DIGITS MINUS 1 IN SECTOR AND VOLUME NUMBERS
PEEK 45991-45998 FILE-TYPE CODE TABLE
PEEK 45999-46010 DISK VOLUME HEADING
PEEK 46017 DISK VOLUME NUMBER
PEEK 46064 NUMBER OF SECTORS (13=DOS 3.2 16=DOS 3.3)
PEEK 49152 READ KEYBOARD (IF >127 THEN KEY HAS BEEN PRESSED
PEEK 49200 TOGGLE SPEAKER (CLICK)
PEEK 49248 CASSETTE INPUT (>127=BINARY 1, 127 IF BUTTON PRESSED)
PEEK 49250 PADDLE 1 BUTTON (>127 IF BUTTON PRESSGD)
PEEK 49251 PADDLE 2 BUTTON (>127 IF BUTTON PRESSED)
PEEK 49252 READ GAME PADDLE 0 (0-255)
PEEK 49253 READ GAME PADDLE 1 (0-255)
PEEK 49254 READ GAME PADDLE 2 (0-255)
PEEK 49255 READ GAME PADDLE 3 (0-255)
PEEK 49408 READ SLOT 1
PEEK 49664 READ SLOT 2
PEEK 49920 READ SLOT 3
PEEK 50176 READ SLOT 4
PEEK 50432 READ SLOT 5
PEEK 50688 READ SLOT 6 (162=DISK CONROLLOR CARD)
PEEK 50944 READ SLOT 7
PEEK 64899 INDICATES WHICH COMPUTER YOU'RE USING
223=APPLE II OR II+, 234=FRANKLIN ACE OR ?, 255=APPLE IIE
POKE 33,33 SCRUNCH LISTING AND REMOVE SPACES IN QUOTE STATEMENTS
POKE 36,X USE AS PRINTER TAB (X=TAB - 1)
POKE 50,128 MAKES ALL OUTPUT TO THE SCREEN INVISIBLE
POKE 50,RANDOM SCRAMBLES OUTPUT TO SCREEN
POKE 51,0 DEFEATS "NOT DIRECT COMMAND", SOMETIMES DOESN'T WORK
POKE 82,128 MAKE CASETTE PROGRAM AUTO-RUN WHEN LOADED
POKE 214,255 SETS RUN FLAG IN FP & ANY KEY STROKES WILL RUN DISK PROGRA
POKE 216,0 CANCEL ONERR FLAG
POKE 1010,3 SETS THE RESET VECTOR TO INITIATE
POKE 1011,150 A COLD START (BOOT)
POKE 1010,102 MAKE
POKE 1011,213 RESET
POKE 1012,112 RUN
POKE 1014,165 SETS THE AMPERSAND (&) VECTOR
POKE 1015,214 TO LIST YOUR PROGRAM
POKE 1014,110 SETS THE AMPERSAND (&) VECTOR
POKE 1015,165 TO CATALOG A DISK
POKE 1912+SLOT,1 ON APPLE PARALLEL CARD (WITH P1-02 PROM) WILL ENABLE L/F'S
POKE 1912+SLOT,0 ON APPLE PARALLEL CARD (WITH P1-02 PROM) WILL ENABLE L/F'S
POKE 2049,1 THIS WILL CAUSE THE FIRST LINE OF PROGRAM TO LIST REPEATEDLY
POKE 40514,20 ALLOWS TEXT FILE GREETING PROGRAM
POKE 40514,52 ALLOWS BINARY FILE GREETING PROGRAM
POKE 40993,24 THIS ALLOWS
POKE 40994,234 DISK COMMANDS IN
POKE 40995,234 THE DIRECT MODE
POKE 42319,96 DISABLES THE INIT COMMAND
POKE 42768,234 CANCEL ALL
POKE 42769,234 DOS ERROR
POKE 42770,234 MESSAGES
POKE 43624,X SELECTS DISK DRIVE WITHOUT EXECUTING A COMMAND (48K SYSTEM)
POKE 43699,0 TURNS AN EXEC FILE OFF BUT LEAVES IT OPEN UNTIL A FP, CLOSE
POKE 43699,1 TURNS AN EXEC FILE BACK ON. INIT, OR MAXFILES IS ISSUE
POKE 44452,24 ALLOWS 20 FILE NAMES (2 EXTRA)
POKE 44605,23 BEFORE CATALOG PAUSE
POKE 44505,234 REVEALS DELETED FILE
POKE 44506,234 NAMES IN CATALG
POKE 44513,67 CATALOG WILL RETURN ONLY LOCKED FILES
POKE 44513,2 RETURN CATALOG TO NORMAL
POKE 44578,234 CANCEL CARRIAGE
POKE 44579,234 RETURNS AFTER CATALOG
POKE 44580,234 FILE NAMES
POKE 44596,234 CANCEL
POKE 44597,234 CATALOG-STOP
POKE 44598,234 WHEN SCREEN IS FULL
POKE 44599,234 STOP CATALOG AT EACH FILE
POKE 44600,234 NAME AND WAIT FOR A KEYPRESS
POKE 46922,96 THIS ALLOWS DISK
POKE 46923,234 INITIALATION
POKE 46924,234 WITHOUT PUTTING
POKE 44723,4 DOS ON THE DISK
POKE 49107,234 PREVENT LANGUAGE
POKE 49108,234 CARD FROM LOADING
POKE 49109,234 DURING RE-BOOT
POKE 49168,0 CLEAR KEYBOARD
POKE 49232,0 DISPLAY GRAPHICS
POKE 49233,0 DISPLAY TEXT
POKE 49234,0 DISPLAY FULL GRAPHICS
POKE 49235,0 DISPLAY TEXT/GRAPHICS
POKE 49236,0 DISPLAY GRAPHICS PAGE 1
POKE 49237,0 DISPLAY GRAPHICS PAGE 2
POKE 49238,0 DISPLAY LORES
POKE 49239,0 DISPLAY HIRES
------------------------------------------------------------------------------
48K MEMORY MAP
DECIMAL HEX USAGE
------------------------------------------------------------------------------
0-255 $0-$FF ZERO-PAGE SYSTEM STORAGE
256-511 $100-$1FF SYSTEM STACK
512-767 $200-$2FF KEYBOARD CHARACTER BUFFER
768-975 $300-$3CF OFTEN AVAILABLE AS FREE SPACE FOR USER PROGRAMS
976-1023 $3D0-3FF SYSTEM VECTORS
1024-2047 $400-$7FF TEXT AND LO-RES GRAPHICS PAGE 1
2048-LOMEM $800-LOMEM PROGRAM STORAGE
2048-3071 $800-$BFF TEXT AND LO-RES GRAPHICS PAGE 2 OR FREE SPACE
3072-8191 $C00-$1FFF FREE SPACE UNLESS RAM APPLESOFT IS IN USE
8192-16383 $2000-$3FFF HI-RES PAGE 1 OR FREE SPACE
16384-24575 $4000-$5FFF HI-RES PAGE 2 OR FREE SPACE
24576-38999 $6000-$95FF FREE SPACE AND STRING STORAGE
38400-49151 $9600-$BFFF DOS
49152-53247 $C000-$CFFF I/O HARDWARE (RESERVED)
53248-57343 $D000-$DFFF APPLESOFT IN LANGUAGE CARD OR ROM
57344-63487 $E000-$F7FF APPLESOFT OR INTEGER BASIC IN LANGUAGE CARD OR ROM
63488-65535 $F800-$FFFF SYSTEM MONITOR
PEEK: TO EXAMINE ANY MEMORY LOCATION L, PRINT PEEK (L), WHERE L IS A DECIMAL
NUMBER 0-65535. TO PEEK AT A TWO-BYTE NUMBER AT CONSEQUTIVE LOCATIONS L AND
L+1, PRINT PEEK (L) + PEEK (L+1) * 256
POKE: TO ASSIGN A VALUE X (0-255) TO LOCATION L; POKE L,X. TO POKE A TWO-BYT
NUMBER (NECESSARY IF X>255), POKE L,X-INT(X/256)*256, AND POKE L+1,INT(X/256).
CALL: TO EXECUTE A MACHINE LANGUAGE SUB ROUTINE AT LOCATION L, CALL L.
JUST FOR FUN TRY THIS: POKE 33,90. THEN TRY LISTING YOUR PROGRAM. OR TRY:
0,99 OR POKE 50,250 OR POKE 50,127. USE RESET TO RETURN TO NORMAL.
FOR TRUE RANDOM NUMBER GENERATION TRY THIS:X= RND(PEEK(78)+PEEK(79)*256)
TO LOCATE THE STARTING ADDRESS OF THE LAST BLOADED FILE USE: PEEK(-21902)+PEEK
(-21901)*256 (RESULT IS IN HEX)
TO DETERMINE THE LENGTH OF THE LAST BLOADED FILE USE: PEEK(-21920)+PEEK(-21919
*256 (RESULT IS IN HEX)
TO DETERMINE THE LINE NUMBER THAT CAUSED AN ERROR TO OCCUR, SET X TO: PEEK(218
+PEEK(219)*256
------------------------------------------------------------------------------
E-Mail Fredric L. Rice / The Skeptic Tank
``` |
143,405 | <p>What are the differences in implementing interfaces <strong>implicitly</strong> and <strong>explicitly</strong> in C#?</p>
<p>When should you use implicit and when should you use explicit?</p>
<p>Are there any pros and/or cons to one or the other?</p>
<hr>
<p>Microsoft's official guidelines (from first edition <a href="https://rads.stackoverflow.com/amzn/click/com/0321246756" rel="noreferrer" rel="nofollow noreferrer">Framework Design Guidelines</a>) states that <strong>using explicit implementations are not recommended</strong>, since it gives the code unexpected behaviour.</p>
<p>I think this guideline is very <strong>valid in a pre-IoC-time</strong>, when you don't pass things around as interfaces.</p>
<p>Could anyone touch on that aspect as well?</p>
| [
{
"answer_id": 143423,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 10,
"selected": true,
"text": "<p><strong>Implicit</strong> is when you define your interface via a member on your class. <strong>Explicit</strong> is w... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] | What are the differences in implementing interfaces **implicitly** and **explicitly** in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
---
Microsoft's official guidelines (from first edition [Framework Design Guidelines](https://rads.stackoverflow.com/amzn/click/com/0321246756)) states that **using explicit implementations are not recommended**, since it gives the code unexpected behaviour.
I think this guideline is very **valid in a pre-IoC-time**, when you don't pass things around as interfaces.
Could anyone touch on that aspect as well? | **Implicit** is when you define your interface via a member on your class. **Explicit** is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: `IList.CopyTo` would be implicitly implemented as:
```
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
```
and explicitly as:
```
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
```
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
```
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
```
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the [**next post**](https://stackoverflow.com/questions/143405/c-interfaces-implicit-and-explicit-implementation#143425) in this thread for excellent reasoning behind each. |
143,429 | <p>We all know that commenting our code is an important part of coding style for making our code understandable to the next person who comes along, or even ourselves in 6 months or so.</p>
<p>However, sometimes a comment just doesn't cut the mustard. I'm not talking about obvious jokes or vented frustraton, I'm talking about comments that appear to be making an attempt at explanation, but do it so poorly they might as well not be there. Comments that are <strong>too short</strong>, are <strong>too cryptic</strong>, or are <strong>just plain wrong</strong>. </p>
<p>As a cautonary tale, could you share something you've seen that was really just <strong>that bad</strong>, and if it's not obvious, show the code it was referring to and point out what's wrong with it? What <strong>should</strong> have gone in there instead?</p>
<p>See also: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/163600/when-not-to-comment-code">When NOT to comment your code</a></li>
<li><a href="https://stackoverflow.com/questions/121945/how-do-you-like-your-comments-best-practices">How do you like your comments? (Best Practices)</a></li>
<li><a href="https://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered">What is the best comment in source code you have ever encountered?</a></li>
</ul>
| [
{
"answer_id": 143439,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 8,
"selected": true,
"text": "<p>Just the typical Comp Sci 101 type comments:</p>\n\n<pre><code>$i = 0; //set i to 0\n\n$i++; //use sneaky trick to... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | We all know that commenting our code is an important part of coding style for making our code understandable to the next person who comes along, or even ourselves in 6 months or so.
However, sometimes a comment just doesn't cut the mustard. I'm not talking about obvious jokes or vented frustraton, I'm talking about comments that appear to be making an attempt at explanation, but do it so poorly they might as well not be there. Comments that are **too short**, are **too cryptic**, or are **just plain wrong**.
As a cautonary tale, could you share something you've seen that was really just **that bad**, and if it's not obvious, show the code it was referring to and point out what's wrong with it? What **should** have gone in there instead?
See also:
* [When NOT to comment your code](https://stackoverflow.com/questions/163600/when-not-to-comment-code)
* [How do you like your comments? (Best Practices)](https://stackoverflow.com/questions/121945/how-do-you-like-your-comments-best-practices)
* [What is the best comment in source code you have ever encountered?](https://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered) | Just the typical Comp Sci 101 type comments:
```
$i = 0; //set i to 0
$i++; //use sneaky trick to add 1 to i!
if ($i==$j) { // I made sure to use == rather than = here to avoid a bug
```
That sort of thing. |
143,484 | <p>I want to change the title showing in a page based on information I pick up from within the page (eg to show the number of inbox messages)</p>
<p><code>document.getElementsByTagName('title')[0].innerHTML="foo";</code> does change the title tag, but firefox does not update the displayed title (in window and tags) when this happens. </p>
<p>Is this possible? </p>
| [
{
"answer_id": 143494,
"author": "Vhaerun",
"author_id": 11234,
"author_profile": "https://Stackoverflow.com/users/11234",
"pm_score": 5,
"selected": true,
"text": "<p>Try using this instead: </p>\n\n<pre>\ndocument.title = \"MyTitle\";\n</pre>\n"
},
{
"answer_id": 143502,
"a... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
] | I want to change the title showing in a page based on information I pick up from within the page (eg to show the number of inbox messages)
`document.getElementsByTagName('title')[0].innerHTML="foo";` does change the title tag, but firefox does not update the displayed title (in window and tags) when this happens.
Is this possible? | Try using this instead:
```
document.title = "MyTitle";
``` |
143,552 | <p>In MySQL, If I have a list of date ranges (range-start and range-end). e.g.</p>
<pre><code>10/06/1983 to 14/06/1983
15/07/1983 to 16/07/1983
18/07/1983 to 18/07/1983
</code></pre>
<p>And I want to check if another date range contains ANY of the ranges already in the list, how would I do that?</p>
<p>e.g.</p>
<pre><code>06/06/1983 to 18/06/1983 = IN LIST
10/06/1983 to 11/06/1983 = IN LIST
14/07/1983 to 14/07/1983 = NOT IN LIST
</code></pre>
| [
{
"answer_id": 143568,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 10,
"selected": true,
"text": "\n\n<p>This is a classical problem, and it's actually easier if you reverse the logic.</p>\n\n<p>Let me give you an e... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
] | In MySQL, If I have a list of date ranges (range-start and range-end). e.g.
```
10/06/1983 to 14/06/1983
15/07/1983 to 16/07/1983
18/07/1983 to 18/07/1983
```
And I want to check if another date range contains ANY of the ranges already in the list, how would I do that?
e.g.
```
06/06/1983 to 18/06/1983 = IN LIST
10/06/1983 to 11/06/1983 = IN LIST
14/07/1983 to 14/07/1983 = NOT IN LIST
``` | This is a classical problem, and it's actually easier if you reverse the logic.
Let me give you an example.
I'll post one period of time here, and all the different variations of other periods that overlap in some way.
```none
|-------------------| compare to this one
|---------| contained within
|----------| contained within, equal start
|-----------| contained within, equal end
|-------------------| contained within, equal start+end
|------------| not fully contained, overlaps start
|---------------| not fully contained, overlaps end
|-------------------------| overlaps start, bigger
|-----------------------| overlaps end, bigger
|------------------------------| overlaps entire period
```
on the other hand, let me post all those that doesn't overlap:
```none
|-------------------| compare to this one
|---| ends before
|---| starts after
```
So if you simple reduce the comparison to:
```none
starts after end
ends before start
```
then you'll find all those that doesn't overlap, and then you'll find all the non-matching periods.
For your final NOT IN LIST example, you can see that it matches those two rules.
You will need to decide wether the following periods are IN or OUTSIDE your ranges:
```none
|-------------|
|-------| equal end with start of comparison period
|-----| equal start with end of comparison period
```
If your table has columns called range\_end and range\_start, here's some simple SQL to retrieve all the matching rows:
```sql
SELECT *
FROM periods
WHERE NOT (range_start > @check_period_end
OR range_end < @check_period_start)
```
Note the *NOT* in there. Since the two simple rules finds all the *non-matching* rows, a simple NOT will reverse it to say: *if it's not one of the non-matching rows, it has to be one of the matching ones*.
Applying simple reversal logic here to get rid of the NOT and you'll end up with:
```sql
SELECT *
FROM periods
WHERE range_start <= @check_period_end
AND range_end >= @check_period_start
``` |
143,554 | <p>I have written a ruby script which opens up dlink admin page in firefox and does a ADSL connection or disconnection.</p>
<p>I could run this script in the terminal without any problem. But if I put it as cron job, it doesn't fire up firefox.</p>
<p>This is the entry I have in <em>crontab</em></p>
<pre><code># connect to dataone
55 17 * * * ruby /home/raguanu/Dropbox/nettie.rb >> /tmp/cron_test
</code></pre>
<p>I see the following entries in /tmp/cron_test. So it looks like the script indeed ran.</p>
<pre><code>PROFILE:
i486-linux
/usr/bin/firefox -jssh
</code></pre>
<p>But I couldn't figure out why I didn't see firefox opening up, for this automation to work. Here is <em>/home/raguanu/Dropbox/nettie.rb</em></p>
<pre><code>#!/usr/bin/ruby -w
require 'rubygems'
require 'firewatir'
require 'optiflag'
module Options extend OptiFlagSet
character_flag :d do
long_form 'disconnect'
description 'Mention this flag if you want to disconnect dataone'
end
flag :l do
optional
long_form 'admin_link'
default 'http://192.168.1.1'
description 'Dlink web administration link. Defaults to http://192.168.1.1'
end
flag :u do
optional
long_form 'user'
default 'admin'
description 'Dlink administrator user name. Defaults to "admin"'
end
flag :p do
optional
long_form 'password'
default 'admin'
description 'Dlink administrator password. Defaults to "admin"'
end
flag :c do
optional
long_form 'connection_name'
default 'bsnl'
description 'Dataone connection name. Defaults to "bsnl"'
end
extended_help_flag :h do
long_form 'help'
end
and_process!
end
class DlinkAdmin
include FireWatir
def initialize(admin_link = "http://192.168.1.1", user = 'admin', pwd = 'admin')
@admin_link, @user, @pwd = admin_link, user, pwd
end
def connect( connection_name = 'bsnl' )
goto_connection_page connection_name
# disconnect prior to connection
@browser.button(:value, 'Disconnect').click
# connect
@browser.button(:value, 'Connect').click
# done!
@browser.close
end
def disconnect( connection_name = 'bsnl' )
goto_connection_page connection_name
# disconnect
@browser.button(:value, 'Disconnect').click
# done!
@browser.close
end
private
def goto_connection_page( connection_name = 'bsnl')
@browser ||= Firefox.new
@browser.goto(@admin_link)
# login
@browser.text_field(:name, 'uiViewUserName').set(@user)
@browser.text_field(:name, 'uiViewPassword').set(@pwd)
@browser.button(:value,'Log In').click
# setup > dataone
@browser.image(:alt, 'Setup').click
@browser.link(:text, connection_name).click
end
end
admin = DlinkAdmin.new(Options.flags.l, Options.flags.u, Options.flags.p)
unless Options.flags.d?
admin.connect( Options.flags.c )
else
admin.disconnect( Options.flags.c )
end
</code></pre>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 143596,
"author": "mana",
"author_id": 12016,
"author_profile": "https://Stackoverflow.com/users/12016",
"pm_score": 0,
"selected": false,
"text": "<p>the crontab entry is wrong</p>\n\n<p>it is like</p>\n\n<pre><code>#min hour day month dow user command... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15139/"
] | I have written a ruby script which opens up dlink admin page in firefox and does a ADSL connection or disconnection.
I could run this script in the terminal without any problem. But if I put it as cron job, it doesn't fire up firefox.
This is the entry I have in *crontab*
```
# connect to dataone
55 17 * * * ruby /home/raguanu/Dropbox/nettie.rb >> /tmp/cron_test
```
I see the following entries in /tmp/cron\_test. So it looks like the script indeed ran.
```
PROFILE:
i486-linux
/usr/bin/firefox -jssh
```
But I couldn't figure out why I didn't see firefox opening up, for this automation to work. Here is */home/raguanu/Dropbox/nettie.rb*
```
#!/usr/bin/ruby -w
require 'rubygems'
require 'firewatir'
require 'optiflag'
module Options extend OptiFlagSet
character_flag :d do
long_form 'disconnect'
description 'Mention this flag if you want to disconnect dataone'
end
flag :l do
optional
long_form 'admin_link'
default 'http://192.168.1.1'
description 'Dlink web administration link. Defaults to http://192.168.1.1'
end
flag :u do
optional
long_form 'user'
default 'admin'
description 'Dlink administrator user name. Defaults to "admin"'
end
flag :p do
optional
long_form 'password'
default 'admin'
description 'Dlink administrator password. Defaults to "admin"'
end
flag :c do
optional
long_form 'connection_name'
default 'bsnl'
description 'Dataone connection name. Defaults to "bsnl"'
end
extended_help_flag :h do
long_form 'help'
end
and_process!
end
class DlinkAdmin
include FireWatir
def initialize(admin_link = "http://192.168.1.1", user = 'admin', pwd = 'admin')
@admin_link, @user, @pwd = admin_link, user, pwd
end
def connect( connection_name = 'bsnl' )
goto_connection_page connection_name
# disconnect prior to connection
@browser.button(:value, 'Disconnect').click
# connect
@browser.button(:value, 'Connect').click
# done!
@browser.close
end
def disconnect( connection_name = 'bsnl' )
goto_connection_page connection_name
# disconnect
@browser.button(:value, 'Disconnect').click
# done!
@browser.close
end
private
def goto_connection_page( connection_name = 'bsnl')
@browser ||= Firefox.new
@browser.goto(@admin_link)
# login
@browser.text_field(:name, 'uiViewUserName').set(@user)
@browser.text_field(:name, 'uiViewPassword').set(@pwd)
@browser.button(:value,'Log In').click
# setup > dataone
@browser.image(:alt, 'Setup').click
@browser.link(:text, connection_name).click
end
end
admin = DlinkAdmin.new(Options.flags.l, Options.flags.u, Options.flags.p)
unless Options.flags.d?
admin.connect( Options.flags.c )
else
admin.disconnect( Options.flags.c )
end
```
Any help is appreciated. | You need to have a DISPLAY environment pointing at a valid X-server. This could either involve setting it to the value ":0.0" (without quotes), such that it refers to your local standard DISPLAY.
There's a few things to keep in mind though:
You could run an X virtual frame buffer (xvfb), so that Firefox simply uses that as it's display. This would mean that Firefox would be able to do all its graphical operations, but that it would be independent of your standard graphical environment. You'll have to set the DISPLAY variable appropriately so that it points to the xvfb instance. For instance, if you invoke xvfb as follows:
```
Xvfb :1 -screen 0 1600x1200x32
```
Then you'll be able to use this by setting the DISPLAY variable to :1
You're starting a full-blown firefox instance to simply connect or disconnect your modem. You would most likely be able to use "curl" to send the appropriate HTTP requests to the server, such that it performs a connect or disconnect for you. One way to trivially see what you should recreate would be to install a Firefox plugin such as LiveHTTPHeaders and note down the most important HTTP requests as you perform the actions manually.
There's even a ruby binding for curl:
[libcurl for Ruby](http://curl.haxx.se/libcurl/ruby/). The resulting script should be much smaller than your current script. |
143,571 | <p>I'm building my first ASP.NET MVC application and I am having some troubles with Partial Views.</p>
<p>If I, as an example, want to put a "Footer" as a Partial I create an "MVC View User Control" in "/Views/Shared/Footer.ascx". (I leave it empty for now)</p>
<p>What is the correct way for adding it to my Layout? </p>
<p>I have tried:</p>
<pre><code><%=Html.RenderPartial("Footer")%>
</code></pre>
<p>and:</p>
<pre><code><%=Html.RenderPartial("~/Views/Shared/Footer.ascx")%>
</code></pre>
<p>For each one I get an exception: </p>
<blockquote>
<p>"CS1502: The best overloaded method
match for
'System.IO.TextWriter.Write(char)' has
some invalid arguments"</p>
</blockquote>
<p>What is the correct way to deal with partials in ASP.NET MVC?</p>
| [
{
"answer_id": 143576,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 6,
"selected": true,
"text": "<p>In this case don't use the <%= syntax. Just use the <% %> syntax. Then the first form in your examples shoul... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm building my first ASP.NET MVC application and I am having some troubles with Partial Views.
If I, as an example, want to put a "Footer" as a Partial I create an "MVC View User Control" in "/Views/Shared/Footer.ascx". (I leave it empty for now)
What is the correct way for adding it to my Layout?
I have tried:
```
<%=Html.RenderPartial("Footer")%>
```
and:
```
<%=Html.RenderPartial("~/Views/Shared/Footer.ascx")%>
```
For each one I get an exception:
>
> "CS1502: The best overloaded method
> match for
> 'System.IO.TextWriter.Write(char)' has
> some invalid arguments"
>
>
>
What is the correct way to deal with partials in ASP.NET MVC? | In this case don't use the <%= syntax. Just use the <% %> syntax. Then the first form in your examples should work.
For more info, check here:
<http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html> |
143,622 | <p>This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?</p>
<pre><code>try {
// Do something
} catch(IOException e) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}
</code></pre>
<p>I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.</p>
| [
{
"answer_id": 143628,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 9,
"selected": true,
"text": "<p>No, since the new <code>throw</code> is not in the <code>try</code> block directly.</p>\n"
},
{
"answer_id": 14363... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270/"
] | This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?
```
try {
// Do something
} catch(IOException e) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}
```
I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java. | No, since the new `throw` is not in the `try` block directly. |
143,680 | <p>It seems that most of the installers for Perl are centered around installing Perl modules, not applications. Things like ExtUtils::MakeMaker and Module::Build are very well suited for modules, but require some additional work for Web Apps.</p>
<p>Ideally it would be nice to be able to do the following after checking out the source from the repository:</p>
<ul>
<li>Have missing dependencies detected</li>
<li>Download and install dependencies from CPAN</li>
<li>Run a command to "Build" the source into a final state (perform any source parsing or configuration necessary for the local environment).</li>
<li>Run a command to install the built files into the appropriate locations. Not only the perl modules, but also things like template (.tt) files, and CGI scripts, JS and image files that should be web-accessible.</li>
<li>Make sure proper permissions are set on installed files (and SELinux context if necessary).</li>
</ul>
<p>Right now we have a system based on <strong>Module::Build</strong> that does most of this. The work was done by done by my co-worker who was learning to use <strong>Module::Build</strong> at the time, and we'd like some advice on generalizing our solution, since it's fairly app-specific right now. In particular, our system requires us to install dependencies by hand (although it does detect them).</p>
<p>Is there any particular system you've used that's been particularly successful? Do you have to write an installer based on <strong>Module::Build</strong> or <strong>ExtUtils::MakeMaker</strong> that's particular to your application, or is something more general available?</p>
<p><strong>EDIT:</strong> To answer brian's questions below:</p>
<ul>
<li>We can log into the machines</li>
<li>We do not have root access to the machines</li>
<li>The machines are all (ostensibly) identical builds of RHEL5 with SELinux enabled</li>
<li>Currently, the people installing the machines are only programmers from our group, and our source is not available to the general public. However, it's conceivable our source could eventually be installed on someone else's machines in our organization, to be installed by their programmers or systems people.</li>
<li>We install by checking out from the repository, though we'd like to have the option of using a distributed archive (see above).</li>
</ul>
| [
{
"answer_id": 143754,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 2,
"selected": false,
"text": "<p>I'd recommend seriously considering a package system such as RPM to do this. Even if you're running on Windows I'd co... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | It seems that most of the installers for Perl are centered around installing Perl modules, not applications. Things like ExtUtils::MakeMaker and Module::Build are very well suited for modules, but require some additional work for Web Apps.
Ideally it would be nice to be able to do the following after checking out the source from the repository:
* Have missing dependencies detected
* Download and install dependencies from CPAN
* Run a command to "Build" the source into a final state (perform any source parsing or configuration necessary for the local environment).
* Run a command to install the built files into the appropriate locations. Not only the perl modules, but also things like template (.tt) files, and CGI scripts, JS and image files that should be web-accessible.
* Make sure proper permissions are set on installed files (and SELinux context if necessary).
Right now we have a system based on **Module::Build** that does most of this. The work was done by done by my co-worker who was learning to use **Module::Build** at the time, and we'd like some advice on generalizing our solution, since it's fairly app-specific right now. In particular, our system requires us to install dependencies by hand (although it does detect them).
Is there any particular system you've used that's been particularly successful? Do you have to write an installer based on **Module::Build** or **ExtUtils::MakeMaker** that's particular to your application, or is something more general available?
**EDIT:** To answer brian's questions below:
* We can log into the machines
* We do not have root access to the machines
* The machines are all (ostensibly) identical builds of RHEL5 with SELinux enabled
* Currently, the people installing the machines are only programmers from our group, and our source is not available to the general public. However, it's conceivable our source could eventually be installed on someone else's machines in our organization, to be installed by their programmers or systems people.
* We install by checking out from the repository, though we'd like to have the option of using a distributed archive (see above). | What are your limitations for installing web apps? Can you log into the machine? Are all of the machines running the same thing? Are the people installing the web apps co-workers or random people from the general public? Are the people installing this sysadmins, programmers, web managers, or something else? Do you install by distributed an archive or checking out from source control?
For most of my stuff, which involves sysadmins familiar with Perl installing in control environments, I just use [MakeMaker](http://search.cpan.org/dist/ExtUtils-Makemaker). It's easy to get it to do all the things you listed if you know a little about `MakeMaker`. If you want to know more about that, ask a another question. ;) [Module::Build](http://search.cpan.org/dist/Module-Build) is just as easy, though, and the way to go if you don't already like using `MakeMaker`.
`Module::Build` would be a good way to go to handle lots of different situations if the people are moderately clueful about the command line and installing software. You'll have a lot of flexibility with `Module::Build`, but also a bit more work. And, the `cpan` tool (which comes with Perl), can install from the current directory and handle dependencies for you. Just tell it to install the current directory:
```
$ cpan .
```
If you only have to install on a single platorm, you'll probably have an easier time making a package in the native format. You could even have `Module::Build` make that package for you so the developers have the flexibility of `Module::Build`, but the installers have the ease of the native process. Sticking with `Module::Build` also means that you could create different packages for different platforms from a single build tool.
If the people installing the web application really have no idea about command lines, CPAN, and other things, you'll probably want to use a packager and installer that doesn't scare them or make them think about what is going on, and can accurately report problems to you automatically.
As Dave points out, using a real CPAN mirror always gets you the latest version of a module, but you can also make your own "fake" CPAN mirror with exactly the distributions you want and have the normal CPAN tools install from that. For our customers, we make "CPAN on a CD" (although thumb drives are good now too). With a simple "run me" script everything gets installed in exactly the versions they need. See, for instance, my Making my own CPAN talk if you're interested in that. Again, consider the audience when you think about that. It's not something you'd hand to the general public.
Good luck, :) |
143,712 | <p>Is there a way of comparing two bitmasks in Transact-SQL to see if any of the bits match? I've got a User table with a bitmask for all the roles the user belongs to, and I'd like to select all the users that have <em>any</em> of the roles in the supplied bitmask. So using the data below, a roles bitmask of 6 (designer+programmer) should select Dave, Charlie and Susan, but not Nick.</p>
<pre>User Table
----------
ID Username Roles
1 Dave 6
2 Charlie 2
3 Susan 4
4 Nick 1
Roles Table
-----------
ID Role
1 Admin
2 Programmer
4 Designer</pre>
<p>Any ideas? Thanks.</p>
| [
{
"answer_id": 143716,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 3,
"selected": false,
"text": "<p>Use the Transact-SQL <a href=\"http://msdn.microsoft.com/en-us/library/ms174965.aspx\" rel=\"nofollow norefe... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] | Is there a way of comparing two bitmasks in Transact-SQL to see if any of the bits match? I've got a User table with a bitmask for all the roles the user belongs to, and I'd like to select all the users that have *any* of the roles in the supplied bitmask. So using the data below, a roles bitmask of 6 (designer+programmer) should select Dave, Charlie and Susan, but not Nick.
```
User Table
----------
ID Username Roles
1 Dave 6
2 Charlie 2
3 Susan 4
4 Nick 1
Roles Table
-----------
ID Role
1 Admin
2 Programmer
4 Designer
```
Any ideas? Thanks. | The answer to your question is to use the Bitwise `&` like this:
```
SELECT * FROM UserTable WHERE Roles & 6 != 0
```
The `6` can be exchanged for any combination of your bitfield where you want to check that any user has one or more of those bits. When trying to validate this I usually find it helpful to write this out longhand in binary. Your user table looks like this:
```
1 2 4
------------------
Dave 0 1 1
Charlie 0 1 0
Susan 0 0 1
Nick 1 0 0
```
Your test (6) is this
```
1 2 4
------------------
Test 0 1 1
```
If we go through each person doing the bitwaise And against the test we get these:
```
1 2 4
------------------
Dave 0 1 1
Test 0 1 1
Result 0 1 1 (6)
Charlie 0 1 0
Test 0 1 1
Result 0 1 0 (2)
Susan 0 0 1
Test 0 1 1
Result 0 0 1 (4)
Nick 1 0 0
Test 0 1 1
Result 0 0 0 (0)
```
The above should demonstrate that any records where the result is not zero has one or more of the requested flags.
Edit: Here's the test case should you want to check this
```
with test (id, username, roles)
AS
(
SELECT 1,'Dave',6
UNION SELECT 2,'Charlie',2
UNION SELECT 3,'Susan',4
UNION SELECT 4,'Nick',1
)
select * from test where (roles & 6) != 0 // returns dave, charlie & susan
```
or
```
select * from test where (roles & 2) != 0 // returns Dave & Charlie
```
or
```
select * from test where (roles & 7) != 0 // returns dave, charlie, susan & nick
``` |
143,736 | <p>I have a simple message box in a WPF application that is launched as below:</p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Howdy", "Howdy");
}
</code></pre>
<p>I can get <a href="http://www.codeplex.com/white" rel="nofollow noreferrer" title="white">white</a> to click my button and launch the message box. </p>
<p>UISpy shows it as a child of my window I couldn't work out the method to access it.</p>
<p>How do I get access to my MessageBox to verify its contents?</p>
| [
{
"answer_id": 143766,
"author": "Brownie",
"author_id": 6600,
"author_profile": "https://Stackoverflow.com/users/6600",
"pm_score": 3,
"selected": true,
"text": "<p>Found it! The window class has a MessageBox method that does the trick:</p>\n\n<pre><code> var app = Application.La... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6600/"
] | I have a simple message box in a WPF application that is launched as below:
```
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Howdy", "Howdy");
}
```
I can get [white](http://www.codeplex.com/white "white") to click my button and launch the message box.
UISpy shows it as a child of my window I couldn't work out the method to access it.
How do I get access to my MessageBox to verify its contents? | Found it! The window class has a MessageBox method that does the trick:
```
var app = Application.Launch(@"c:\ApplicationPath.exe");
var window = app.GetWindow("Window1");
var helloButton = window.Get<Button>("Hello");
Assert.IsNotNull(helloButton);
helloButton.Click();
var messageBox = window.MessageBox("Howdy");
Assert.IsNotNull(messageBox);
``` |
143,739 | <p>How do you do your own fonts? I don't want a heavyweight algorithm (freetype, truetype, adobe, etc) and would be fine with pre-rendered bitmap fonts.</p>
<p>I do want anti-aliasing, and would like proportional fonts if possible.</p>
<p>I've heard I can use Gimp to do the rendering (with some post processing?)</p>
<p>I'm developing for an embedded device with an LCD. It's got a 32 bit processor, but I don't want to run Linux (overkill - too much code/data space for too little functionality that I would use)</p>
<p>C. C++ if necessary, but C is preferred. Algorithms and ideas/concepts are fine in any language...</p>
<p>-Adam</p>
| [
{
"answer_id": 143810,
"author": "SteinNorheim",
"author_id": 19220,
"author_profile": "https://Stackoverflow.com/users/19220",
"pm_score": 3,
"selected": true,
"text": "<p>In my old demo-scene days I often drew all characters in the font in one big bitmap image. In the code, I stored th... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] | How do you do your own fonts? I don't want a heavyweight algorithm (freetype, truetype, adobe, etc) and would be fine with pre-rendered bitmap fonts.
I do want anti-aliasing, and would like proportional fonts if possible.
I've heard I can use Gimp to do the rendering (with some post processing?)
I'm developing for an embedded device with an LCD. It's got a 32 bit processor, but I don't want to run Linux (overkill - too much code/data space for too little functionality that I would use)
C. C++ if necessary, but C is preferred. Algorithms and ideas/concepts are fine in any language...
-Adam | In my old demo-scene days I often drew all characters in the font in one big bitmap image. In the code, I stored the (X,Y) coordinates of each character in the font, as well as the width of each character. The height was usually constant throughout the font. If space isn't an issue, you can put all characters in a grid, that is - have a constant distance between the top-left corner of each character.
Rendering the text then becomes a matter of copying one letter at a time to the destination position. At that time, I usually reserved one color as being the "transparent" color, but you could definitely use an alpha-channel for this today.
A simpler approach, that can be used for small b/w fonts, is to define the characters directly in code:
```
LetterA db 01111100b
db 11000110b
db 11000110b
db 11111110b
db 11000110b
db 11000110b
```
The XPM file format is actually a file format with C syntax that can be used as a hybrid solution for storing the characters. |
143,746 | <p>I know most people think that as a <em>bad practice</em> but when you are trying to make your class public interface only work with references, keeping pointers inside and only when necessary, I think there is no way to return something telling that the value you are looking doesn't exist in the container.</p>
<pre>
class list {
public:
value &get(type key);
};
</pre>
<p>Let's think that you don't want to have dangerous pointers being saw in the public interface of the class, how do you return a not found in this case, throwing an exception?</p>
<p>What is your approach to that? Do you return an empty <em>value</em> and check for the empty state of it? I actually use the throw approach but I introduce a checking method:</p>
<pre>
class list {
public:
bool exists(type key);
value &get(type key);
};
</pre>
<p>So when I forget to check that the value exists first I get an exception, that is really an <em>exception</em>.</p>
<p>How would you do it?</p>
| [
{
"answer_id": 143758,
"author": "MidnightGun",
"author_id": 13220,
"author_profile": "https://Stackoverflow.com/users/13220",
"pm_score": -1,
"selected": false,
"text": "<p>Interesting question. It's a problem in C++ to exclusively use references I guess - in Java the references are mor... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623/"
] | I know most people think that as a *bad practice* but when you are trying to make your class public interface only work with references, keeping pointers inside and only when necessary, I think there is no way to return something telling that the value you are looking doesn't exist in the container.
```
class list {
public:
value &get(type key);
};
```
Let's think that you don't want to have dangerous pointers being saw in the public interface of the class, how do you return a not found in this case, throwing an exception?
What is your approach to that? Do you return an empty *value* and check for the empty state of it? I actually use the throw approach but I introduce a checking method:
```
class list {
public:
bool exists(type key);
value &get(type key);
};
```
So when I forget to check that the value exists first I get an exception, that is really an *exception*.
How would you do it? | The STL deals with this situation by using iterators. For example, the std::map class has a similar function:
```
iterator find( const key_type& key );
```
If the key isn't found, it returns 'end()'. You may want to use this iterator approach, or to use some sort of wrapper for your return value. |
143,747 | <p>I'm writing some JavaScript code that needs to fire the <code>click</code> event for a link. In Internet Explorer I can do this </p>
<pre><code>var button = document.getElementById('myButton');
button.click();
</code></pre>
<p>But this doesn't work in Firefox, and I assume any other browser. In Firefox, I've done this </p>
<pre><code>var button = document.getElementById('myButton');
window.location = button.href;
</code></pre>
<p>I feel like this is not the best way to do this. Is there a better way to trigger a <code>click</code> event? Preferably something that works regardless of the type of element or the browser.</p>
| [
{
"answer_id": 143755,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>It's not generally possible, afaik, mozilla has the <a href=\"http://developer.mozilla.org/En/DOM:element.click#1... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | I'm writing some JavaScript code that needs to fire the `click` event for a link. In Internet Explorer I can do this
```
var button = document.getElementById('myButton');
button.click();
```
But this doesn't work in Firefox, and I assume any other browser. In Firefox, I've done this
```
var button = document.getElementById('myButton');
window.location = button.href;
```
I feel like this is not the best way to do this. Is there a better way to trigger a `click` event? Preferably something that works regardless of the type of element or the browser. | <http://jehiah.cz/archive/firing-javascript-events-properly>
```
function fireEvent(element,event) {
if (document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
} else {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
}
``` |
143,756 | <p>I need to rename the database but when I do in
<code>PGAdmin : ALTER DATABASE "databaseName" RENAME TO "databaseNameOld"</code> it told me that it cannot.</p>
<p>How can I do it?</p>
<p>(<strong>Version 8.3 on WindowsXP</strong>)</p>
<p><strong>Update</strong></p>
<ul>
<li><p>The first error message : Cannot because I was connect to it. So I selected an other database and did the queries.</p></li>
<li><p>I get a second error message telling me that it has come user connect. I see in the <code>PGAdmin</code> screen that it has many <code>PID</code> but they are inactive... I do not see how to kill them.</p></li>
</ul>
| [
{
"answer_id": 143764,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 8,
"selected": false,
"text": "<p>Try not quoting the database name:</p>\n\n<pre><code>ALTER DATABASE people RENAME TO customers;\n</code></pre>\n\n<p>A... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] | I need to rename the database but when I do in
`PGAdmin : ALTER DATABASE "databaseName" RENAME TO "databaseNameOld"` it told me that it cannot.
How can I do it?
(**Version 8.3 on WindowsXP**)
**Update**
* The first error message : Cannot because I was connect to it. So I selected an other database and did the queries.
* I get a second error message telling me that it has come user connect. I see in the `PGAdmin` screen that it has many `PID` but they are inactive... I do not see how to kill them. | Try not quoting the database name:
```
ALTER DATABASE people RENAME TO customers;
```
Also ensure that there are no other clients connected to the database at the time. Lastly, try posting the error message it returns so we can get a bit more information. |
143,814 | <p>In an ideal world, our development processes would be perfect, resulting in regular releases that were so thoroughly tested that it would never be necessary to "hotfix" a running application.</p>
<p>But, unfortunately, we live in the real world, and sometimes bugs slip past us and don't rear their ugly heads until we're already busy coding away at the next release. And the bug needs to be fixed <strong><em>Now</em></strong>. Not as a part of the next scheduled release. Not tonight when the traffic dies down. <strong><em>Now</em></strong>.</p>
<p>How do you deal with this need? It really can run counter to good design practices, like refactoring your code into nice, discrete class libraries.</p>
<p>Hand-editing markup and stored procedures on a production server can be a recipe for disaster, but it can also avert disaster.</p>
<p>What are some good strategies for application design and deployment techniques to find a balance between maintenance needs and good coding practices?</p>
| [
{
"answer_id": 143851,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "<p>[Even though we test a lot before we release, ] What we do is this:</p>\n<p>Our SVN looks like this:</p>\n<pre><code>/repo/t... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | In an ideal world, our development processes would be perfect, resulting in regular releases that were so thoroughly tested that it would never be necessary to "hotfix" a running application.
But, unfortunately, we live in the real world, and sometimes bugs slip past us and don't rear their ugly heads until we're already busy coding away at the next release. And the bug needs to be fixed ***Now***. Not as a part of the next scheduled release. Not tonight when the traffic dies down. ***Now***.
How do you deal with this need? It really can run counter to good design practices, like refactoring your code into nice, discrete class libraries.
Hand-editing markup and stored procedures on a production server can be a recipe for disaster, but it can also avert disaster.
What are some good strategies for application design and deployment techniques to find a balance between maintenance needs and good coding practices? | [Even though we test a lot before we release, ] What we do is this:
Our SVN looks like this:
```
/repo/trunk/
/repo/tags/1.1
/repo/tags/1.2
/repo/tags/1.3
```
Now whenever we release, we create a tag which we eventually check out in production. Before we do production, we do staging which is [less servers but] pretty much the same as production.
Reasons to create a "tag" include that some of the settings of our app in production code are slightly different (e.g. no errors are emailed, but logged) from "trunk" anyway, so it makes sense to create the tag and commit those changes. And then checkout on the production cluster.
Now whenever we need to *hotfix* an issue, we fix it in `tags/x` first and then we `svn update` from the tag and are good. Sometimes we go through staging, with some issues (e.g. minor/trivial fixes like spelling) we by-pass staging.
The only thing to remember is to apply all patches from `tags/x` to `trunk`.
If you have more than one server, Capistrano (link to capify.org doesn't go to the intended anymore) is extremely helpful to run all those operations. |
143,815 | <p>Can I use JavaScript to check (irrespective of scrollbars) if an HTML element has overflowed its content? For example, a long div with small, fixed size, the overflow property set to visible, and no scrollbars on the element.</p>
| [
{
"answer_id": 143833,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 4,
"selected": false,
"text": "<p>Try comparing <code>element.scrollHeight</code> / <code>element.scrollWidth</code> to <code>element.offsetHeigh... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Can I use JavaScript to check (irrespective of scrollbars) if an HTML element has overflowed its content? For example, a long div with small, fixed size, the overflow property set to visible, and no scrollbars on the element. | Normally, you can compare the `client[Height|Width]` with `scroll[Height|Width]` in order to detect this... but the values will be the same when overflow is visible. So, a detection routine must account for this:
```
// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
// Will temporarily modify the "overflow" style to detect this
// if necessary.
function checkOverflow(el)
{
var curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflow = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
}
```
Tested in FF3, FF40.0.2, IE6, Chrome 0.2.149.30. |
143,822 | <p>this wiki page gave a general idea of how to convert a single char to ascii <a href="http://en.wikibooks.org/wiki/Ruby_Programming/ASCII" rel="noreferrer">http://en.wikibooks.org/wiki/Ruby_Programming/ASCII</a></p>
<p>But say if I have a string and I wanted to get each character's ascii from it, what do i need to do?</p>
<pre><code>"string".each_byte do |c|
$char = c.chr
$ascii = ?char
puts $ascii
end
</code></pre>
<p>It doesn't work because it's not happy with the line $ascii = ?char</p>
<pre><code>syntax error, unexpected '?'
$ascii = ?char
^
</code></pre>
| [
{
"answer_id": 143834,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": true,
"text": "<p>The <code>c</code> variable already contains the char code!</p>\n\n<pre><code>\"string\".each_byte do |c|\n puts... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2668/"
] | this wiki page gave a general idea of how to convert a single char to ascii <http://en.wikibooks.org/wiki/Ruby_Programming/ASCII>
But say if I have a string and I wanted to get each character's ascii from it, what do i need to do?
```
"string".each_byte do |c|
$char = c.chr
$ascii = ?char
puts $ascii
end
```
It doesn't work because it's not happy with the line $ascii = ?char
```
syntax error, unexpected '?'
$ascii = ?char
^
``` | The `c` variable already contains the char code!
```
"string".each_byte do |c|
puts c
end
```
yields
```
115
116
114
105
110
103
``` |
143,847 | <p>What is the best way to find if an object is in an array?</p>
<p>This is the best way I know:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}
console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 143863,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 11,
"selected": true,
"text": "<p>As of ECMAScript 2016 you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glo... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17533/"
] | What is the best way to find if an object is in an array?
This is the best way I know:
```js
function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}
console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined
``` | As of ECMAScript 2016 you can use [`includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
```
arr.includes(obj);
```
If you want to support IE or other older browsers:
```
function include(arr,obj) {
return (arr.indexOf(obj) != -1);
}
```
EDIT:
This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:
1. [Mozilla's](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) (ECMA-262) version:
```
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
```
2. [Daniel James](https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array#144172)'s version:
```
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
```
3. [roosteronacid](https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array#144664)'s version:
```
Array.prototype.hasObject = (
!Array.indexOf ? function (o)
{
var l = this.length + 1;
while (l -= 1)
{
if (this[l - 1] === o)
{
return true;
}
}
return false;
} : function (o)
{
return (this.indexOf(o) !== -1);
}
);
``` |
143,850 | <p>let's say we have a c++ class like:</p>
<pre><code>class MyClass
{
void processArray( <an array of 255 integers> )
{
int i ;
for (i=0;i<255;i++)
{
// do something with values in the array
}
}
}
</code></pre>
<p>and one instance of the class like: </p>
<pre><code>MyClass myInstance ;
</code></pre>
<p>and 2 threads which call the processArray method of that instance (depending on how system executes threads, probably in a completely irregular order). There is no mutex lock used in that scope so both threads can enter.</p>
<p><strong>My question is what happens to the i ? Does each thread scope has it's own "i" or would each entering thread modify i in the for loop, causing i to be changing weirdly all the time.</strong> </p>
| [
{
"answer_id": 143853,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": true,
"text": "<p><code>i</code> is allocated on the stack. Since each thread has its own separate stack, each thread gets its own ... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23000/"
] | let's say we have a c++ class like:
```
class MyClass
{
void processArray( <an array of 255 integers> )
{
int i ;
for (i=0;i<255;i++)
{
// do something with values in the array
}
}
}
```
and one instance of the class like:
```
MyClass myInstance ;
```
and 2 threads which call the processArray method of that instance (depending on how system executes threads, probably in a completely irregular order). There is no mutex lock used in that scope so both threads can enter.
**My question is what happens to the i ? Does each thread scope has it's own "i" or would each entering thread modify i in the for loop, causing i to be changing weirdly all the time.** | `i` is allocated on the stack. Since each thread has its own separate stack, each thread gets its own copy of `i`. |
143,925 | <p>I want to be able to run a single spec file's tests — for the one file I'm editing, for example. <code>rake spec</code> executes all the specs. My project is not a Rails project, so <code>rake spec:doc</code> doesn't work.</p>
<p>Don't know if this matters, but here is my directory structure.</p>
<pre>
./Rakefile
./lib
./lib/cushion.rb
./lib/cushion
./lib/cushion/doc.rb
./lib/cushion/db.rb
./spec
./spec/spec.opts
./spec/spec_helper.rb
./spec/db_spec.rb
</pre>
| [
{
"answer_id": 143934,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 8,
"selected": false,
"text": "<p>The raw invocation:</p>\n\n<pre>\nrake spec SPEC=spec/controllers/sessions_controller_spec.rb \\\n SPEC_OPTS=\"... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12887/"
] | I want to be able to run a single spec file's tests — for the one file I'm editing, for example. `rake spec` executes all the specs. My project is not a Rails project, so `rake spec:doc` doesn't work.
Don't know if this matters, but here is my directory structure.
```
./Rakefile
./lib
./lib/cushion.rb
./lib/cushion
./lib/cushion/doc.rb
./lib/cushion/db.rb
./spec
./spec/spec.opts
./spec/spec_helper.rb
./spec/db_spec.rb
``` | Or you can skip rake and use the 'rspec' command:
```
bundle exec rspec path/to/spec/file.rb
```
In your case I think as long as your ./spec/db\_spec.rb file includes the appropriate helpers, it should work fine.
If you're using an older version of rspec it is:
```
bundle exec spec path/to/spec/file.rb
``` |
143,938 | <p>I'm writing a Delphi expert. I need to be able to write a value to a property on a property which is an object. E.g. I have a GroupBox on the form and I want to edit the Margins.Left property. I'm using the following procedure to do it but if gives an AV on the marked line.</p>
<p>The procedure takes a component from the (property editor) the property name (eg 'Margins.Left') and the new value, parses out the property name, fetches the object, reads the current value and attempts to change it if different. It then calls a method to log any changes.</p>
<pre><code>procedure EditIntegerSubProperty(Component: IOTAComponent;const PropName: String;NewValue: Integer);
var AnObject: TObject;
TK: TTypeKind;
At: Integer;
AClassName, APropName: String;
PropInfo: PPropInfo;
OldValue: Integer;
begin
At := Pos('.', PropName);
if At < 1 then
raise Exception.Create('Invalid SubProperty Name: '+PropName);
AClassName := Copy(PropName, 1, At-1);
APropName := Copy(PropName, At+1, length(PropName));
TK := Component.GetPropTypeByName(AClassName);
if TK <> tkClass then
EXIT;
AnObject := GetObjectProp((Component as INTAComponent).GetComponent, AClassName);
if PropIsType(AnObject, APropName, tkInteger) then
begin
OldValue := GetInt64Prop(AnObject, APropName);
if OldValue <> NewValue then
begin
SetInt64Prop(AnObject, APropName, NewValue); <----AV HERE
ChangeLogInteger(Name, PropName, OldValue, NewValue);
end;
end;
end;
</code></pre>
| [
{
"answer_id": 143952,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.phpmyadmin.net/home_page/index.php\" rel=\"nofollow noreferrer\">phpMyAdmin</a> is a good favourite if y... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23008/"
] | I'm writing a Delphi expert. I need to be able to write a value to a property on a property which is an object. E.g. I have a GroupBox on the form and I want to edit the Margins.Left property. I'm using the following procedure to do it but if gives an AV on the marked line.
The procedure takes a component from the (property editor) the property name (eg 'Margins.Left') and the new value, parses out the property name, fetches the object, reads the current value and attempts to change it if different. It then calls a method to log any changes.
```
procedure EditIntegerSubProperty(Component: IOTAComponent;const PropName: String;NewValue: Integer);
var AnObject: TObject;
TK: TTypeKind;
At: Integer;
AClassName, APropName: String;
PropInfo: PPropInfo;
OldValue: Integer;
begin
At := Pos('.', PropName);
if At < 1 then
raise Exception.Create('Invalid SubProperty Name: '+PropName);
AClassName := Copy(PropName, 1, At-1);
APropName := Copy(PropName, At+1, length(PropName));
TK := Component.GetPropTypeByName(AClassName);
if TK <> tkClass then
EXIT;
AnObject := GetObjectProp((Component as INTAComponent).GetComponent, AClassName);
if PropIsType(AnObject, APropName, tkInteger) then
begin
OldValue := GetInt64Prop(AnObject, APropName);
if OldValue <> NewValue then
begin
SetInt64Prop(AnObject, APropName, NewValue); <----AV HERE
ChangeLogInteger(Name, PropName, OldValue, NewValue);
end;
end;
end;
``` | If you want the database behind a firewall, and believe me, you do want your database behind a firewall, see if you can have a VPN for going directly into the box. Once you are on the VPN, you can use whichever management tool you currently use for managing the database. So if you use SQL Server, you can connect via the VPN, and use Enterprise Manager to manage the database. Oracle probably has a similar tool, although I'm not that familiar. While having a VPN does incur an extra cost, it will probably make things many times easier. |
143,947 | <p>More than about LINQ to [insert your favorite provider here], this question is about searching or filtering in-memory collections. </p>
<p>I know LINQ (or searching/filtering extension methods) works in objects implementing <code>IEnumerable</code> or <code>IEnumerable<T></code>. The question is: <em>because of the nature of enumeration, is every query complexity at least <strong>O(n)</strong>?</em></p>
<p>For example:</p>
<pre><code>var result = list.FirstOrDefault(o => o.something > n);
</code></pre>
<p>In this case, every algorithm will take at least <strong>O(n)</strong> unless <code>list</code> is ordered with respect to <code>'something'</code>, in which case the search should take <strong>O(log(n))</strong>: it should be a binary search. However, If I understand correctly, this query will be resolved through enumeration, so it should take <strong>O(n)</strong>, even in <code>list</code> was previously ordered.</p>
<ul>
<li>Is there something I can do to solve a query in <strong>O(log(n))</strong>?</li>
<li>If I want performance, should I use Array.Sort and Array.BinarySearch?</li>
</ul>
| [
{
"answer_id": 144002,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, it has to be, because the only way of accessing any member of an <code>IEnumerable</code> is by using its methods, w... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18552/"
] | More than about LINQ to [insert your favorite provider here], this question is about searching or filtering in-memory collections.
I know LINQ (or searching/filtering extension methods) works in objects implementing `IEnumerable` or `IEnumerable<T>`. The question is: *because of the nature of enumeration, is every query complexity at least **O(n)**?*
For example:
```
var result = list.FirstOrDefault(o => o.something > n);
```
In this case, every algorithm will take at least **O(n)** unless `list` is ordered with respect to `'something'`, in which case the search should take **O(log(n))**: it should be a binary search. However, If I understand correctly, this query will be resolved through enumeration, so it should take **O(n)**, even in `list` was previously ordered.
* Is there something I can do to solve a query in **O(log(n))**?
* If I want performance, should I use Array.Sort and Array.BinarySearch? | Even with parallelisation, it's still O(n). The constant factor would be different (depending on your number of cores) but as n varied the total time would still vary linearly.
Of course, you could write your own implementations of the various LINQ operators over your own data types, but they'd only be appropriate in very specific situations - you'd have to know for sure that the predicate only operated on the optimised aspects of the data. For instance, if you've got a list of people that's ordered by age, it's not going to help you with a query which tries to find someone with a particular name :)
To examine the predicate, you'd have to use expression trees instead of delegates, and life would become a lot harder.
I suspect I'd normally add new methods which make it obvious that you're using the indexed/ordered/whatever nature of the data type, and which will always work appropriately. You couldn't easily invoke those extra methods from query expressions, of course, but you can still use LINQ with dot notation. |
143,997 | <p>In Jesse Liberty's Learning C# book, he says "Objects of one type can be converted into objects of another type. This is called casting."</p>
<p>If you investigate the IL generated from the code below, you can clearly see that the casted assignment isn't doing the same thing as the converted assignment. In the former, you can see the boxing/unboxing occurring; in the latter you can see a call to a convert method. </p>
<p>I know in the end it may be just a silly semantic difference--but is casting just another word for converting. I don't mean to be snarky, but I'm not interested in anyone's gut feeling on this--opinions don't count here! Can anyone point to a definitive reference that confirms or denies if casting and converting are the same thing?</p>
<pre><code> object x;
int y;
x = 4;
y = ( int )x;
y = Convert.ToInt32( x );
</code></pre>
<p>Thank you</p>
<p>rp</p>
<p>Note added after Matt's comment about explicit/implicit:</p>
<p>I don't think implicit/explicit is the difference. In the code I posted, the change is explicit in both cases. An implicit conversion is what occurs when you assign a short to an int.</p>
<p>Note to Sklivvz:</p>
<p>I wanted confirmation that my suspicion of the looseness of Jesse Liberty's (otherwise usually lucid and clear) language was correct. I thought that Jesse Liberty was being a little loose with his language. I understand that casting is routed in object hierarchy--i.e., you can't cast from an integer to a string but you could cast from custom exception derived from System.Exception to a System.Exception. </p>
<p>It's interesting, though, that when you do try to cast from an int to a string the compiler tells you that it couldn't "convert" the value. Maybe Jesse is more correct than I thought! </p>
| [
{
"answer_id": 144003,
"author": "Matt",
"author_id": 13666,
"author_profile": "https://Stackoverflow.com/users/13666",
"pm_score": -1,
"selected": false,
"text": "<p>The difference there is whether the conversion is implicit or explicit. The first one up there is a cast, the second one... | 2008/09/27 | [
"https://Stackoverflow.com/questions/143997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
] | In Jesse Liberty's Learning C# book, he says "Objects of one type can be converted into objects of another type. This is called casting."
If you investigate the IL generated from the code below, you can clearly see that the casted assignment isn't doing the same thing as the converted assignment. In the former, you can see the boxing/unboxing occurring; in the latter you can see a call to a convert method.
I know in the end it may be just a silly semantic difference--but is casting just another word for converting. I don't mean to be snarky, but I'm not interested in anyone's gut feeling on this--opinions don't count here! Can anyone point to a definitive reference that confirms or denies if casting and converting are the same thing?
```
object x;
int y;
x = 4;
y = ( int )x;
y = Convert.ToInt32( x );
```
Thank you
rp
Note added after Matt's comment about explicit/implicit:
I don't think implicit/explicit is the difference. In the code I posted, the change is explicit in both cases. An implicit conversion is what occurs when you assign a short to an int.
Note to Sklivvz:
I wanted confirmation that my suspicion of the looseness of Jesse Liberty's (otherwise usually lucid and clear) language was correct. I thought that Jesse Liberty was being a little loose with his language. I understand that casting is routed in object hierarchy--i.e., you can't cast from an integer to a string but you could cast from custom exception derived from System.Exception to a System.Exception.
It's interesting, though, that when you do try to cast from an int to a string the compiler tells you that it couldn't "convert" the value. Maybe Jesse is more correct than I thought! | The simple answer is: it depends.
For value types, casting will involve genuinely converting it to a different type. For instance:
```
float f = 1.5f;
int i = (int) f; // Conversion
```
When the casting expression unboxes, the result (assuming it works) is *usually* just a copy of what was in the box, with the same type. There are exceptions, however - you can unbox from a boxed int to an enum (with an underlying type of int) and vice versa; likewise you can unbox from a boxed int to a Nullable<int>.
When the casting expression is from one reference type to another and no user-defined conversion is involved, there's no conversion as far as the object itself is concerned - only the type of the *reference* "changes" - and that's really only the way that the value is regarded, rather than the reference itself (which will be the same bits as before). For example:
```
object o = "hello";
string x = (string) o; // No data is "converted"; x and o refer to the same object
```
When user-defined conversions get involved, this *usually* entails returning a different object/value. For example, you could define a conversion to string for your own type - and
this would certainly not be the same data as your own object. (It might be an existing string referred to from your object already, of course.) In my experience user-defined conversions usually exist between value types rather than reference types, so this is rarely an issue.
All of these count as conversions in terms of the specification - but they don't all count as converting an *object* into an *object* of a different type. I suspect this is a case of Jesse Liberty being loose with terminology - I've noticed that in Programming C# 3.0, which I've just been reading.
Does that cover everything? |
144,046 | <p>I am trying to find a better way to integrate IRB with my normal ruby devleopment. Currently I rarely use IRB with my code. I only use it to verify syntax or to try something small. </p>
<p>I know I can load my own code into ruby as a</p>
<pre><code>require 'mycode'
</code></pre>
<p>but this usually doesn't mesh with my programming style. Sometimes the variables I want to examine are out of scope or inside of a loop. Is there an easy way to fire up my script and freeze at a certain point inside of IRB? I guess I'm looking for an easier way to debug my ruby code without breaking my F5(compile) key. </p>
<p>Maybe a more experienced ruby developer can share with me a more streamlined method of development.</p>
| [
{
"answer_id": 144074,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 0,
"selected": false,
"text": "<p>I just use rdebug to debug any of my ruby or RoR code. </p>\n"
},
{
"answer_id": 144080,
"author": "Cameron B... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22423/"
] | I am trying to find a better way to integrate IRB with my normal ruby devleopment. Currently I rarely use IRB with my code. I only use it to verify syntax or to try something small.
I know I can load my own code into ruby as a
```
require 'mycode'
```
but this usually doesn't mesh with my programming style. Sometimes the variables I want to examine are out of scope or inside of a loop. Is there an easy way to fire up my script and freeze at a certain point inside of IRB? I guess I'm looking for an easier way to debug my ruby code without breaking my F5(compile) key.
Maybe a more experienced ruby developer can share with me a more streamlined method of development. | Install the ruby-debug gem. Of course, require it inside your app (only in development/test mode). Now you can write 'debugger' where you want to stop execution.
Once your app stop at your breakpoint, you can type 'help' to know about all commands. One of them is 'irb'. It starts an IRB session in which you have access to all methods in your current context.
I personally mostly use p (print), eval, v i (instance vars) and v l (local vars). Of course, n for next and c for continue.
The command to step out of a given block/method never worked for me though. I never investigated why :-) |
144,058 | <p>I just installed Ganymede and am exploring an old project in it. All of my JSPs are giving me weird validation errors. I'm seeing stuff like - </p>
<pre><code>Syntax error on token "}", delete this token
Syntax error on token "catch", Identifier expected
Syntax error, insert "Finally" to complete TryStatement
</code></pre>
<p>I'm doing best practice stuff here, no scriplets or anything, so I think that Eclipse is incorrectly applying a Java class validator to my JSPs. Any idea on how to stop that from happening?</p>
<p>Under Options/Editors/File Associations I have the following for JSPs:</p>
<pre><code>JSP Editor (default)
Web Page Editor
Text Editor
CSS JSP Editor
</code></pre>
<p>Am I missing something?</p>
<p>Also I think this is correct, but just in case it's not, here is my page directive - </p>
<pre><code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
</code></pre>
| [
{
"answer_id": 144115,
"author": "Jorn",
"author_id": 8681,
"author_profile": "https://Stackoverflow.com/users/8681",
"pm_score": 2,
"selected": false,
"text": "<p>Under preferences -> editors -> file associations, you can see which editor(s) are associated with .jsp files. Perhaps it go... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543/"
] | I just installed Ganymede and am exploring an old project in it. All of my JSPs are giving me weird validation errors. I'm seeing stuff like -
```
Syntax error on token "}", delete this token
Syntax error on token "catch", Identifier expected
Syntax error, insert "Finally" to complete TryStatement
```
I'm doing best practice stuff here, no scriplets or anything, so I think that Eclipse is incorrectly applying a Java class validator to my JSPs. Any idea on how to stop that from happening?
Under Options/Editors/File Associations I have the following for JSPs:
```
JSP Editor (default)
Web Page Editor
Text Editor
CSS JSP Editor
```
Am I missing something?
Also I think this is correct, but just in case it's not, here is my page directive -
```
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
``` | I have just downloaded Ganymede 3.4.2 and added WTP 3.0.4 to it and this error has gone for me. |
144,088 | <p>I'm playing with ASP.NET MVC for the last few days and was able to build a small site. Everything works great. </p>
<p>Now, I need to pass the page's META tags (title, description, keywords, etc.) via the ViewData. (i'm using a master page).</p>
<p>How you're dealing with this? Thank you in advance.</p>
| [
{
"answer_id": 144127,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 5,
"selected": true,
"text": "<p>Here is how I am currently doing it...</p>\n\n<p>In the masterpage, I have a content place holder with a default title, descri... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19610/"
] | I'm playing with ASP.NET MVC for the last few days and was able to build a small site. Everything works great.
Now, I need to pass the page's META tags (title, description, keywords, etc.) via the ViewData. (i'm using a master page).
How you're dealing with this? Thank you in advance. | Here is how I am currently doing it...
In the masterpage, I have a content place holder with a default title, description and keywords:
```
<head>
<asp:ContentPlaceHolder ID="cphHead" runat="server">
<title>Default Title</title>
<meta name="description" content="Default Description" />
<meta name="keywords" content="Default Keywords" />
</asp:ContentPlaceHolder>
</head>
```
And then in the page, you can override all this content:
```
<asp:Content ID="headContent" ContentPlaceHolderID="cphHead" runat="server">
<title>Page Specific Title</title>
<meta name="description" content="Page Specific Description" />
<meta name="keywords" content="Page Specific Keywords" />
</asp:Content>
```
This should give you an idea on how to set it up. Now you can put this information in your ViewData (ViewData["PageTitle"]) or include it in your model (ViewData.Model.MetaDescription - would make sense for blog posts, etc) and make it data driven. |
144,109 | <p>I'm just wondering what the optimal solution is here.</p>
<p>Say I have a normalized database. The primary key of the whole system is a varchar. What I'm wondering is should I relate this varchar to an int for normalization or leave it? It's simpler to leave as a varchar, but it might be more optimal </p>
<p>For instance I can have</p>
<pre><code>People
======================
name varchar(10)
DoB DateTime
Height int
Phone_Number
======================
name varchar(10)
number varchar(15)
</code></pre>
<p>Or I could have</p>
<pre><code>People
======================
id int Identity
name varchar(10)
DoB DateTime
Height int
Phone_Number
======================
id int
number varchar(15)
</code></pre>
<p>Add several other one-to-many relationships of course. </p>
<p>What do you all think? Which is better and why?</p>
| [
{
"answer_id": 144148,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 4,
"selected": true,
"text": "<p>Can you really use names as primary keys? Isn't there a high risk of several people with the same name?</p>\n\n<p>If ... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7870/"
] | I'm just wondering what the optimal solution is here.
Say I have a normalized database. The primary key of the whole system is a varchar. What I'm wondering is should I relate this varchar to an int for normalization or leave it? It's simpler to leave as a varchar, but it might be more optimal
For instance I can have
```
People
======================
name varchar(10)
DoB DateTime
Height int
Phone_Number
======================
name varchar(10)
number varchar(15)
```
Or I could have
```
People
======================
id int Identity
name varchar(10)
DoB DateTime
Height int
Phone_Number
======================
id int
number varchar(15)
```
Add several other one-to-many relationships of course.
What do you all think? Which is better and why? | Can you really use names as primary keys? Isn't there a high risk of several people with the same name?
If you really are so lucky that your name attribute can be used as primary key, then - by all means - use that. Often, though, you will have to make something up, like a customer\_id, etc.
And finally: "NAME" is a reserved word in at least one DBMS, so consider using something else, e.g. fullname. |
144,118 | <p>While trying to generate classes from a xsd, i got this error:</p>
<pre><code>java.lang.IllegalArgumentException: Illegal class inheritance loop. Outer class OrderPropertyList may not subclass from inner class: OrderPropertyList
</code></pre>
<p>My xsd define a element to group a unbounded element like this:</p>
<pre><code> <element minOccurs="0" name="orderPropertyList">
<complexType>
<sequence>
<element maxOccurs="unbounded" name="orderProperty" type="tns:orderProperty" />
</sequence>
</complexType>
</element>
</code></pre>
<p>And my customization binding follows as specified on <a href="http://java.sun.com/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html" rel="nofollow noreferrer">this page</a>, but it doesn´t work.
Here my binding:</p>
<pre><code><jaxb:bindings schemaLocation="../xsd/Schema.xsd" node="/xs:schema">
<jaxb:bindings node="//xs:element[@name='orderPropertyList']">
<jaxb:class name="OrderPropertyList"/>
</jaxb:bindings>
</jaxb:bindings>
</code></pre>
<p>My intention is to generate a individual class for orderPropertyList, not the default behave that is generating a inner class inside the root element of the xsd.</p>
<p>I´ve watched someone with the same intention <a href="http://forums.java.net/jive/thread.jspa?threadID=15633" rel="nofollow noreferrer">here</a> and <a href="http://forums.java.net/jive/message.jspa?messageID=228180" rel="nofollow noreferrer">here</a>, but it doesn´t work properly for me. :(</p>
<p>JAXB version: </p>
<pre><code>Specification-Version: 2.1
Implementation-Version: 2.1.8
</code></pre>
<p>Any help?</p>
| [
{
"answer_id": 144155,
"author": "David M. Karr",
"author_id": 10508,
"author_profile": "https://Stackoverflow.com/users/10508",
"pm_score": 0,
"selected": false,
"text": "<p>I believe this is happening because it's likely that the generated Java class representing the sequence of \"orde... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21370/"
] | While trying to generate classes from a xsd, i got this error:
```
java.lang.IllegalArgumentException: Illegal class inheritance loop. Outer class OrderPropertyList may not subclass from inner class: OrderPropertyList
```
My xsd define a element to group a unbounded element like this:
```
<element minOccurs="0" name="orderPropertyList">
<complexType>
<sequence>
<element maxOccurs="unbounded" name="orderProperty" type="tns:orderProperty" />
</sequence>
</complexType>
</element>
```
And my customization binding follows as specified on [this page](http://java.sun.com/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html), but it doesn´t work.
Here my binding:
```
<jaxb:bindings schemaLocation="../xsd/Schema.xsd" node="/xs:schema">
<jaxb:bindings node="//xs:element[@name='orderPropertyList']">
<jaxb:class name="OrderPropertyList"/>
</jaxb:bindings>
</jaxb:bindings>
```
My intention is to generate a individual class for orderPropertyList, not the default behave that is generating a inner class inside the root element of the xsd.
I´ve watched someone with the same intention [here](http://forums.java.net/jive/thread.jspa?threadID=15633) and [here](http://forums.java.net/jive/message.jspa?messageID=228180), but it doesn´t work properly for me. :(
JAXB version:
```
Specification-Version: 2.1
Implementation-Version: 2.1.8
```
Any help? | I believe what you need to to is set:
```
<jaxb:globalBindings localScoping="toplevel"/>
```
This will generate standalone classes instead of nested classes.
Doing
```
<jaxb:bindings schemaLocation="../xsd/Schema.xsd" node="/xs:schema">
<jaxb:bindings node="//xs:element[@name='orderPropertyList']">
<jaxb:class name="OrderPropertyList"/>
</jaxb:bindings>
</jaxb:bindings>
```
is a redundant binding, since orderPropertyList will map by default to OrderPropertyList. The name of the package includes the outer class name it is nested in by default, so you're not changing that.
Also, if you did want to change the name of the generated class, I think the XPath would actually be:
```
<jaxb:bindings node="//xs:element[@name='orderPropertyList']/xs:complexType">
```
with complexType on the end. I think excluding this was what was causing the error message you got. |
144,147 | <p>I have a sparse array in Jscript, with non-null elements occuring at both negative and positive indices. When I try to use a for in loop, it doesn't traverse the array from the lowest (negative) index to the highest positive index. Instead it returns the array in the order that I added the elements. Enumeration doesn't work either. Is there any method that will allow me to do that?</p>
<p><strong>Example</strong></p>
<pre><code>arrName = new Array();
arrName[-10] = "A";
arrName[20] = "B";
arrName[10] = "C";
</code></pre>
<p>When looping through, it should give me A then C the B.</p>
| [
{
"answer_id": 144182,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 4,
"selected": true,
"text": "<p>Technically, \"A\" isn't in the Array at all since you can't have a negative index. It is just a member of the arrName object.... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a sparse array in Jscript, with non-null elements occuring at both negative and positive indices. When I try to use a for in loop, it doesn't traverse the array from the lowest (negative) index to the highest positive index. Instead it returns the array in the order that I added the elements. Enumeration doesn't work either. Is there any method that will allow me to do that?
**Example**
```
arrName = new Array();
arrName[-10] = "A";
arrName[20] = "B";
arrName[10] = "C";
```
When looping through, it should give me A then C the B. | Technically, "A" isn't in the Array at all since you can't have a negative index. It is just a member of the arrName object. If you check the arrName.length you will see that it is 21 (0,1,2,...,20) Why don't you use a plain object instead (as a hashtable). Something like this should work:
```
<script type="text/javascript">
//define and initialize your object/hastable
var obj = {};
obj[20] = 'C';
obj[10] = 'B';
obj[-10] = 'A';
// get the indexes and sort them
var indexes = [];
for(var i in obj){
indexes.push(i);
}
indexes.sort(function(a,b){
return a-b;
});
// write the values to the page in index order (increasing)
for(var i=0,l=indexes.length; i<l; i++){
document.write(obj[indexes[i]] + ' ');
}
// Should print out as "A B C" to the page
</script>
``` |
144,151 | <p>My macro updates a large spreadsheet with numbers, but it runs very slowly as excel is rendering the result as it computes it. How do I stop excel from rendering the output until the macro is complete?</p>
| [
{
"answer_id": 144154,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 0,
"selected": false,
"text": "<p>You can turn off automatic calculation in the options dialog, it sets it so that it only calculates when you pres... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5472/"
] | My macro updates a large spreadsheet with numbers, but it runs very slowly as excel is rendering the result as it computes it. How do I stop excel from rendering the output until the macro is complete? | I use both of the proposed solutions:
```
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
...
...
...
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
``` |
144,167 | <p>I am using Oracle SQL (in SQLDeveloper, so I don't have access to SQLPLUS commands such as COLUMN) to execute a query that looks something like this:</p>
<pre><code>select assigner_staff_id as staff_id, active_flag, assign_date,
complete_date, mod_date
from work where assigner_staff_id = '2096';
</code></pre>
<p>The results it give me look something like this:</p>
<pre>
STAFF_ID ACTIVE_FLAG ASSIGN_DATE COMPLETE_DATE MOD_DATE
---------------------- ----------- ------------------------- ------------------------- -------------------------
2096 F 25-SEP-08 27-SEP-08 27-SEP-08 02.27.30.642959000 PM
2096 F 25-SEP-08 25-SEP-08 25-SEP-08 01.41.02.517321000 AM
2 rows selected
</pre>
<p>This can very easily produce a very wide and unwieldy textual report when I'm trying to paste the results as a nicely formatted quick-n-dirty text block into an e-mail or problem report, etc. What's the best way to get rid of all tha extra white space in the output columns when I'm using just plain-vanilla Oracle SQL? So far all my web searches haven't turned up much, as all the web search results are showing me how to do it using formatting commands like COLUMN in SQLPLUS (which I don't have).</p>
| [
{
"answer_id": 144187,
"author": "Thomas Jones-Low",
"author_id": 23030,
"author_profile": "https://Stackoverflow.com/users/23030",
"pm_score": 3,
"selected": true,
"text": "<p>What are you using to get the results? The output you pasted looks like it's coming from SQL*PLUS. It may be th... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13140/"
] | I am using Oracle SQL (in SQLDeveloper, so I don't have access to SQLPLUS commands such as COLUMN) to execute a query that looks something like this:
```
select assigner_staff_id as staff_id, active_flag, assign_date,
complete_date, mod_date
from work where assigner_staff_id = '2096';
```
The results it give me look something like this:
```
STAFF_ID ACTIVE_FLAG ASSIGN_DATE COMPLETE_DATE MOD_DATE
---------------------- ----------- ------------------------- ------------------------- -------------------------
2096 F 25-SEP-08 27-SEP-08 27-SEP-08 02.27.30.642959000 PM
2096 F 25-SEP-08 25-SEP-08 25-SEP-08 01.41.02.517321000 AM
2 rows selected
```
This can very easily produce a very wide and unwieldy textual report when I'm trying to paste the results as a nicely formatted quick-n-dirty text block into an e-mail or problem report, etc. What's the best way to get rid of all tha extra white space in the output columns when I'm using just plain-vanilla Oracle SQL? So far all my web searches haven't turned up much, as all the web search results are showing me how to do it using formatting commands like COLUMN in SQLPLUS (which I don't have). | What are you using to get the results? The output you pasted looks like it's coming from SQL\*PLUS. It may be that whatever tool you are using to generate the results has some method of modifying the output.
By default Oracle outputs columns based upon the width of the title or the width of the column data which ever is wider.
If you want make columns smaller you will need to either rename them or convert them to text and use substr() to make the defaults smaller.
```
select substr(assigner_staff_id, 8) as staff_id,
active_flag as Flag,
to_char(assign_date, 'DD/MM/YY'),
to_char(complete_date, 'DD/MM/YY'),
mod_date
from work where assigner_staff_id = '2096';
``` |
144,176 | <p>I need to convert a (possibly) null terminated array of ascii bytes to a string in C# and the fastest way I've found to do it is by using my UnsafeAsciiBytesToString method shown below. This method uses the String.String(sbyte*) constructor which contains a warning in it's remarks:</p>
<p>"The value parameter is assumed to point to an array representing a string encoded using the default ANSI code page (that is, the encoding method specified by Encoding.Default).</p>
<p>Note: <strong>* Because the default ANSI code page is system-dependent, the string created by this constructor from identical signed byte arrays may differ on different systems. *</strong> ...</p>
<p><strong>* If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. *</strong>
"</p>
<p>Now, I'm positive that the way the string is encoded will never change... but the default codepage on the system that my app is running on might change. So, is there any reason that I shouldn't run screaming from using String.String(sbyte*) for this purpose?</p>
<pre><code>using System;
using System.Text;
namespace FastAsciiBytesToString
{
static class StringEx
{
public static string AsciiBytesToString(this byte[] buffer, int offset, int maxLength)
{
int maxIndex = offset + maxLength;
for( int i = offset; i < maxIndex; i++ )
{
/// Skip non-nulls.
if( buffer[i] != 0 ) continue;
/// First null we find, return the string.
return Encoding.ASCII.GetString(buffer, offset, i - offset);
}
/// Terminating null not found. Convert the entire section from offset to maxLength.
return Encoding.ASCII.GetString(buffer, offset, maxLength);
}
public static string UnsafeAsciiBytesToString(this byte[] buffer, int offset)
{
string result = null;
unsafe
{
fixed( byte* pAscii = &buffer[offset] )
{
result = new String((sbyte*)pAscii);
}
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
byte[] asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c', 0, 0, 0 };
string result = asciiBytes.AsciiBytesToString(3, 6);
Console.WriteLine("AsciiBytesToString Result: \"{0}\"", result);
result = asciiBytes.UnsafeAsciiBytesToString(3);
Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result);
/// Non-null terminated test.
asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c' };
result = asciiBytes.UnsafeAsciiBytesToString(3);
Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result);
Console.ReadLine();
}
}
}
</code></pre>
| [
{
"answer_id": 144189,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "<p>Any reason not to use the <code>String(sbyte*, int, int)</code> constructor? If you've worked out which portion of the... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16387/"
] | I need to convert a (possibly) null terminated array of ascii bytes to a string in C# and the fastest way I've found to do it is by using my UnsafeAsciiBytesToString method shown below. This method uses the String.String(sbyte\*) constructor which contains a warning in it's remarks:
"The value parameter is assumed to point to an array representing a string encoded using the default ANSI code page (that is, the encoding method specified by Encoding.Default).
Note: **\* Because the default ANSI code page is system-dependent, the string created by this constructor from identical signed byte arrays may differ on different systems. \*** ...
**\* If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. \***
"
Now, I'm positive that the way the string is encoded will never change... but the default codepage on the system that my app is running on might change. So, is there any reason that I shouldn't run screaming from using String.String(sbyte\*) for this purpose?
```
using System;
using System.Text;
namespace FastAsciiBytesToString
{
static class StringEx
{
public static string AsciiBytesToString(this byte[] buffer, int offset, int maxLength)
{
int maxIndex = offset + maxLength;
for( int i = offset; i < maxIndex; i++ )
{
/// Skip non-nulls.
if( buffer[i] != 0 ) continue;
/// First null we find, return the string.
return Encoding.ASCII.GetString(buffer, offset, i - offset);
}
/// Terminating null not found. Convert the entire section from offset to maxLength.
return Encoding.ASCII.GetString(buffer, offset, maxLength);
}
public static string UnsafeAsciiBytesToString(this byte[] buffer, int offset)
{
string result = null;
unsafe
{
fixed( byte* pAscii = &buffer[offset] )
{
result = new String((sbyte*)pAscii);
}
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
byte[] asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c', 0, 0, 0 };
string result = asciiBytes.AsciiBytesToString(3, 6);
Console.WriteLine("AsciiBytesToString Result: \"{0}\"", result);
result = asciiBytes.UnsafeAsciiBytesToString(3);
Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result);
/// Non-null terminated test.
asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c' };
result = asciiBytes.UnsafeAsciiBytesToString(3);
Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result);
Console.ReadLine();
}
}
}
``` | Any reason not to use the `String(sbyte*, int, int)` constructor? If you've worked out which portion of the buffer you need, the rest should be simple:
```
public static string UnsafeAsciiBytesToString(byte[] buffer, int offset, int length)
{
unsafe
{
fixed (byte* pAscii = buffer)
{
return new String((sbyte*)pAscii, offset, length);
}
}
}
```
If you need to look first:
```
public static string UnsafeAsciiBytesToString(byte[] buffer, int offset)
{
int end = offset;
while (end < buffer.Length && buffer[end] != 0)
{
end++;
}
unsafe
{
fixed (byte* pAscii = buffer)
{
return new String((sbyte*)pAscii, offset, end - offset);
}
}
}
```
If this truly is an ASCII string (i.e. all bytes are less than 128) then the codepage problem shouldn't be an issue unless you've got a *particularly* strange default codepage which isn't based on ASCII.
Out of interest, have you actually profiled your application to make sure that this is really the bottleneck? Do you definitely need the absolute fastest conversion, instead of one which is more readable (e.g. using Encoding.GetString for the appropriate encoding)? |
144,218 | <p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
| [
{
"answer_id": 144225,
"author": "Dre",
"author_id": 23033,
"author_profile": "https://Stackoverflow.com/users/23033",
"pm_score": 0,
"selected": false,
"text": "<p>Decimal defaults to 28 places of precision.<br/>\nThe only way to limit the number of digits it returns is by altering the ... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:
```
from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
```
But this doesn't:
```
>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
```
So two questions:
1. Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?
2. Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity. | Changing the decimal working precision to 2 digits is *not* a good idea, unless you absolutely only are going to perform a single operation.
You should always perform calculations at higher precision than the level of significance, and only round the final result. If you perform a long sequence of calculations and round to the number of significant digits at each step, errors will accumulate. The decimal module doesn't know whether any particular operation is one in a long sequence, or the final result, so it assumes that it shouldn't round more than necessary. Ideally it would use infinite precision, but that is too expensive so the Python developers settled for 28 digits.
Once you've arrived at the final result, what you probably want is quantize:
```
>>> (Decimal('1.00') / Decimal('3.00')).quantize(Decimal("0.001"))
Decimal("0.333")
```
You have to keep track of significance manually. If you want automatic significance tracking, you should use interval arithmetic. There are some libraries available for Python, including [pyinterval](http://pyinterval.googlecode.com/) and [mpmath](http://code.google.com/p/mpmath/) (which supports arbitrary precision). It is also straightforward to implement interval arithmetic with the decimal library, since it supports directed rounding.
You may also want to read the [Decimal Arithmetic FAQ: Is the decimal arithmetic ‘significance’ arithmetic?](http://speleotrove.com/decimal/decifaq4.html#signif) |
144,226 | <p>From what I know, the em keyword in CSS means the current size of a font.</p>
<p>So if you put 1.2 em, it means 120% of the font height.</p>
<p>It doesn't seem right though that em is used for setting the width of divs etc like YUI grids does:</p>
<pre><code>margin-right:24.0769em;*margin-right:23.62em;
</code></pre>
<p>Everytime I read about em, I forget what it really represents.</p>
<p>I'm hoping someone can explain it to me so it sticks in my head heeh.</p>
| [
{
"answer_id": 144233,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 2,
"selected": false,
"text": "<p>It does mean the size of the font, but using it for width/height is useful for creating designs that scale with the font-siz... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | From what I know, the em keyword in CSS means the current size of a font.
So if you put 1.2 em, it means 120% of the font height.
It doesn't seem right though that em is used for setting the width of divs etc like YUI grids does:
```
margin-right:24.0769em;*margin-right:23.62em;
```
Everytime I read about em, I forget what it really represents.
I'm hoping someone can explain it to me so it sticks in my head heeh. | Historically it is the width of an "M" in the font. Hence the name!
In CSS2.1 it is [defined](http://www.w3.org/TR/CSS21/syndata.html#em-width) to be the same as the font-size.
In many cases it seems more natural to use em rather than points or pixels, because it is relative to the font size. For example you might define a text-column to have a width of 40em. If you later decide to change the font-size, the column will still keep the same number of letters per line. |
144,246 | <p>I have an application that is causing a lot of headaches. It's a .NET app connecting to SQL Server 2005 via a web service. The program has grid that is filled by a long running stored procedure that is prone to timing out. In the case when it does time out and a SqlException is thrown, there is no execption handling to close the connection.</p>
<p>What are the actual consequences of this condition? I think that the framework or SQL Server probably takes care of it one way or another but am not sure. </p>
<p><strong>Addition</strong>
The program always works well in the morning, but after an hour or so of use it basically stops working. The issue isn't that I don't know how to code the connection properly. I need to know if these symptoms could be casued by the unclosed connections. It is kind of a big deal to change the production code and I would like to know that it is at least possible for this to be the issue.</p>
<p><strong>Conclusion</strong>
I engineered this failure to occur on hundreds of simultaneous connections. Never was I able reproduce the failure condition in the application environment. Marked best practices answer as correct. Thanks everyone.</p>
| [
{
"answer_id": 144247,
"author": "Alex Weinstein",
"author_id": 16668,
"author_profile": "https://Stackoverflow.com/users/16668",
"pm_score": 2,
"selected": false,
"text": "<p>There is a connection limit; if your app crashes frequently and does not close the connections automatically, ne... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22273/"
] | I have an application that is causing a lot of headaches. It's a .NET app connecting to SQL Server 2005 via a web service. The program has grid that is filled by a long running stored procedure that is prone to timing out. In the case when it does time out and a SqlException is thrown, there is no execption handling to close the connection.
What are the actual consequences of this condition? I think that the framework or SQL Server probably takes care of it one way or another but am not sure.
**Addition**
The program always works well in the morning, but after an hour or so of use it basically stops working. The issue isn't that I don't know how to code the connection properly. I need to know if these symptoms could be casued by the unclosed connections. It is kind of a big deal to change the production code and I would like to know that it is at least possible for this to be the issue.
**Conclusion**
I engineered this failure to occur on hundreds of simultaneous connections. Never was I able reproduce the failure condition in the application environment. Marked best practices answer as correct. Thanks everyone. | Since a SqlConnection closes while disposing i usually use this syntax
```
using (SqlConnection conn = new SqlConnection())
{
// SqlCode here
}
``` |
144,250 | <p>I am writing an iPhone application and need to essentially implement something equivalent to the 'eyedropper' tool in photoshop, where you can touch a point on the image and capture the RGB values for the pixel in question to determine and match its color. Getting the UIImage is the easy part, but is there a way to convert the UIImage data into a bitmap representation in which I could extract this information for a given pixel? A working code sample would be most appreciated, and note that I am not concerned with the alpha value.</p>
| [
{
"answer_id": 144928,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 4,
"selected": false,
"text": "<p>You can't access the bitmap data of a UIImage directly.</p>\n\n<p>You need to get the CGImage representation of the UIImage... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17123/"
] | I am writing an iPhone application and need to essentially implement something equivalent to the 'eyedropper' tool in photoshop, where you can touch a point on the image and capture the RGB values for the pixel in question to determine and match its color. Getting the UIImage is the easy part, but is there a way to convert the UIImage data into a bitmap representation in which I could extract this information for a given pixel? A working code sample would be most appreciated, and note that I am not concerned with the alpha value. | A little more detail...
-----------------------
I posted earlier this evening with a consolidation and small addition to what had been said on this page - that can be found at the bottom of this post. I am editing the post at this point, however, to post what I propose is (at least for my requirements, which include modifying pixel data) a better method, as it provides writable data (whereas, as I understand it, the method provided by previous posts and at the bottom of this post provides a read-only reference to data).
Method 1: Writable Pixel Information
1. I defined constants
```
#define RGBA 4
#define RGBA_8_BIT 8
```
2. In my UIImage subclass I declared instance variables:
```
size_t bytesPerRow;
size_t byteCount;
size_t pixelCount;
CGContextRef context;
CGColorSpaceRef colorSpace;
UInt8 *pixelByteData;
// A pointer to an array of RGBA bytes in memory
RPVW_RGBAPixel *pixelData;
```
3. The pixel struct (with alpha in this version)
```
typedef struct RGBAPixel {
byte red;
byte green;
byte blue;
byte alpha;
} RGBAPixel;
```
4. Bitmap function (returns pre-calculated RGBA; divide RGB by A to get unmodified RGB):
```
-(RGBAPixel*) bitmap {
NSLog( @"Returning bitmap representation of UIImage." );
// 8 bits each of red, green, blue, and alpha.
[self setBytesPerRow:self.size.width * RGBA];
[self setByteCount:bytesPerRow * self.size.height];
[self setPixelCount:self.size.width * self.size.height];
// Create RGB color space
[self setColorSpace:CGColorSpaceCreateDeviceRGB()];
if (!colorSpace)
{
NSLog(@"Error allocating color space.");
return nil;
}
[self setPixelData:malloc(byteCount)];
if (!pixelData)
{
NSLog(@"Error allocating bitmap memory. Releasing color space.");
CGColorSpaceRelease(colorSpace);
return nil;
}
// Create the bitmap context.
// Pre-multiplied RGBA, 8-bits per component.
// The source image format will be converted to the format specified here by CGBitmapContextCreate.
[self setContext:CGBitmapContextCreate(
(void*)pixelData,
self.size.width,
self.size.height,
RGBA_8_BIT,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast
)];
// Make sure we have our context
if (!context) {
free(pixelData);
NSLog(@"Context not created!");
}
// Draw the image to the bitmap context.
// The memory allocated for the context for rendering will then contain the raw image pixelData in the specified color space.
CGRect rect = { { 0 , 0 }, { self.size.width, self.size.height } };
CGContextDrawImage( context, rect, self.CGImage );
// Now we can get a pointer to the image pixelData associated with the bitmap context.
pixelData = (RGBAPixel*) CGBitmapContextGetData(context);
return pixelData;
}
```
---
Read-Only Data (Previous information) - method 2:
-------------------------------------------------
---
Step 1. I declared a type for byte:
```
typedef unsigned char byte;
```
Step 2. I declared a struct to correspond to a pixel:
```
typedef struct RGBPixel{
byte red;
byte green;
byte blue;
}
RGBPixel;
```
Step 3. I subclassed UIImageView and declared (with corresponding synthesized properties):
```
// Reference to Quartz CGImage for receiver (self)
CFDataRef bitmapData;
// Buffer holding raw pixel data copied from Quartz CGImage held in receiver (self)
UInt8* pixelByteData;
// A pointer to the first pixel element in an array
RGBPixel* pixelData;
```
Step 4. Subclass code I put in a method named bitmap (to return the bitmap pixel data):
```
//Get the bitmap data from the receiver's CGImage (see UIImage docs)
[self setBitmapData: CGDataProviderCopyData(CGImageGetDataProvider([self CGImage]))];
//Create a buffer to store bitmap data (unitialized memory as long as the data)
[self setPixelBitData:malloc(CFDataGetLength(bitmapData))];
//Copy image data into allocated buffer
CFDataGetBytes(bitmapData,CFRangeMake(0,CFDataGetLength(bitmapData)),pixelByteData);
//Cast a pointer to the first element of pixelByteData
//Essentially what we're doing is making a second pointer that divides the byteData's units differently - instead of dividing each unit as 1 byte we will divide each unit as 3 bytes (1 pixel).
pixelData = (RGBPixel*) pixelByteData;
//Now you can access pixels by index: pixelData[ index ]
NSLog(@"Pixel data one red (%i), green (%i), blue (%i).", pixelData[0].red, pixelData[0].green, pixelData[0].blue);
//You can determine the desired index by multiplying row * column.
return pixelData;
```
Step 5. I made an accessor method:
```
-(RGBPixel*)pixelDataForRow:(int)row column:(int)column{
//Return a pointer to the pixel data
return &pixelData[row * column];
}
``` |
144,321 | <p>I'm processing a huge file with (GNU) <code>awk</code>, (other available tools are: Linux shell tools, some old (>5.0) version of Perl, but can't install modules).</p>
<p>My problem: if some field1, field2, field3 contain X, Y, Z I must search for a file in another directory which contains field4, and field5 on one line, and insert some data from the found file to the current output.</p>
<p>E.g.:</p>
<p>Actual file line:</p>
<pre><code>f1 f2 f3 f4 f5
X Y Z A B
</code></pre>
<p>Now I need to search for another file (in another directory), which contains e.g.</p>
<pre><code>f1 f2 f3 f4
A U B W
</code></pre>
<p>And write to STDOUT <code>$0</code> from the original file, and <code>f2</code> and <code>f3</code> from the found file, then process the next line of the original file.</p>
<p>Is it possible to do it with <code>awk</code>?</p>
| [
{
"answer_id": 144406,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to work for some test files I set up matching your examples. Involving perl in this manner (interpose... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11621/"
] | I'm processing a huge file with (GNU) `awk`, (other available tools are: Linux shell tools, some old (>5.0) version of Perl, but can't install modules).
My problem: if some field1, field2, field3 contain X, Y, Z I must search for a file in another directory which contains field4, and field5 on one line, and insert some data from the found file to the current output.
E.g.:
Actual file line:
```
f1 f2 f3 f4 f5
X Y Z A B
```
Now I need to search for another file (in another directory), which contains e.g.
```
f1 f2 f3 f4
A U B W
```
And write to STDOUT `$0` from the original file, and `f2` and `f3` from the found file, then process the next line of the original file.
Is it possible to do it with `awk`? | Let me start out by saying that your problem description isn't really that helpful. Next time, please just be more specific: You might be missing out on much better solutions.
So from your description, I understand you have two files which contain whitespace-separated data. In the first file, you want to match the first three columns against some search pattern. If found, you want to find all lines in another file which contain the fourth and and fifth column of the matching line in the first file. From those lines, you need to extract the second and third column and then print the first column of the first file and the second and third from the second file. Okay, here goes:
```
#!/usr/bin/env perl -nwa
use strict;
use File::Find 'find';
my @search = qw(X Y Z);
# if you know in advance that the otherfile isn't
# huge, you can cache it in memory as an optimization.
# with any more columns, you want a loop here:
if ($F[0] eq $search[0]
and $F[1] eq $search[1]
and $F[2] eq $search[2])
{
my @files;
find(sub {
return if not -f $_;
# verbatim search for the columns in the file name.
# I'm still not sure what your file-search criteria are, though.
push @files, $File::Find::name if /\Q$F[3]\E/ and /\Q$F[4]\E/;
# alternatively search for the combination:
#push @files, $File::Find::name if /\Q$F[3]\E.*\Q$F[4]\E/;
# or search *all* files in the search path?
#push @files, $File::Find::name;
}, '/search/path'
)
foreach my $file (@files) {
open my $fh, '<', $file or die "Can't open file '$file': $!";
while (defined($_ = <$fh>)) {
chomp;
# order of fields doesn't matter per your requirement.
my @cols = split ' ', $_;
my %seen = map {($_=>1)} @cols;
if ($seen{$F[3]} and $seen{$F[4]}) {
print join(' ', $F[0], @cols[1,2]), "\n";
}
}
close $fh;
}
} # end if matching line
```
Unlike another poster's solution which contains lots of system calls, this doesn't fall back to the shell at all and thus should be plenty fast. |
144,339 | <p>A couple of days ago, I read a blog entry (<a href="http://ayende.com/Blog/archive/2008/09/08/Implementing-generic-natural-language-DSL.aspx" rel="noreferrer">http://ayende.com/Blog/archive/2008/09/08/Implementing-generic-natural-language-DSL.aspx</a>) where the author discuss the idea of a generic natural language DSL parser using .NET.</p>
<p>The brilliant part of his idea, in my opinion, is that the text is parsed and matched against classes using the same name as the sentences. </p>
<p>Taking as an example, the following lines:</p>
<pre>
Create user user1 with email test@email.com and password test
Log user1 in
Take user1 to category t-shirts
Make user1 add item Flower T-Shirt to cart
Take user1 to checkout
</pre>
<p>Would get converted using a collection of "known" objects, that takes the result of parsing. Some example objects would be (using Java for my example):</p>
<pre><code>public class CreateUser {
private final String user;
private String email;
private String password;
public CreateUser(String user) {
this.user = user;
}
public void withEmail(String email) {
this.email = email;
}
public String andPassword(String password) {
this.password = password;
}
}
</code></pre>
<p>So, when processing the first sentence, CreateUser class would be a match (obviously because it's a concatenation of "create user") and, since it takes a parameter on the constructor, the parser would take "user1" as being the user parameter. </p>
<p>After that, the parser would identify that the next part, "with email" also matches a method name, and since that method takes a parameter, it would parse "test@email.com" as being the email parameter. </p>
<p>I think you get the idea by now, right? One quite clear application of that, at least for me, would be to allow application testers create "testing scripts" in natural language and then parse the sentences into classes that uses JUnit to check for app behaviors.</p>
<p>I'd like to hear ideas, tips and opinions on tools or resource that could code such parser using Java. Better yet if we could avoid using complex lexers, or frameworks like ANTLR, which I think maybe would be using a hammer to kill a fly.</p>
<p>More than that, if anyone is up to start an open source project for that, I would definitely be interested.</p>
| [
{
"answer_id": 144374,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 6,
"selected": true,
"text": "<p>Considering the complexity of lexing and parsing, I don't know if I'd want to code all that by hand. <strong><a href=... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14540/"
] | A couple of days ago, I read a blog entry (<http://ayende.com/Blog/archive/2008/09/08/Implementing-generic-natural-language-DSL.aspx>) where the author discuss the idea of a generic natural language DSL parser using .NET.
The brilliant part of his idea, in my opinion, is that the text is parsed and matched against classes using the same name as the sentences.
Taking as an example, the following lines:
```
Create user user1 with email test@email.com and password test
Log user1 in
Take user1 to category t-shirts
Make user1 add item Flower T-Shirt to cart
Take user1 to checkout
```
Would get converted using a collection of "known" objects, that takes the result of parsing. Some example objects would be (using Java for my example):
```
public class CreateUser {
private final String user;
private String email;
private String password;
public CreateUser(String user) {
this.user = user;
}
public void withEmail(String email) {
this.email = email;
}
public String andPassword(String password) {
this.password = password;
}
}
```
So, when processing the first sentence, CreateUser class would be a match (obviously because it's a concatenation of "create user") and, since it takes a parameter on the constructor, the parser would take "user1" as being the user parameter.
After that, the parser would identify that the next part, "with email" also matches a method name, and since that method takes a parameter, it would parse "test@email.com" as being the email parameter.
I think you get the idea by now, right? One quite clear application of that, at least for me, would be to allow application testers create "testing scripts" in natural language and then parse the sentences into classes that uses JUnit to check for app behaviors.
I'd like to hear ideas, tips and opinions on tools or resource that could code such parser using Java. Better yet if we could avoid using complex lexers, or frameworks like ANTLR, which I think maybe would be using a hammer to kill a fly.
More than that, if anyone is up to start an open source project for that, I would definitely be interested. | Considering the complexity of lexing and parsing, I don't know if I'd want to code all that by hand. **[ANTLR](http://www.antlr.org/) isn't that hard to pickup and I think it is worthing looking into based on your problem.** If you use a parse grammar to build and abstract syntax tree from the input, its pretty easy to then process that AST with a tree grammar. The tree grammar could easily handle executing the process you described.
You'll find ANTLR in many places including Eclipse, Groovy, and Grails for a start. [The Definitive ANTLR Reference](https://rads.stackoverflow.com/amzn/click/com/0978739256) even makes it fairly straightforward to get up to speed on the basic fairly quickly.
I had a project that had to handle some user generated query text earlier this year. I started down a path to manually process it, but it quickly became overwhelming. I took a couple days to get up the speed on ANTLR and had an initial version of my grammar and processor running in a few days. Subsequent changes and adjustments to the requirements would have killed any custom version, but required relatively little effort to adjust once I had the ANTLR grammars up and running.
Good luck! |
144,375 | <p>I want a nice 2 column layout using CSS float's.</p>
<p>Column#1 160 px
Column#2 100% (i.e. the rest of the space).</p>
<p>I want to place the Col#2's div first, so my layout looks like:</p>
<pre><code><div id="header"></div>
<div id="content">
<div id="col2"></div>
<div id="col1"></div>
</div>
<div id="footer"></div>
</code></pre>
<p>What has to be get this effect?</p>
| [
{
"answer_id": 144381,
"author": "Vijesh VP",
"author_id": 22016,
"author_profile": "https://Stackoverflow.com/users/22016",
"pm_score": 0,
"selected": false,
"text": "<p>You should use the \"float\" CSS property for doing this. Check out for a <a href=\"http://www.456bereastreet.com/lab... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | I want a nice 2 column layout using CSS float's.
Column#1 160 px
Column#2 100% (i.e. the rest of the space).
I want to place the Col#2's div first, so my layout looks like:
```
<div id="header"></div>
<div id="content">
<div id="col2"></div>
<div id="col1"></div>
</div>
<div id="footer"></div>
```
What has to be get this effect? | Neither of the above will work.
```css
div#col2 {
width: 160px;
float: left;
position: relative;
}
div#col1 {
width:100%;
margin-left: 160px;
}
```
That's assuming that Column 2 should appear as a left sidebar, with col 1 as the main content. |
144,380 | <p>I'm writing a game which is taking user input and rendering it on-screen. The engine I'm using for this is entirely unicode-friendly, so I'd like to keep that if at all possible. The problem is that the rendering loop looks like this:</p>
<pre><code>"string".each_byte do |c|
render_this_letter(c)
end
</code></pre>
<p>I don't know a whole lot about i18n, but I know enough to know the above code is only ever going to work for me and people who speak my language. I'd prefer something like:</p>
<pre><code>"unicode string".each_unicode_letter do |u|
render_unicode_letter(u)
end
</code></pre>
<p>Does this exist in the core distribution? I'm somewhat averse to adding additional requirements to the install, but if it's the only way to do it, I'll live.</p>
<p>For extra fun, I have no way of knowing if the string is, in fact, a unicode string.</p>
<p>EDIT: The library I'm using can indeed render entire strings, however I'm letting the user edit what comes up on the fly - if they hit 'backspace', essentially, I need to know how many bytes to chop off the end.</p>
| [
{
"answer_id": 144381,
"author": "Vijesh VP",
"author_id": 22016,
"author_profile": "https://Stackoverflow.com/users/22016",
"pm_score": 0,
"selected": false,
"text": "<p>You should use the \"float\" CSS property for doing this. Check out for a <a href=\"http://www.456bereastreet.com/lab... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2555346/"
] | I'm writing a game which is taking user input and rendering it on-screen. The engine I'm using for this is entirely unicode-friendly, so I'd like to keep that if at all possible. The problem is that the rendering loop looks like this:
```
"string".each_byte do |c|
render_this_letter(c)
end
```
I don't know a whole lot about i18n, but I know enough to know the above code is only ever going to work for me and people who speak my language. I'd prefer something like:
```
"unicode string".each_unicode_letter do |u|
render_unicode_letter(u)
end
```
Does this exist in the core distribution? I'm somewhat averse to adding additional requirements to the install, but if it's the only way to do it, I'll live.
For extra fun, I have no way of knowing if the string is, in fact, a unicode string.
EDIT: The library I'm using can indeed render entire strings, however I'm letting the user edit what comes up on the fly - if they hit 'backspace', essentially, I need to know how many bytes to chop off the end. | Neither of the above will work.
```css
div#col2 {
width: 160px;
float: left;
position: relative;
}
div#col1 {
width:100%;
margin-left: 160px;
}
```
That's assuming that Column 2 should appear as a left sidebar, with col 1 as the main content. |
144,439 | <p>If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path?</p>
<p>I know of <pre>Path.Combine</pre> but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.</p>
<p>e.g:</p>
<pre>
string folder1 = "foo";
string folder2 = "bar";
CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")
</pre>
<p>Any ideas?
Does C# support unlimited args in methods?</p>
| [
{
"answer_id": 144441,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>Does C# support unlimited args in methods?</p>\n</blockquote>\n\n<p>Yes, have a look at the params k... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] | If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path?
I know of
```
Path.Combine
```
but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.
e.g:
```
string folder1 = "foo";
string folder2 = "bar";
CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")
```
Any ideas?
Does C# support unlimited args in methods? | >
> Does C# support unlimited args in methods?
>
>
>
Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested):
```
string CombinePaths(params string[] parts) {
string result = String.Empty;
foreach (string s in parts) {
result = Path.Combine(result, s);
}
return result;
}
``` |
144,474 | <p>I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java:</p>
<pre>
Array (
["col_name_1"] => Array (
1 => ["col_value_1"],
2 => ["col_value_2"],
... ,
n => ["col_value_n"]
),
["col_name_n"] => Array (
1 => ["col_value_1"],
2 => ["col_value_2"],
... ,
n => ["col_value_n"]
)
)
</pre>
<p>Is there a clean way (i.e. no dirty code) to save this thing in Java? Note; I would like to use Strings as array indexes (in the first dimension) and I don't know the definite size of the arrays.. </p>
| [
{
"answer_id": 144485,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": false,
"text": "<p>You want a <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html\" rel=\"nofollow noreferrer\">Map</a>, wh... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6618/"
] | I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java:
```
Array (
["col_name_1"] => Array (
1 => ["col_value_1"],
2 => ["col_value_2"],
... ,
n => ["col_value_n"]
),
["col_name_n"] => Array (
1 => ["col_value_1"],
2 => ["col_value_2"],
... ,
n => ["col_value_n"]
)
)
```
Is there a clean way (i.e. no dirty code) to save this thing in Java? Note; I would like to use Strings as array indexes (in the first dimension) and I don't know the definite size of the arrays.. | You can use a Map and a List (these both are interfaces implemented in more than one way for you to choose the most adequate in your case).
For more information check the tutorials for [Map](http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html) and [List](http://java.sun.com/docs/books/tutorial/collections/interfaces/list.html) and maybe you should start with the [Collections](http://java.sun.com/docs/books/tutorial/collections/) tutorial.
An example:
```
import java.util.*;
public class Foo {
public static void main(String[] args) {
Map<String, List<String>> m = new HashMap<String, List<String>>();
List<String> l = new LinkedList<String>();
l.add("col_value_1");
l.add("col_value_2");
//and so on
m.put("col_name_1",l); //repeat for the rest of the colnames
//then, to get it you do
List<String> rl = m.get("col_name_1");
}
}
``` |
144,503 | <p>I initially designed my system following the s# architecture example <a href="http://wwww.codeproject.com/KB/architecture/NHibernateBestPractices.aspx" rel="nofollow noreferrer">outlined in this codeproject article</a> (Unfortunately, I am not using NHibernate). The basic idea is that for each domain object that would need to communicate with the persistence layer you would have a corresponding Data Access Object in a different library. Each Data Access Object implements an interface and when a domain object needs access to a data access method it always codes against an interface and never against the DAOs themselves.</p>
<p>At the time, and still, I thought this design very flexible. However, as the amount of objects in my domain model has grown I am finding myself questioning if there isn't an organizational problem here. For example, almost every object in the domain ends up with a corresponding Data Access Object and Data Access Object interface. Not only that, but each one of these is in a different place which is more difficult to maintain if I want to do something simple like shift around some namespaces.</p>
<p>Interestingly enough, many of these DAOs (and their corresponding interfaces) are very simple creatures - the most common has only a single GetById() method. I end up with a whole bunch of objects such as</p>
<pre><code>public interface ICustomerDao {
Customer GetById(int id);
}
public interface IProductDao {
Product GetById(int id);
}
public interface IAutomaticWeaselDao {
AutomaticWeasel GetById(int id);
}
</code></pre>
<p>Where their implementors are usually very trivial too. This has me wondering if it wouldn't be simpler to go in a different direction, maybe switching my strategy by having a single object for simple data access tasks, and reserving the creation of dedicated Data Access Objects for those that need something a little more complicated.</p>
<pre><code>public interface SimpleObjectRepository {
Customer GetCustomerById(int id);
Product GetProductById(int id);
AutomaticWeasel GetAutomaticWeaselById(int id);
Transaction GetTransactioinById(int id);
}
public interface TransactionDao {
Transaction[] GetAllCurrentlyOngoingTransactionsInitiatedByASweatyGuyNamedCarl();
}
</code></pre>
<p>Does anyone has any experience with an architecture like this? Overall I am very happy with the set-up as it is now my only concern being management of all these little files. I am still wondering however what other approaches toward structuring the Data Access Layer exist.</p>
| [
{
"answer_id": 144538,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 1,
"selected": false,
"text": "<p>I'm also using the <a href=\"http://martinfowler.com/eaaCatalog/repository.html\" rel=\"nofollow noreferrer\"... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | I initially designed my system following the s# architecture example [outlined in this codeproject article](http://wwww.codeproject.com/KB/architecture/NHibernateBestPractices.aspx) (Unfortunately, I am not using NHibernate). The basic idea is that for each domain object that would need to communicate with the persistence layer you would have a corresponding Data Access Object in a different library. Each Data Access Object implements an interface and when a domain object needs access to a data access method it always codes against an interface and never against the DAOs themselves.
At the time, and still, I thought this design very flexible. However, as the amount of objects in my domain model has grown I am finding myself questioning if there isn't an organizational problem here. For example, almost every object in the domain ends up with a corresponding Data Access Object and Data Access Object interface. Not only that, but each one of these is in a different place which is more difficult to maintain if I want to do something simple like shift around some namespaces.
Interestingly enough, many of these DAOs (and their corresponding interfaces) are very simple creatures - the most common has only a single GetById() method. I end up with a whole bunch of objects such as
```
public interface ICustomerDao {
Customer GetById(int id);
}
public interface IProductDao {
Product GetById(int id);
}
public interface IAutomaticWeaselDao {
AutomaticWeasel GetById(int id);
}
```
Where their implementors are usually very trivial too. This has me wondering if it wouldn't be simpler to go in a different direction, maybe switching my strategy by having a single object for simple data access tasks, and reserving the creation of dedicated Data Access Objects for those that need something a little more complicated.
```
public interface SimpleObjectRepository {
Customer GetCustomerById(int id);
Product GetProductById(int id);
AutomaticWeasel GetAutomaticWeaselById(int id);
Transaction GetTransactioinById(int id);
}
public interface TransactionDao {
Transaction[] GetAllCurrentlyOngoingTransactionsInitiatedByASweatyGuyNamedCarl();
}
```
Does anyone has any experience with an architecture like this? Overall I am very happy with the set-up as it is now my only concern being management of all these little files. I am still wondering however what other approaches toward structuring the Data Access Layer exist. | I recommend against the simple approach other than in simple systems, usually I think your better creating a custom repository for each aggregate and encapsulating as much suitable logic as you can within it.
So my approach would to have a repository for each aggregate that needs it, such as CustomerRepository. This would have an Add (save) method and, if suitable for that aggregate, a Remove (delete) method. It would also have any other custom methods that apply including queries (GetActive) and maybe some of those queries could accept specifications.
This sounds like a lot of effort but other than the custom queries most of the code is, at least if you are using a modern ORM, very simple to implement so I use inheritance (ReadWriteRepositoryBase where T: IAggregateRoot) and/or composition (calling out to a RepositoryHelper class). The base class might have methods that apply in all cases, such as GetById.
Hope this helps. |
144,516 | <p>I'm currently writing an interface to allow applications to send exception data to a central repository for support purposes. I'm at a quandary about how to pass extra contextual data:</p>
<pre><code>public interface IExceptionNotifier
{
void Notify(Exception ex, NameValueCollection context); //this
void Notify(Exception ex, IDictionary<string, string> context); //or this
}
</code></pre>
<p>I've often found myself is a similar position when creating lookups. Ignoring whether or not the exception notifier concept is good, is it be best to use an <code>IDictionary<string, string></code> or <code>NameValueCollection</code>? Why would you pick one over the other?</p>
| [
{
"answer_id": 144518,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 2,
"selected": true,
"text": "<p>If the context is a throw-away value and (here comes the important part) will not be serialized, e.g. for sending th... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3642/"
] | I'm currently writing an interface to allow applications to send exception data to a central repository for support purposes. I'm at a quandary about how to pass extra contextual data:
```
public interface IExceptionNotifier
{
void Notify(Exception ex, NameValueCollection context); //this
void Notify(Exception ex, IDictionary<string, string> context); //or this
}
```
I've often found myself is a similar position when creating lookups. Ignoring whether or not the exception notifier concept is good, is it be best to use an `IDictionary<string, string>` or `NameValueCollection`? Why would you pick one over the other? | If the context is a throw-away value and (here comes the important part) will not be serialized, e.g. for sending the data to another system, I'd go with the IDictionary because it makes using your interface more flexible.
If, on the other hand, the context is kept all the time or the context will be serialized, use NameValueCollection because then you are under control of what you'll actually get from your caller.
Edit: mausch is right in that you should use a generic approach, but I still wouldn't use an interface if you want to serialize the data. |
144,550 | <p><strong>Problem:</strong></p>
<p>Ajax suggest-search on [<em>n</em>] ingredients in recipes. That is: match recipes against multiple ingredients.</p>
<p>For instance: <code>SELECT Recipes using "flower", "salt"</code> would produce: <code>"Pizza", "Bread", "Saltwater"</code> and so forth.</p>
<p><strong>Tables:</strong></p>
<pre><code>Ingredients [
IngredientsID INT [PK],
IngredientsName VARCHAR
]
Recipes [
RecipesID INT [PK],
RecipesName VARCHAR
]
IngredientsRecipes [
IngredientsRecipesID INT [PK],
IngredientsID INT,
RecipesID INT
]
</code></pre>
<p><strong>Query:</strong></p>
<pre><code>SELECT
Recipes.RecipesID,
Recipes.RecipesName,
Ingredients.IngredientsID,
Ingredients.IngredientsName
FROM
IngredientsRecipes
INNER JOIN Ingredients
ON IngredientsRecipes.IngredientsID = Ingredients.IngredientsID
INNER JOIN Recipes
ON IngredientsRecipes.RecipesID = Recipes.RecipesID
WHERE
Ingredients.IngredientsName IN ('salt', 'water', 'flower')
</code></pre>
<p>I am currently constructing my query using ASP.NET C# because of the dynamic nature of the <code>WHERE</code> clause.</p>
<p>I bites that I have to construct the query in my code-layer instead of using a stored procedure/pure SQL, which in theory should be much faster.</p>
<p>Have you guys got any thoughts on how I would move all of the logic from my code-layer to pure SQL, or at least how I can optimize the performance of what I'm doing?</p>
<p>I am thinking along the lines of temporary tables:</p>
<p><strong>Step one</strong>: <code>SELECT IngredientsID FROM Ingredients</code> and <code>INSERT INTO temp-table</code></p>
<p><strong>Step two</strong>: <code>SELECT RecipesName FROM Recipes</code> joined with <code>IngredientsRecipes</code> joined with <code>temp-table.IngredientsID</code></p>
| [
{
"answer_id": 144589,
"author": "alexmac",
"author_id": 23066,
"author_profile": "https://Stackoverflow.com/users/23066",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on how you are processing the input ingredients I think this current method has some sql injection risks. </p... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] | **Problem:**
Ajax suggest-search on [*n*] ingredients in recipes. That is: match recipes against multiple ingredients.
For instance: `SELECT Recipes using "flower", "salt"` would produce: `"Pizza", "Bread", "Saltwater"` and so forth.
**Tables:**
```
Ingredients [
IngredientsID INT [PK],
IngredientsName VARCHAR
]
Recipes [
RecipesID INT [PK],
RecipesName VARCHAR
]
IngredientsRecipes [
IngredientsRecipesID INT [PK],
IngredientsID INT,
RecipesID INT
]
```
**Query:**
```
SELECT
Recipes.RecipesID,
Recipes.RecipesName,
Ingredients.IngredientsID,
Ingredients.IngredientsName
FROM
IngredientsRecipes
INNER JOIN Ingredients
ON IngredientsRecipes.IngredientsID = Ingredients.IngredientsID
INNER JOIN Recipes
ON IngredientsRecipes.RecipesID = Recipes.RecipesID
WHERE
Ingredients.IngredientsName IN ('salt', 'water', 'flower')
```
I am currently constructing my query using ASP.NET C# because of the dynamic nature of the `WHERE` clause.
I bites that I have to construct the query in my code-layer instead of using a stored procedure/pure SQL, which in theory should be much faster.
Have you guys got any thoughts on how I would move all of the logic from my code-layer to pure SQL, or at least how I can optimize the performance of what I'm doing?
I am thinking along the lines of temporary tables:
**Step one**: `SELECT IngredientsID FROM Ingredients` and `INSERT INTO temp-table`
**Step two**: `SELECT RecipesName FROM Recipes` joined with `IngredientsRecipes` joined with `temp-table.IngredientsID` | You have two options. If you're using SQL Server 2008 (or Oracle) you can pass in a [table value parameter](http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters).
If you're using SQL Server 2005, you can use [XML to simulate this capability](http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx)
If you're using something earlier than 2005, you need to concatenate the ids in a single string and create a UDF to parse them. |
144,570 | <p>I thought that there was some way in .net 3.0 to give an array list a type so that it didnt just return Object's but I'm having trouble doing so. Is it possible? If so, how?</p>
| [
{
"answer_id": 144574,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 2,
"selected": false,
"text": "<p>You're probably looking for List<code><T></code>, available since .NET 2.0, or for any other of the generic t... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | I thought that there was some way in .net 3.0 to give an array list a type so that it didnt just return Object's but I'm having trouble doing so. Is it possible? If so, how? | `List<T>` was introduced with generics in .NET 2.0:
```
using System.Collections.Generic;
var list = new List<int>();
list.Add(1);
list.Add("string"); //compile-time error!
int i = list[0];
``` |
144,630 | <p>I am working on an ASP.NET MVC web app that allows people to publish content, but other than publish the content to a remote server, I want to allow people to use their domain name directly. For example, the user "Tom" can have his domain name TomSite.com point to <a href="http://www.mywebapp.com/user/tom" rel="nofollow noreferrer">http://www.mywebapp.com/user/tom</a>, but the sub path will also be mapped. For example, TomSite.com/path will be mapped to www.mywebapp.com/user/tom/path, and this is transparent to the web visitor. The visitor will never see "mywebapp.com" anywhere on TomSite.com.</p>
<p>I think Smugmug.com provides such service, to allow people to use their own domain name for the photo portfolio. I want to achieve the same result.</p>
<p>How can I do this? Thanks!</p>
| [
{
"answer_id": 144695,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 0,
"selected": false,
"text": "<p>Just make a new record in your webserver setting tomsite.com directly to your mywebapp.com/user/tom/ path ?</p>\n\... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20067/"
] | I am working on an ASP.NET MVC web app that allows people to publish content, but other than publish the content to a remote server, I want to allow people to use their domain name directly. For example, the user "Tom" can have his domain name TomSite.com point to <http://www.mywebapp.com/user/tom>, but the sub path will also be mapped. For example, TomSite.com/path will be mapped to www.mywebapp.com/user/tom/path, and this is transparent to the web visitor. The visitor will never see "mywebapp.com" anywhere on TomSite.com.
I think Smugmug.com provides such service, to allow people to use their own domain name for the photo portfolio. I want to achieve the same result.
How can I do this? Thanks! | This require multiple steps.
First you have to find out how your users will configure their domain to have a CNAME record for you site. You can archieve this in a number of ways where the best is education. Making partnerships with hosting providers requires a great deal of volume.
In IIS this will require you to either add each host name manually (however this could also be archieved through scripting) or have a dedicated IP address only for you site.
There is also a need for the domain to be associated with an account. The user has to add this themselves and you would probably add a check in the interface which confirms the domain is pointed at your server. The code for this would look like (remember to include the System.Net namespace).
```
if (Dns.GetHostEntry("www.user.example.com").HostName == "www.example.com")
{
// www.user.example.com is a CNAME for www.example.com
}
```
In you ASP.NET MVC project you need to implement routes for this particular purpose. Create a custom class inheriting from Route which also takes the domain into account. |
144,639 | <p>By default (using the <code>plain</code> style) BibTeX orders citations alphabetically. </p>
<p>How to order the citations by order of appearance in the document?</p>
| [
{
"answer_id": 144640,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 5,
"selected": false,
"text": "<p>The best I came up with is using the <code>unsrt</code> style, which seems to be a tweaked <code>plain</code> style. i.e.</... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199/"
] | By default (using the `plain` style) BibTeX orders citations alphabetically.
How to order the citations by order of appearance in the document? | There are three good answers to this question.
* Use the `unsrt` bibliography style, if you're happy with its formatting otherwise
* Use the `makebst` [(link)](http://www.ctan.org/tex-archive/macros/latex/contrib/custom-bib/) tool to design your own bibliography style
And my personal recommendation:
* Use the `biblatex` package [(link)](https://ctan.org/pkg/biblatex). It's the most complete and flexible bibliography tool in the LaTeX world.
Using `biblatex`, you'd write something like
```
\documentclass[12pt]{article}
\usepackage[sorting=none]{biblatex}
\bibliography{journals,phd-references} % Where journals.bib and phd-references.bib are BibTeX databases
\begin{document}
\cite{robertson2007}
\cite{earnshaw1842}
\printbibliography
\end{document}
``` |
144,642 | <p>I require a tree / directed acyclic graph implementation something like this:</p>
<pre><code>public class TreeNode<K, V> {
private K key; // 'key' for this node, always present
private V value; // 'value' for this node, doesn't have to be set
private TreeNode<K, V> parent;
private Set<TreeNode<K, V>> children;
}
</code></pre>
<ul>
<li>There is no sorting of any kind. </li>
<li>The <code>TreeNode</code> is just a wrapper around the key and a possible value (nodes don't have to have values set).</li>
<li>I require links to both the parent and the children.</li>
</ul>
<p>Is there anything out there in the standard APIs or Commons etc that will do this for me?</p>
<p>I don't mind writing it myself (and I'm certainly <strong>not</strong> asking you folks to) I just don't want to re-invent the wheel.</p>
| [
{
"answer_id": 144652,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 5,
"selected": true,
"text": "<p>There doesn't seem to be anything of the kind. I asked <a href=\"https://stackoverflow.com/questions/66893/tree-data-structur... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | I require a tree / directed acyclic graph implementation something like this:
```
public class TreeNode<K, V> {
private K key; // 'key' for this node, always present
private V value; // 'value' for this node, doesn't have to be set
private TreeNode<K, V> parent;
private Set<TreeNode<K, V>> children;
}
```
* There is no sorting of any kind.
* The `TreeNode` is just a wrapper around the key and a possible value (nodes don't have to have values set).
* I require links to both the parent and the children.
Is there anything out there in the standard APIs or Commons etc that will do this for me?
I don't mind writing it myself (and I'm certainly **not** asking you folks to) I just don't want to re-invent the wheel. | There doesn't seem to be anything of the kind. I asked [a similar question](https://stackoverflow.com/questions/66893/tree-data-structure-in-c) last week and ended up implementing my own tree. My implementation was very similar to what you're proposing:
```
public class TreeNode<T>
{
private LinkedList<TreeNode<T>> children = new LinkedList<TreeNode<T>>();
public T value { get; set; }
public TreeNode(T value)
{
this.value = value;
}
public LinkedList<TreeNode<T>> GetChildren()
{
return children;
}
}
```
You will have to add a link back to the parent(s). |
144,651 | <p>I've the following rewrite rule in .htaccess:</p>
<pre><code>RewriteRule ^groups/([^/\.]+)/?$ groupdetail.php?gname=$1 [L,NC]
</code></pre>
<p>This takes something like www.example.com/groups/groupname and calls www.example/groupdetail.php?gname=groupname. And it works just fine.</p>
<p>But all the relative links on groupdetail.php use groups/ as the relative path, and I don't want them to. How do I avoid this?</p>
<p>For example, when a user clicks on a link <code><a href="link.php"></code> on groupdetail.php?gname=groupname, he's taken to www.example/groups/link.php. I want to take the user to www.example.com/link.php.</p>
<p>Obviously, I want to URL to the user to look like "www.example.com/groups/groupname" so I don't want to use [R]/redirect.</p>
| [
{
"answer_id": 144676,
"author": "Kevin Hakanson",
"author_id": 22514,
"author_profile": "https://Stackoverflow.com/users/22514",
"pm_score": 1,
"selected": false,
"text": "<p>If you change the rewite rule to do a <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriterul... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've the following rewrite rule in .htaccess:
```
RewriteRule ^groups/([^/\.]+)/?$ groupdetail.php?gname=$1 [L,NC]
```
This takes something like www.example.com/groups/groupname and calls www.example/groupdetail.php?gname=groupname. And it works just fine.
But all the relative links on groupdetail.php use groups/ as the relative path, and I don't want them to. How do I avoid this?
For example, when a user clicks on a link `<a href="link.php">` on groupdetail.php?gname=groupname, he's taken to www.example/groups/link.php. I want to take the user to www.example.com/link.php.
Obviously, I want to URL to the user to look like "www.example.com/groups/groupname" so I don't want to use [R]/redirect. | If like me you had hundreds of relative links in the page, insert a `<base href="">` in the `<head>` with an absolute path (could use relative too). You'll need to also make the path to .js files in the `<head>` absolute because IE and firefox deal with the base href differently. I agree it is an annoying issue. |
144,657 | <p>I have a Java program that uses Hibernate and MySQL to store a lot of tracing data about the use of the Eclipse IDE. This data contains a lot of strings such as method names, directories, perspective name, etc. </p>
<p>For example, an event object (which is then reflected in a record) can specify the source file and the current method, the user name, etc. Obviously, string data can repeat itself. </p>
<p>As long as it's in memory, much of it is internalized so all repeated string instances point to the same object (I make sure of that). However, with @Basic (I use annotations), Hibernate maps it into a VARCHAR(255), which means a lot of wasted space.</p>
<p>If I was coding the SQL myself, I could have replaced the VARCHAR with an index to a manually-managed string lookup table and saved the space (at the cost of extra lookups). </p>
<p>Is there some way to get Hibernate to do this for me? I'm willing to pay the performance hit for the space.</p>
| [
{
"answer_id": 144674,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect you'll need a string holder object and then make sure all these objects refer to that. </p>\n\n<pre><code>class... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23072/"
] | I have a Java program that uses Hibernate and MySQL to store a lot of tracing data about the use of the Eclipse IDE. This data contains a lot of strings such as method names, directories, perspective name, etc.
For example, an event object (which is then reflected in a record) can specify the source file and the current method, the user name, etc. Obviously, string data can repeat itself.
As long as it's in memory, much of it is internalized so all repeated string instances point to the same object (I make sure of that). However, with @Basic (I use annotations), Hibernate maps it into a VARCHAR(255), which means a lot of wasted space.
If I was coding the SQL myself, I could have replaced the VARCHAR with an index to a manually-managed string lookup table and saved the space (at the cost of extra lookups).
Is there some way to get Hibernate to do this for me? I'm willing to pay the performance hit for the space. | Building on sblundy's answer, you could probably get away with something like:
```
class Foo {
// client code uses this to get the value... ignored by Hibernate
@Transient
public String getString() {
return getStringHolder().getString();
}
public StringHolder getStringHolder() {...}
}
```
At least then the client code wouldn't necessarily have to be aware of the change. I don't know if it'd be worth the trouble, though. |
144,669 | <p>I've removed a checked in file from the CVS branch, i.e.:</p>
<pre><code>cvs remove -f file.txt
cvs commit
</code></pre>
<p>How do I restore the file?</p>
| [
{
"answer_id": 144672,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 6,
"selected": true,
"text": "<p>I believe that:</p>\n\n<pre><code>cvs add file.txt\ncvs commit file.txt\n</code></pre>\n\n<p>... will resurrect it... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4704/"
] | I've removed a checked in file from the CVS branch, i.e.:
```
cvs remove -f file.txt
cvs commit
```
How do I restore the file? | I believe that:
```
cvs add file.txt
cvs commit file.txt
```
... will resurrect it from the attic. |
144,701 | <p>I frequently start with a simple console application to try out an idea, then create a new GUI based project and copy the code in. Is there a better way? Can I convert my existing console application easily?</p>
| [
{
"answer_id": 144720,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 7,
"selected": true,
"text": "<p>Just add a new Winform, add the following code to your <code>Main</code>:</p>\n\n<pre><code> Application.EnableVisu... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
] | I frequently start with a simple console application to try out an idea, then create a new GUI based project and copy the code in. Is there a better way? Can I convert my existing console application easily? | Just add a new Winform, add the following code to your `Main`:
```
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
```
Also, be sure the `[STAThread]` attribute is declared above your `Main` function to indicate the COM threading model your Windows application will use (more about STAThread [here](https://www.youtube.com/watch?v=S0jPzb9kk3o)).
Then right click your project and select properties and change the "Output type" to Windows application and you're done.
**EDIT :**
In VS2008 the property to change is Application type
 |
144,713 | <p>I have an XML document with un-namespaced elements, and I want to use XSLT to add namespaces to them. Most elements will be in namespace A; a few will be in namespace B. How do I do this?</p>
| [
{
"answer_id": 144724,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 1,
"selected": false,
"text": "<p>Here's what I have so far:</p>\n\n<pre><code><xsl:template match=\"*\">\n <xsl:element name=\"{local-nam... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
] | I have an XML document with un-namespaced elements, and I want to use XSLT to add namespaces to them. Most elements will be in namespace A; a few will be in namespace B. How do I do this? | With foo.xml
```
<foo x="1">
<bar y="2">
<baz z="3"/>
</bar>
<a-special-element n="8"/>
</foo>
```
and foo.xsl
```
<xsl:template match="*">
<xsl:element name="{local-name()}" namespace="A" >
<xsl:copy-of select="attribute::*"/>
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="a-special-element">
<B:a-special-element xmlns:B="B">
<xsl:apply-templates match="children()"/>
</B:a-special-element>
</xsl:template>
</xsl:transform>
```
I get
```
<foo xmlns="A" x="1">
<bar y="2">
<baz z="3"/>
</bar>
<B:a-special-element xmlns:B="B"/>
</foo>
```
Is that what you’re looking for? |
144,731 | <p>Are there any commonly used patterns in Javascript for storing the URL's of endpoints that will be requested in an AJAX application?</p>
<p>For example would you create a "Service" class to abstract the URL's away?</p>
| [
{
"answer_id": 144736,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 0,
"selected": false,
"text": "<p>Is your question similar to <a href=\"https://stackoverflow.com/questions/108853/relative-urls-for-javascript-files... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21875/"
] | Are there any commonly used patterns in Javascript for storing the URL's of endpoints that will be requested in an AJAX application?
For example would you create a "Service" class to abstract the URL's away? | I've used something like this (used in Rails):
```
NAMESPACE.categories.baseUri = '/categories';
NAMESPACE.categories.getUri = function(options)
{
options = options || {};
var uri = [NAMESPACE.categories.baseUri];
if(options.id)
{
uri.push(options.id);
}
if(options.action)
{
uri.push(options.action);
}
if(options.format)
{
uri.push('?format=' + options.format);
}
return uri.join('/');
}
``` |
144,761 | <p>I have a problem with a string in C++ which has several words in Spanish. This means that I have a lot of words with accents and tildes. I want to replace them for their not accented counterparts. Example: I want to replace this word: "había" for habia. I tried replace it directly but with replace method of string class but I could not get that to work.</p>
<p>I'm using this code:</p>
<pre><code>for (it= dictionary.begin(); it != dictionary.end(); it++)
{
strMine=(it->first);
found=toReplace.find_first_of(strMine);
while (found!=std::string::npos)
{
strAux=(it->second);
toReplace.erase(found,strMine.length());
toReplace.insert(found,strAux);
found=toReplace.find_first_of(strMine,found+1);
}
}
</code></pre>
<p>Where <code>dictionary</code> is a map like this (with more entries):</p>
<pre><code>dictionary.insert ( std::pair<std::string,std::string>("á","a") );
dictionary.insert ( std::pair<std::string,std::string>("é","e") );
dictionary.insert ( std::pair<std::string,std::string>("í","i") );
dictionary.insert ( std::pair<std::string,std::string>("ó","o") );
dictionary.insert ( std::pair<std::string,std::string>("ú","u") );
dictionary.insert ( std::pair<std::string,std::string>("ñ","n") );
</code></pre>
<p>and <code>toReplace</code> strings is:</p>
<pre><code>std::string toReplace="á-é-í-ó-ú-ñ-á-é-í-ó-ú-ñ";
</code></pre>
<p>I obviously must be missing something. I can't figure it out.
Is there any library I can use?.</p>
<p>Thanks,</p>
| [
{
"answer_id": 144769,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": -1,
"selected": false,
"text": "<p>If you can (if you're running Unix), I suggest using the <a href=\"http://www.gnu.org/software/coreutils/manual/html_nod... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23084/"
] | I have a problem with a string in C++ which has several words in Spanish. This means that I have a lot of words with accents and tildes. I want to replace them for their not accented counterparts. Example: I want to replace this word: "había" for habia. I tried replace it directly but with replace method of string class but I could not get that to work.
I'm using this code:
```
for (it= dictionary.begin(); it != dictionary.end(); it++)
{
strMine=(it->first);
found=toReplace.find_first_of(strMine);
while (found!=std::string::npos)
{
strAux=(it->second);
toReplace.erase(found,strMine.length());
toReplace.insert(found,strAux);
found=toReplace.find_first_of(strMine,found+1);
}
}
```
Where `dictionary` is a map like this (with more entries):
```
dictionary.insert ( std::pair<std::string,std::string>("á","a") );
dictionary.insert ( std::pair<std::string,std::string>("é","e") );
dictionary.insert ( std::pair<std::string,std::string>("í","i") );
dictionary.insert ( std::pair<std::string,std::string>("ó","o") );
dictionary.insert ( std::pair<std::string,std::string>("ú","u") );
dictionary.insert ( std::pair<std::string,std::string>("ñ","n") );
```
and `toReplace` strings is:
```
std::string toReplace="á-é-í-ó-ú-ñ-á-é-í-ó-ú-ñ";
```
I obviously must be missing something. I can't figure it out.
Is there any library I can use?.
Thanks, | First, this is a really bad idea: you’re mangling somebody’s language by removing letters. Although the extra dots in words like “naïve” seem superfluous to people who only speak English, there are literally thousands of writing systems in the world in which such distinctions are very important. Writing software to mutilate someone’s speech puts you squarely on the wrong side of the tension between using computers as means to broaden the realm of human expression vs. tools of oppression.
What is the reason you’re trying to do this? Is something further down the line choking on the accents? Many people would love to help you solve that.
That said, libicu can do this for you. Open the [transform demo](http://www.icu-project.org/icu-bin/translit); copy and paste your Spanish text into the “Input” box; enter
```
NFD; [:M:] remove; NFC
```
as “Compound 1” and click transform.
(With help from slide 9 of [Unicode Transforms in ICU](http://macchiato.com/slides/icu_transforms.pdf). Slides 29-30 show how to use the API.) |
144,774 | <p>I'm writing a program that uses <a href="http://msdn.microsoft.com/en-us/library/dd145102(VS.85).aspx" rel="nofollow noreferrer"><code>SetWindowRgn</code></a> to make transparent holes in a window that belongs to another process. (This is done only when the user explicitly requests it.)</p>
<p>The program has to assume that the target window may already have holes which need to be preserved, so before it calls <code>SetWindowRgn</code>, it calls <a href="http://msdn.microsoft.com/en-us/library/dd144950(VS.85).aspx" rel="nofollow noreferrer"><code>GetWindowRgn</code></a> to get the current region, then combines the current region with the new one and calls <code>SetWindowRgn</code>:</p>
<pre><code>HRGN rgnOld = CreateRectRgn ( 0, 0, 0, 0 );
int regionType = GetWindowRgn ( hwnd, rgnOld );
</code></pre>
<p>This works fine in XP, but the call to <code>GetWindowRgn</code> fails in Vista. I've tried turning off Aero and elevating my thread's privilege to <code>SE_DEBUG_NAME</code> with <a href="http://msdn.microsoft.com/en-us/library/aa375202(VS.85).aspx" rel="nofollow noreferrer"><code>AdjustTokenPrivileges</code></a>, but neither helps.</p>
<p>GetLastError() doesn't seem to return a valid value for GetWindowRgn -- it returns 0 on one machine and 5 (Access denied) on another.</p>
<p>Can anyone tell me what I'm doing wrong or suggest a different approach? </p>
| [
{
"answer_id": 144856,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p>Are you sure your window <em>has</em> a region? Most top-level windows in XP do, simply because the default theme uses them fo... | 2008/09/27 | [
"https://Stackoverflow.com/questions/144774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23091/"
] | I'm writing a program that uses [`SetWindowRgn`](http://msdn.microsoft.com/en-us/library/dd145102(VS.85).aspx) to make transparent holes in a window that belongs to another process. (This is done only when the user explicitly requests it.)
The program has to assume that the target window may already have holes which need to be preserved, so before it calls `SetWindowRgn`, it calls [`GetWindowRgn`](http://msdn.microsoft.com/en-us/library/dd144950(VS.85).aspx) to get the current region, then combines the current region with the new one and calls `SetWindowRgn`:
```
HRGN rgnOld = CreateRectRgn ( 0, 0, 0, 0 );
int regionType = GetWindowRgn ( hwnd, rgnOld );
```
This works fine in XP, but the call to `GetWindowRgn` fails in Vista. I've tried turning off Aero and elevating my thread's privilege to `SE_DEBUG_NAME` with [`AdjustTokenPrivileges`](http://msdn.microsoft.com/en-us/library/aa375202(VS.85).aspx), but neither helps.
GetLastError() doesn't seem to return a valid value for GetWindowRgn -- it returns 0 on one machine and 5 (Access denied) on another.
Can anyone tell me what I'm doing wrong or suggest a different approach? | Are you sure your window *has* a region? Most top-level windows in XP do, simply because the default theme uses them for round corners... but this is still a bad assumption to be making, and may very well not hold once you get to Vista.
If you haven't set a region yet, and the call fails, use a sensible default (the window rect) and don't let it ruin your life. Now, if `SetWindowRgn()` fails... |
144,810 | <p>Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it's pretty easy), and I thought it would be cool if I were able to make a 'console' on my webpage (as in, you press the ` key like you do in <a href="http://en.wiktionary.org/wiki/first-person_shooter" rel="noreferrer">FPS</a> games, etc.), and then have it Ajax itself back to the server in-order to do stuff.</p>
<p>I originally thought the best way would be to just get the text inside the textarea, and then split it, or should I use the keyup event, convert the keycode returned to an ASCII character, append the character to a string and send the string to the server (then empty the string).</p>
<p>I couldn't find any information on getting text from a textarea, all I got was keyup information. Also, how can I convert the keycode returned to an ASCII character?</p>
| [
{
"answer_id": 144818,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 4,
"selected": false,
"text": "<p>Normally, it's the value property</p>\n\n<pre><code>testArea.value\n</code></pre>\n\n<p>Or is there something I'm missing... | 2008/09/28 | [
"https://Stackoverflow.com/questions/144810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20900/"
] | Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it's pretty easy), and I thought it would be cool if I were able to make a 'console' on my webpage (as in, you press the ` key like you do in [FPS](http://en.wiktionary.org/wiki/first-person_shooter) games, etc.), and then have it Ajax itself back to the server in-order to do stuff.
I originally thought the best way would be to just get the text inside the textarea, and then split it, or should I use the keyup event, convert the keycode returned to an ASCII character, append the character to a string and send the string to the server (then empty the string).
I couldn't find any information on getting text from a textarea, all I got was keyup information. Also, how can I convert the keycode returned to an ASCII character? | Why would you want to convert key strokes to text? Add a button that sends the text inside the textarea to the server when clicked. You can get the text using the value attribute as the poster before has pointed out, or using jQuery's API:
```
$('input#mybutton').click(function() {
var text = $('textarea#mytextarea').val();
//send to server and process response
});
``` |
144,824 | <p>Can you use the bash "getopts" function twice in the same script?</p>
<p>I have a set of options that would mean different things depending on the value of a specific option. Since I can't guarantee that getopts will evaluate that specific option first, I would like to run getopts one time, using only that specific option, then run it a second time using the other options.</p>
| [
{
"answer_id": 144838,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, just reset OPTIND afterwards.</p>\n\n<pre><code>#!/bin/bash\n\nset -- -1\nwhile getopts 1 opt; do\n case \"${... | 2008/09/28 | [
"https://Stackoverflow.com/questions/144824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17925/"
] | Can you use the bash "getopts" function twice in the same script?
I have a set of options that would mean different things depending on the value of a specific option. Since I can't guarantee that getopts will evaluate that specific option first, I would like to run getopts one time, using only that specific option, then run it a second time using the other options. | Yes, just reset OPTIND afterwards.
```
#!/bin/bash
set -- -1
while getopts 1 opt; do
case "${opt}" in
1) echo "Worked!";;
*) exit 1;
esac
done
OPTIND=1
set -- -2
while getopts 2 opt; do
case "${opt}" in
2) echo "Worked!";;
*) exit 1;
esac
done
``` |
144,833 | <p>I know that attributes are extremely useful. There are some predefined ones such as <code>[Browsable(false)]</code> which allows you to hide properties in the properties tab. Here is a good question explaining attributes: <a href="https://stackoverflow.com/questions/20346/c-what-are-attributes">What are attributes in .NET?</a></p>
<p><strong>What are the predefined attributes (and their namespace) you actually use in your projects?</strong> </p>
| [
{
"answer_id": 144841,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 6,
"selected": false,
"text": "<p><code>[Serializable]</code> is used all the time for serializing and deserializing objects to and from external data s... | 2008/09/28 | [
"https://Stackoverflow.com/questions/144833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] | I know that attributes are extremely useful. There are some predefined ones such as `[Browsable(false)]` which allows you to hide properties in the properties tab. Here is a good question explaining attributes: [What are attributes in .NET?](https://stackoverflow.com/questions/20346/c-what-are-attributes)
**What are the predefined attributes (and their namespace) you actually use in your projects?** | `[DebuggerDisplay]` can be really helpful to quickly see customized output of a Type when you mouse over the instance of the Type during debugging. example:
```
[DebuggerDisplay("FirstName={FirstName}, LastName={LastName}")]
class Customer
{
public string FirstName;
public string LastName;
}
```
This is how it should look in the debugger:

Also, it is worth mentioning that `[WebMethod]` attribute with `CacheDuration` property set can avoid unnecessary execution of the web service method. |
144,902 | <p>Recently I had to do some very processing heavy stuff with data stored in a DataSet. It was heavy enough that I ended up using a tool to help identify some bottlenecks in my code. When I was analyzing the bottlenecks, I noticed that although DataSet lookups were not terribly slow (they weren't the bottleneck), it was slower than I expected. I always assumed that DataSets used some sort of HashTable style implementation which would make lookups O(1) (or at least thats what I think HashTables are). The speed of my lookups seemed to be significantly slower than this.</p>
<p>I was wondering if anyone who knows anything about the implementation of .NET's DataSet class would care to share what they know.</p>
<p>If I do something like this : </p>
<pre><code>DataTable dt = new DataTable();
if(dt.Columns.Contains("SomeColumn"))
{
object o = dt.Rows[0]["SomeColumn"];
}
</code></pre>
<p>How fast would the lookup time be for the <code>Contains(...)</code> method, and for retrieving the value to store in <code>Object o</code>? I would have thought it be very fast like a HashTable (assuming what I understand about HashTables is correct) but it doesn't seem like it...</p>
<p>I wrote that code from memory so some things may not be "syntactically correct".</p>
| [
{
"answer_id": 144911,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>I imagine that any lookups would be O(n), as I don't think they would use any type of hashtable, but would actually use mo... | 2008/09/28 | [
"https://Stackoverflow.com/questions/144902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | Recently I had to do some very processing heavy stuff with data stored in a DataSet. It was heavy enough that I ended up using a tool to help identify some bottlenecks in my code. When I was analyzing the bottlenecks, I noticed that although DataSet lookups were not terribly slow (they weren't the bottleneck), it was slower than I expected. I always assumed that DataSets used some sort of HashTable style implementation which would make lookups O(1) (or at least thats what I think HashTables are). The speed of my lookups seemed to be significantly slower than this.
I was wondering if anyone who knows anything about the implementation of .NET's DataSet class would care to share what they know.
If I do something like this :
```
DataTable dt = new DataTable();
if(dt.Columns.Contains("SomeColumn"))
{
object o = dt.Rows[0]["SomeColumn"];
}
```
How fast would the lookup time be for the `Contains(...)` method, and for retrieving the value to store in `Object o`? I would have thought it be very fast like a HashTable (assuming what I understand about HashTables is correct) but it doesn't seem like it...
I wrote that code from memory so some things may not be "syntactically correct". | Via [Reflector](http://www.red-gate.com/products/reflector/) the steps for DataRow["ColumnName"] are:
1. Get the DataColumn from ColumnName. Uses the row's DataColumnCollection["ColumnName"]. Internally, DataColumnCollection stores its DataColumns in a Hastable. O(1)
2. Get the DataRow's row index. The index is stored in an internal member. O(1)
3. Get the DataColumn's value at the index using DataColumn[index]. DataColumn stores its data in a System.Data.Common.DataStorage (internal, abstract) member:
return dataColumnInstance.\_storage.Get(recordIndex);
A sample concrete implementation is System.Data.Common.StringStorage (internal, sealed). StringStorage (and the other concrete DataStorages I checked) store their values in an array. Get(recordIndex) simply grabs the object in the value array at the recordIndex. O(1)
So overall you're O(1) but that doesn't mean the hashing and function calling during the operation is without cost. It just means it doesn't cost more as the number of DataRows or DataColumns increases.
Interesting that DataStorage uses an array for values. Can't imagine that's easy to rebuild when you add or remove rows. |
144,980 | <p>Greetings.</p>
<p>I'm trying to implement some multithreaded code in an application. The purpose of this code is to validate items that the database gives it. Validation can take quite a while (a few hundred ms to a few seconds), so this process needs to be forked off into its own thread for each item.</p>
<p>The database may give it 20 or 30 items a second in the beginning, but that begins to decline rapidly, eventually reaching about 65K items over 24 hours, at which point the application exits.</p>
<p>I'd like it if anyone more knowledgeable could take a peek at my code and see if there's any obvious problems. No one I work with knows multithreading, so I'm really just on my own, on this one.</p>
<p>Here's the code. It's kinda long but should be pretty clear. Let me know if you have any feedback or advice. Thanks!</p>
<pre><code>public class ItemValidationService
{
/// <summary>
/// The object to lock on in this class, for multithreading purposes.
/// </summary>
private static object locker = new object();
/// <summary>Items that have been validated.</summary>
private HashSet<int> validatedItems;
/// <summary>Items that are currently being validated.</summary>
private HashSet<int> validatingItems;
/// <summary>Remove an item from the index if its links are bad.</summary>
/// <param name="id">The ID of the item.</param>
public void ValidateItem(int id)
{
lock (locker)
{
if
(
!this.validatedItems.Contains(id) &&
!this.validatingItems.Contains(id)
){
ThreadPool.QueueUserWorkItem(sender =>
{
this.Validate(id);
});
}
}
} // method
private void Validate(int itemId)
{
lock (locker)
{
this.validatingItems.Add(itemId);
}
// *********************************************
// Time-consuming routine to validate an item...
// *********************************************
lock (locker)
{
this.validatingItems.Remove(itemId);
this.validatedItems.Add(itemId);
}
} // method
} // class
</code></pre>
| [
{
"answer_id": 144991,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 2,
"selected": false,
"text": "<p>The thread pool is a convenient choice if you have <em>light weight</em> sporadic processing that isn't time sensitive.... | 2008/09/28 | [
"https://Stackoverflow.com/questions/144980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] | Greetings.
I'm trying to implement some multithreaded code in an application. The purpose of this code is to validate items that the database gives it. Validation can take quite a while (a few hundred ms to a few seconds), so this process needs to be forked off into its own thread for each item.
The database may give it 20 or 30 items a second in the beginning, but that begins to decline rapidly, eventually reaching about 65K items over 24 hours, at which point the application exits.
I'd like it if anyone more knowledgeable could take a peek at my code and see if there's any obvious problems. No one I work with knows multithreading, so I'm really just on my own, on this one.
Here's the code. It's kinda long but should be pretty clear. Let me know if you have any feedback or advice. Thanks!
```
public class ItemValidationService
{
/// <summary>
/// The object to lock on in this class, for multithreading purposes.
/// </summary>
private static object locker = new object();
/// <summary>Items that have been validated.</summary>
private HashSet<int> validatedItems;
/// <summary>Items that are currently being validated.</summary>
private HashSet<int> validatingItems;
/// <summary>Remove an item from the index if its links are bad.</summary>
/// <param name="id">The ID of the item.</param>
public void ValidateItem(int id)
{
lock (locker)
{
if
(
!this.validatedItems.Contains(id) &&
!this.validatingItems.Contains(id)
){
ThreadPool.QueueUserWorkItem(sender =>
{
this.Validate(id);
});
}
}
} // method
private void Validate(int itemId)
{
lock (locker)
{
this.validatingItems.Add(itemId);
}
// *********************************************
// Time-consuming routine to validate an item...
// *********************************************
lock (locker)
{
this.validatingItems.Remove(itemId);
this.validatedItems.Add(itemId);
}
} // method
} // class
``` | The thread pool is a convenient choice if you have *light weight* sporadic processing that isn't time sensitive. However, I recall reading on MSDN that it's not appropriate for large scale processing of this nature.
I used it for something quite similar to this and regret it. I took a worker-thread approach in subsequent apps and am much happier with the level of control I have.
My favorite pattern in the worker-thread model is to create a master thread which holds a queue of tasks items. Then fork a bunch of workers that pop items off that queue to process. I use a blocking queue so that when there are no items the process, the workers just block until something is pushed onto the queue. In this model, the master thread produces work items from some source (db, etc.) and the worker threads consume them. |
144,983 | <p>Every time I start Emacs I see a page of help text and a bunch of messages suggesting that I try the tutorial. How do I stop this from happening?</p>
| [
{
"answer_id": 144984,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 4,
"selected": true,
"text": "<p>Put the following in your <code>.emacs</code>:</p>\n\n<pre>\n(setq inhibit-startup-message t)\n(setq inhibit-startup-echo-a... | 2008/09/28 | [
"https://Stackoverflow.com/questions/144983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11138/"
] | Every time I start Emacs I see a page of help text and a bunch of messages suggesting that I try the tutorial. How do I stop this from happening? | Put the following in your `.emacs`:
```
(setq inhibit-startup-message t)
(setq inhibit-startup-echo-area-message t)
``` |
145,006 | <p>Very simply put, I have the following code snippet:</p>
<pre><code>FILE* test = fopen("C:\\core.u", "w");
printf("Filepointer at: %d\n", ftell(test));
fwrite(data, size, 1, test);
printf("Written: %d bytes.\n", size);
fseek(test, 0, SEEK_END);
printf("Filepointer is now at %d.\n", ftell(test));
fclose(test);
</code></pre>
<p>and it outputs:</p>
<pre><code>Filepointer at: 0
Written: 73105 bytes.
Filepointer is now at 74160.
</code></pre>
<p>Why is that? Why does the number of bytes written not match the file pointer?</p>
| [
{
"answer_id": 145013,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": true,
"text": "<p>Since you're opening the file in text mode, it will convert end-of-line markers, such as LF, into CR/LF.</p>\n\n<p>Thi... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Very simply put, I have the following code snippet:
```
FILE* test = fopen("C:\\core.u", "w");
printf("Filepointer at: %d\n", ftell(test));
fwrite(data, size, 1, test);
printf("Written: %d bytes.\n", size);
fseek(test, 0, SEEK_END);
printf("Filepointer is now at %d.\n", ftell(test));
fclose(test);
```
and it outputs:
```
Filepointer at: 0
Written: 73105 bytes.
Filepointer is now at 74160.
```
Why is that? Why does the number of bytes written not match the file pointer? | Since you're opening the file in text mode, it will convert end-of-line markers, such as LF, into CR/LF.
This is likely if you're running on Windows (and you probably are, given that your file name starts with `"c:\"`).
If you open the file in `"wb"` mode, I suspect you'll find the numbers are identical:
```
FILE* test = fopen("C:\\core.u", "wb");
```
The C99 standard has this to say in `7.19.5.3 The fopen function`:
>
> The argument mode points to a string. If the string is one of the following, the file is
> open in the indicated mode. Otherwise, the behaviour is undefined.
>
>
> `r` open text file for reading
>
> `w` truncate to zero length or create text file for writing
>
> `a` append; open or create text file for writing at end-of-file
>
> `rb` open binary file for reading
>
> `wb` truncate to zero length or create binary file for writing
>
> `ab` append; open or create binary file for writing at end-of-file
>
> `r+` open text file for update (reading and writing)
>
> `w+` truncate to zero length or create text file for update
>
> `a+` append; open or create text file for update, writing at end-of-file
>
> `r+b` or `rb+` open binary file for update (reading and writing)
>
> `w+b` or `wb+` truncate to zero length or create binary file for update
>
> `a+b` or `ab+` append; open or create binary file for update, writing at end-of-file
>
>
>
You can see they distinguish between `w` and `wb`. I don't believe an implementation is *required* to treat the two differently but it's usually safer to use binary mode for binary data. |
145,025 | <p>I'm implementing a secure WCF service. Authentication is done using username / password or Windows credentials. The service is hosted in a Windows Service process. Now, I'm trying to find out the best way to implement <em>authorization</em> for each service operation.</p>
<p>For example, consider the following method:</p>
<pre><code>public EntityInfo GetEntityInfo(string entityId);
</code></pre>
<p>As you may know, in WCF, there is an OperationContext object from which you can retrieve the security credentials passed in by the caller/client. Now,<em>authentication</em> would have already finished by the time the first line in the method is called. However, how do we implement authorization if the decision depends on the input data itself? For example, in the above case, say 'admin' users(whose permissions etc are stored in a database), are allowed to get entity info, and other users should not be allowed... where do we put the authorization checks?</p>
<p>Say we put it in the first line of the method like so:</p>
<pre><code>CheckAccessPermission(PermissionType.GetEntity, user, entityId) //user is pulled from the current OperationContext
</code></pre>
<p>Now, there are a couple of questions:</p>
<ol>
<li><p>Do we validate the entityId (for example check null / empty value etc) BEFORE the authorization check or INSIDE the authorization check? In other words, if authorization checks should be included in every method, is that a good pattern? Which should happen first - argument validation or authorization?</p></li>
<li><p>How do we unit test a WCF service when authorization checks are all over the place like this, and we don't have an OperationContext in the unit test!? (Assuming I'm tryin to test this service class implementation directly without any of the WCF setup).</p></li>
</ol>
<p>Any ideas guys?</p>
| [
{
"answer_id": 145160,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 3,
"selected": false,
"text": "<p>For question 1, it's best to perform authorization first. That way, you don't leak validation error messages back t... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6995/"
] | I'm implementing a secure WCF service. Authentication is done using username / password or Windows credentials. The service is hosted in a Windows Service process. Now, I'm trying to find out the best way to implement *authorization* for each service operation.
For example, consider the following method:
```
public EntityInfo GetEntityInfo(string entityId);
```
As you may know, in WCF, there is an OperationContext object from which you can retrieve the security credentials passed in by the caller/client. Now,*authentication* would have already finished by the time the first line in the method is called. However, how do we implement authorization if the decision depends on the input data itself? For example, in the above case, say 'admin' users(whose permissions etc are stored in a database), are allowed to get entity info, and other users should not be allowed... where do we put the authorization checks?
Say we put it in the first line of the method like so:
```
CheckAccessPermission(PermissionType.GetEntity, user, entityId) //user is pulled from the current OperationContext
```
Now, there are a couple of questions:
1. Do we validate the entityId (for example check null / empty value etc) BEFORE the authorization check or INSIDE the authorization check? In other words, if authorization checks should be included in every method, is that a good pattern? Which should happen first - argument validation or authorization?
2. How do we unit test a WCF service when authorization checks are all over the place like this, and we don't have an OperationContext in the unit test!? (Assuming I'm tryin to test this service class implementation directly without any of the WCF setup).
Any ideas guys? | For question 1, absolutely do authorization first. No code (within your control) should execute before authorization to maintain the tightest security. Paul's example above is excellent.
For question 2, you could handle this by subclassing your concrete service implementation. Make the true business logic implementation an abstract class with an abstract "CheckPermissions" method as you mention above. Then create 2 subclasses, one for WCF use, and one (very isolated in a non deployed DLL) which returns true (or whatever you'd like it to do in your unit testing).
Example (note, these shouldn't be in the same file or even DLL though!):
```
public abstract class MyServiceImpl
{
public void MyMethod(string entityId)
{
CheckPermissions(entityId);
//move along...
}
protected abstract bool CheckPermissions(string entityId);
}
public class MyServiceUnitTest
{
private bool CheckPermissions(string entityId)
{
return true;
}
}
public class MyServiceMyAuth
{
private bool CheckPermissions(string entityId)
{
//do some custom authentication
return true;
}
}
```
Then your WCF deployment uses the class "MyServiceMyAuth", and you do your unit testing against the other. |
145,052 | <p>Is there any libraries that would allow me to use the same known notation as we use in BeanUtils for extracting POJO parameters, but for easily replacing placeholders in a string?</p>
<p>I know it would be possible to roll my own, using BeanUtils itself or other libraries with similar features, but I didn't want to reinvent the wheel.</p>
<p>I would like to take a String as follows:</p>
<pre><code>String s = "User ${user.name} just placed an order. Deliver is to be
made to ${user.address.street}, ${user.address.number} - ${user.address.city} /
${user.address.state}";
</code></pre>
<p>And passing one instance of the User class below:</p>
<pre><code>public class User {
private String name;
private Address address;
// (...)
public String getName() { return name; }
public Address getAddress() { return address; }
}
public class Address {
private String street;
private int number;
private String city;
private String state;
public String getStreet() { return street; }
public int getNumber() { return number; }
// other getters...
}
</code></pre>
<p>To something like:</p>
<pre><code>System.out.println(BeanUtilsReplacer.replaceString(s, user));
</code></pre>
<p>Would get each placeholder replaced with actual values.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 145156,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 1,
"selected": false,
"text": "<p>Spring Framework should have a feature that does this (see Spring JDBC example below). If you can use groovy (just add the g... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14540/"
] | Is there any libraries that would allow me to use the same known notation as we use in BeanUtils for extracting POJO parameters, but for easily replacing placeholders in a string?
I know it would be possible to roll my own, using BeanUtils itself or other libraries with similar features, but I didn't want to reinvent the wheel.
I would like to take a String as follows:
```
String s = "User ${user.name} just placed an order. Deliver is to be
made to ${user.address.street}, ${user.address.number} - ${user.address.city} /
${user.address.state}";
```
And passing one instance of the User class below:
```
public class User {
private String name;
private Address address;
// (...)
public String getName() { return name; }
public Address getAddress() { return address; }
}
public class Address {
private String street;
private int number;
private String city;
private String state;
public String getStreet() { return street; }
public int getNumber() { return number; }
// other getters...
}
```
To something like:
```
System.out.println(BeanUtilsReplacer.replaceString(s, user));
```
Would get each placeholder replaced with actual values.
Any ideas? | Rolling your own using BeanUtils wouldn't take too much wheel reinvention (assuming you want it to be as basic as asked for). This implementation takes a Map for replacement context, where the map key should correspond to the first portion of the variable lookup paths given for replacement.
```
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsReplacer
{
private static Pattern lookupPattern = Pattern.compile("\\$\\{([^\\}]+)\\}");
public static String replaceString(String input, Map<String, Object> context)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
int position = 0;
StringBuffer result = new StringBuffer();
Matcher m = lookupPattern.matcher(input);
while (m.find())
{
result.append(input.substring(position, m.start()));
result.append(BeanUtils.getNestedProperty(context, m.group(1)));
position = m.end();
}
if (position == 0)
{
return input;
}
else
{
result.append(input.substring(position));
return result.toString();
}
}
}
```
Given the variables provided in your question:
```
Map<String, Object> context = new HashMap<String, Object>();
context.put("user", user);
System.out.println(BeanUtilsReplacer.replaceString(s, context));
``` |
145,056 | <p>A friend came across a quadratic Bézier curve function in his codebase that used a gigantic rats nest of a switch table to perform the computation. He challenged me to find a single, short expression that would allow him to replace the gigantic block of code.</p>
<p>In attempting to satisfy two different curiosities, I thought I'd try implementing the function in OCaml. I'm a very novice OCaml programmer and I'm also unfamiliar with the function and this <em>specific</em> implementation is hard to come by via Google.</p>
<p>Critiques on both the function's performance/correctness as well as its implementation are very much appreciated.</p>
<p>Implementation of <a href="http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B.C3.A9zier_curves" rel="nofollow noreferrer">Quadratic Bézier Curve</a>:</p>
<pre><code>let rec b2 n =
let p1 = -10. in
let p2 = 10. in
let q = n*.n in
let rec b2i n i hd =
if i > n then
List.rev hd
else
let t = i /. n in
b2i n (i+.1.) ((((1.-.t)**2.)*.p1+.(2.*.t*.(1.-.t)*.q)+.(t**2.)*.p2) :: hd)
in
b2i n 0. []
;;
let floatprint lst =
List.iter (fun f -> Printf.printf "%f; " f) lst ;;
floatprint (b2 8.);;
</code></pre>
| [
{
"answer_id": 145142,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "<p>I have two suggestions:</p>\n<p>You should call <code>List.rev</code> after <code>b2i</code> returns so ocaml can exploit... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
] | A friend came across a quadratic Bézier curve function in his codebase that used a gigantic rats nest of a switch table to perform the computation. He challenged me to find a single, short expression that would allow him to replace the gigantic block of code.
In attempting to satisfy two different curiosities, I thought I'd try implementing the function in OCaml. I'm a very novice OCaml programmer and I'm also unfamiliar with the function and this *specific* implementation is hard to come by via Google.
Critiques on both the function's performance/correctness as well as its implementation are very much appreciated.
Implementation of [Quadratic Bézier Curve](http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B.C3.A9zier_curves):
```
let rec b2 n =
let p1 = -10. in
let p2 = 10. in
let q = n*.n in
let rec b2i n i hd =
if i > n then
List.rev hd
else
let t = i /. n in
b2i n (i+.1.) ((((1.-.t)**2.)*.p1+.(2.*.t*.(1.-.t)*.q)+.(t**2.)*.p2) :: hd)
in
b2i n 0. []
;;
let floatprint lst =
List.iter (fun f -> Printf.printf "%f; " f) lst ;;
floatprint (b2 8.);;
``` | b2 isn't recursive, so no need for [let rec b2 n =]. Since n never changes, no need to have it as argument to b2i, just use n from the enclosing scope. Your inner function should depend on p0, p1 and p2, but I see it depending on -10., n\*\*2 and 10. The function also has the form of a map from [ 0.0; 1.0; 2.0; ...; n.0] to the final values. Could you write it:
```
let b i =
let t = i /. n in
let tminus = (1.-.t) in
(tminus *. tminus *. p0) +. (2. *. t *. tminus *. p1) +. (t *. t * p2)
in
List.map b ([generate list 1.0; 2.0; ... n.0])
```
A function to generate the list 1.0...n.0 could be: (for small n)
```
let rec count m n = if m > n then [] else m :: (count (m+.1.) n)
``` |
145,096 | <p>I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this?</p>
| [
{
"answer_id": 145098,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 7,
"selected": true,
"text": "<p><strong>Overview:</strong></p>\n\n<p>It is almost true that C++ is a superset of C, and your professor is correct i... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23126/"
] | I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this? | **Overview:**
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function). C++ does change the definition of some terms in C such as structs, although still in a superset way.
**Examples of why it is not a strict superset:**
[This Wikipedia article](http://en.wikipedia.org/wiki/C%2B%2B) has a couple good examples of such a differences:
>
> One commonly encountered difference is
> that C allows implicit conversion from
> void\* to other pointer types, but C++
> does not. So, the following is valid C
> code:
>
>
>
> ```
> int *i = malloc(sizeof(int) * 5);
>
> ```
>
> ... but to make it work in both C and
> C++ one would need to use an explicit
> cast:
>
>
>
> ```
> int *i = (int *) malloc(sizeof(int) * 5)
>
> ```
>
> Another common portability issue is
> that C++ defines many new keywords,
> such as new and class, that may be
> used as identifiers (e.g. variable
> names) in a C program.
>
>
>
[This wikipedia article](http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B) has further differences as well:
>
> C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:
>
>
>
```
void fn(void)
{
goto flack;
int i = 1;
flack:
;
}
```
**What should you learn first?**
You should learn C++ first, not because learning C first will hurt you, not because you will have to unlearn anything (you won't), but because there is no benefit in learning C first. You will eventually learn just about everything about C anyway because it is more or less contained in C++. |
145,154 | <p>My singleton accessor method is usually some variant of:</p>
<pre><code>static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
</code></pre>
<p>What could I be doing to improve this?</p>
| [
{
"answer_id": 145164,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 7,
"selected": false,
"text": "<pre><code>@interface MySingleton : NSObject\n{\n}\n\n+ (MySingleton *)sharedSingleton;\n@end\n\n@implementation MySin... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23113/"
] | My singleton accessor method is usually some variant of:
```
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
```
What could I be doing to improve this? | Another option is to use the `+(void)initialize` method. From the documentation:
>
> The runtime sends `initialize` to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the `initialize` message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
>
>
>
So you could do something akin to this:
```
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}
``` |
145,169 | <p>I'm using the current version of restful_authentication that is found on github and I'm having a bunch of strange session issues. The server seems to be somehow assigning sessions to users it shouldn't be. This only happens when crossing the logged out/logged in barrier.</p>
<p>Here's an example. With no sessions active on the server, I log in to an account with user A. On another machine, I log in with user B. Then when logging out of user B, sometime after the logout redirect happens, I will be logged in as user A. From this point, I can continue to navigate the site as if I had logged in as that user! Something I've observed via the logs is that when this hijack happens, the session IDs are not the same. User A is logged in in both sessions, but the session ID's are completely different. This is just one example of what might happen. I can't reproduce the issue reliably as it is seemingly random. </p>
<p>It doesn't seem to be a symptom of the environment or the server it's running on. I can reproduce the problem using both mongrel and passenger. I've also seen it in development and production. I am using db-based sessions in this application and it is running on Rails 2.1.1. I applied the stateful option when calling the generator. Otherwise no other modifications have been made to how sessions are handled.</p>
<p>Update
Here is the offending method which came directly from restful_authentication.</p>
<pre><code># Accesses the current user from the session.
# Future calls avoid the database because nil is not equal to false.
def current_user
@current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false
end
</code></pre>
| [
{
"answer_id": 147032,
"author": "Nathan de Vries",
"author_id": 11109,
"author_profile": "https://Stackoverflow.com/users/11109",
"pm_score": 2,
"selected": false,
"text": "<p>This can happen if you (or those who wrote restful_authentication) are caching the current user in a class vari... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23128/"
] | I'm using the current version of restful\_authentication that is found on github and I'm having a bunch of strange session issues. The server seems to be somehow assigning sessions to users it shouldn't be. This only happens when crossing the logged out/logged in barrier.
Here's an example. With no sessions active on the server, I log in to an account with user A. On another machine, I log in with user B. Then when logging out of user B, sometime after the logout redirect happens, I will be logged in as user A. From this point, I can continue to navigate the site as if I had logged in as that user! Something I've observed via the logs is that when this hijack happens, the session IDs are not the same. User A is logged in in both sessions, but the session ID's are completely different. This is just one example of what might happen. I can't reproduce the issue reliably as it is seemingly random.
It doesn't seem to be a symptom of the environment or the server it's running on. I can reproduce the problem using both mongrel and passenger. I've also seen it in development and production. I am using db-based sessions in this application and it is running on Rails 2.1.1. I applied the stateful option when calling the generator. Otherwise no other modifications have been made to how sessions are handled.
Update
Here is the offending method which came directly from restful\_authentication.
```
# Accesses the current user from the session.
# Future calls avoid the database because nil is not equal to false.
def current_user
@current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false
end
``` | I don't know if this is so much of an answer as it is a work around. All I did was switch over to cookie based sessions and everything is working smoothly. |
145,175 | <p>Right now I write expressions in the <code>*scratch*</code> buffer and test them by evaluating with <kbd>C-x</kbd> <kbd>C-e</kbd>. I would really appreciate having an interactive interpreter like SLIME or irb, in which I could test Emacs Lisp expressions.</p>
| [
{
"answer_id": 145205,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 1,
"selected": false,
"text": "<p>In the <code>*scratch*</code> buffer, just type C-j to evaluate the expression before point.</p>\n"
},
{
"answer_id":... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21998/"
] | Right now I write expressions in the `*scratch*` buffer and test them by evaluating with `C-x` `C-e`. I would really appreciate having an interactive interpreter like SLIME or irb, in which I could test Emacs Lisp expressions. | It's easy to evaluate Lisp expressions in Inferior Emacs-Lisp Mode:
```
M-x ielm
```
You can read more about this feature in the [Emacs manual section on "Lisp Interaction"](http://www.gnu.org/software/emacs/manual/html_mono/emacs.html#Lisp-Interaction) |
145,209 | <p>I want to mount some internal and external NTFS drives in CentOS 5.2, preferably automatically upon boot-up. Doesn't matter if it's read/write or read-only, but read/write would be preferred, if it's safe.</p>
<p>Edit: Thanks for all answers, I summarized them below =)</p>
| [
{
"answer_id": 145213,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 2,
"selected": false,
"text": "<p>You should already have ntfs available, read-write support is now pretty reliable.<br>\nYou can test it with \"m... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18406/"
] | I want to mount some internal and external NTFS drives in CentOS 5.2, preferably automatically upon boot-up. Doesn't matter if it's read/write or read-only, but read/write would be preferred, if it's safe.
Edit: Thanks for all answers, I summarized them below =) | To answer my own question: PostMan and mgb led me to the right path, but their answers did not contain complete solution.
Note: A short manual/wiki on this question is here: <http://wiki.centos.org/TipsAndTricks/NTFSPartitions>
So, I am using a fresh, bare install of CentOS 5.2 with latest updates. First of all, I ran the `su` command to avoid any permission issues.
I created mount points for a couple of external NTFS drives:
```
mkdir /mnt/iomega80
mkdir /mnt/iogear250
```
I had to use the fdisk command, but it wasn't in my system. Here's what installs it:
```
yum install util-linux
```
Then I ran `/sbin/fdisk -l` and found the device names:
```
Disk /dev/sdc: 250.0 GB, 250059350016 bytes
255 heads, 63 sectors/track, 30401 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks Id System
**/dev/sdc1** * 1 30401 244196001 7 HPFS/NTFS
Disk /dev/sdd: 82.3 GB, 82348278272 bytes
255 heads, 63 sectors/track, 10011 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks Id System
**/dev/sdd1** * 1 10011 80413326 7 HPFS/NTFS
```
For me, they are `/dev/sdc1` and `/dev/sdd1`.
I had to install NTFS-3G, a package that enables NTFS support on CentOS. To install NTFS-3G, I first had to include RPMFORGE in YUM repository list.
To include RPMFORGE in YUM repository list, I used these instructions: <http://rpmrepo.org/RPMforge/Using>. For my system, the two commands I had to run were:
```
wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.3.6-1.el5.rf.i386.rpm
rpm -Uhv rpmforge-release-0.3.6-1.el5.rf.i386.rpm
```
Finally, I installed NTFS-3G using this YUM command:
```
yum install fuse fuse-ntfs-3g dkms dkms-fuse
```
At last, I could use the mount command to mount the filesystems:
```
mount -t ntfs-3g /dev/sdc1 /mnt/iogear250
mount -t ntfs-3g /dev/sdd1 /mnt/iomega80
```
By adding these two lines to `/etc/fstab`, like previous answers suggested, I got the drives to mount upon boot-up:
```
/dev/sdc1 /mnt/iogear250 ntfs-3g rw,umask=0000,defaults 0 0
/dev/sdd1 /mnt/iomega80 ntfs-3g rw,umask=0000,defaults 0 0
``` |
145,241 | <h2><strong>Edit: I have solved this by myself. See <a href="https://stackoverflow.com/questions/145241/change-the-value-of-a-text-box-to-its-current-order-in-a-sortable-tab/145388#145388">my answer below</a></strong></h2>
<p>I have set up a nice sortable table with jQuery and it is quite nice. But now i want to extend it.</p>
<p>Each table row has a text box, and i want i am after is to, every time a row is dropped, the text boxes update to reflect the order of the text boxes. <strong>E.g. The text box up the top always has the value of '1', the second is always '2' and so on.</strong></p>
<p>I am using jQuery and the <a href="http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/" rel="nofollow noreferrer">Table Drag and Drop JQuery plugin</a></p>
<h3>Code</h3>
<p><strong>Javascript:</strong></p>
<pre><code><script type = "text/javascript" >
$(document).ready(function () {
$("#table-2").tableDnD({
onDrop: function (table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Order: ";
for (var i = 0; i < rows.length; i++) {
debugStr += rows[i].id + ", ";
}
console.log(debugStr)
document.forms['productform'].sort1.value = debugStr;
document.forms['productform'].sort2.value = debugStr;
document.forms['productform'].sort3.value = debugStr;
document.forms['productform'].sort4.value = debugStr;
},
});
});
</script>
</code></pre>
<p><strong>HTML Table:</strong></p>
<pre class="lang-html prettyprint-override"><code><form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr>
<td>Product</td>
<td>Order</td>
</tr>
</thead>
<tbody>
<tr class="row1" id="Pol">
<td><a href="1/">Pol</a></td>
<td><input type="textbox" name="sort1"/></td>
</tr>
<tr class="row2" id="Evo">
<td><a href="2/">Evo</a></td>
<td><input type="textbox" name="sort2"/></td>
</tr>
<tr class="row3" id="Kal">
<td><a href="3/">Kal</a></td>
<td><input type="textbox" name="sort3"/></td>
</tr>
<tr class="row4" id="Lok">
<td><a href="4/">Lok</a></td>
<td><input type="textbox" name="sort4"/></td>
</tr>
</tbody>
</table>
</form>
</code></pre>
| [
{
"answer_id": 145284,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 0,
"selected": false,
"text": "<p>Hmmm..\nI think you want to do something like this:</p>\n\n<pre><code>$(\"input:text\", \"#table-2\").each( function(... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] | **Edit: I have solved this by myself. See [my answer below](https://stackoverflow.com/questions/145241/change-the-value-of-a-text-box-to-its-current-order-in-a-sortable-tab/145388#145388)**
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
I have set up a nice sortable table with jQuery and it is quite nice. But now i want to extend it.
Each table row has a text box, and i want i am after is to, every time a row is dropped, the text boxes update to reflect the order of the text boxes. **E.g. The text box up the top always has the value of '1', the second is always '2' and so on.**
I am using jQuery and the [Table Drag and Drop JQuery plugin](http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/)
### Code
**Javascript:**
```
<script type = "text/javascript" >
$(document).ready(function () {
$("#table-2").tableDnD({
onDrop: function (table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Order: ";
for (var i = 0; i < rows.length; i++) {
debugStr += rows[i].id + ", ";
}
console.log(debugStr)
document.forms['productform'].sort1.value = debugStr;
document.forms['productform'].sort2.value = debugStr;
document.forms['productform'].sort3.value = debugStr;
document.forms['productform'].sort4.value = debugStr;
},
});
});
</script>
```
**HTML Table:**
```html
<form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr>
<td>Product</td>
<td>Order</td>
</tr>
</thead>
<tbody>
<tr class="row1" id="Pol">
<td><a href="1/">Pol</a></td>
<td><input type="textbox" name="sort1"/></td>
</tr>
<tr class="row2" id="Evo">
<td><a href="2/">Evo</a></td>
<td><input type="textbox" name="sort2"/></td>
</tr>
<tr class="row3" id="Kal">
<td><a href="3/">Kal</a></td>
<td><input type="textbox" name="sort3"/></td>
</tr>
<tr class="row4" id="Lok">
<td><a href="4/">Lok</a></td>
<td><input type="textbox" name="sort4"/></td>
</tr>
</tbody>
</table>
</form>
``` | Hardnrg in #jquery ended up solving it for me.
It involved adding an id="" to each input:
```
<form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr><td>Product</td> <td>Order</td></tr>
</thead>
<tbody>
<tr class="row1" id="Pol"> <td><a href="1/">Pol</a></td> <td><input id="Pol_field" type="textbox" name="sort1"/></td> </tr>
<tr class="row2" id="Evo"> <td><a href="2/">Evo</a></td> <td><input id="Evo_field" type="textbox" name="sort2"/></td> </tr>
<tr class="row3" id="Kal"> <td><a href="3/">Kal</a></td> <td><input id="Kal_field" type="textbox" name="sort3"/></td> </tr>
<tr class="row4" id="Lok"> <td><a href="4/">Lok</a></td> <td><input id="Lok_field" type="textbox" name="sort4"/></td> </tr>
</tbody>
</table>
</form>
```
And add this js to the OnDrop event:
```
for (var i=0; i < rows.length; i++) {
$('#' + rows[i].id + "_field").val(i+1);
}
```
Easy peasy! |